Decisions, Loops & FunctionsCore· 35 min read

Functions

Package reusable code into functions with def in Python — parameters, return values, and why functions keep your programs clean and DRY.

What you will learn

  • Define functions with def
  • Use parameters and return
  • Reuse your code

def defines a function

A function is a named, reusable block of code. You define it once (write the steps) and then call it whenever you need it, as many times as you like. The word def starts a definition, the name comes next, and the brackets hold any parameters — values you hand in each time.

A function with a parameter and return
def greet(name):
    return "Hello, " + name + "!"

print(greet("Asha"))
print(greet("Ravi"))

Here is how this runs:

  1. def greet(name): defines a function called greet that expects one input, called name. The indented line is its body and does not run yet — it is just saved for later.
  2. Inside, return hands a value back to whoever called the function — here it builds and returns the text "Hello, " + name + "!" (+ joins strings together).
  3. greet("Asha") calls the function with name set to "Asha". It returns "Hello, Asha!", which print then shows.
  4. The second call reuses the same function with "Ravi" — that is the whole point of a function: write it once, call it again and again.

Note: Output: Hello, Asha! Hello, Ravi!

A function can take more than one parameter, and return can hand back the result of a calculation:

Returning a value
def add(a, b):
    return a + b

print(add(5, 3))   # 8

This function expects two inputs, a and b. When you call add(5, 3), a becomes 5 and b becomes 3, the function adds them and returns 8, and print displays that result. Without return the function would do the sum but hand nothing back, so there would be nothing to print.

Note: Output: 8

Tip: Functions keep your code DRY (Do not Repeat Yourself). Write the logic once, call it many times.

Q. Which keyword defines a function in Python?

Answer: def starts a function definition, e.g. def greet(name):

✍️ Practice

  1. Write a function that returns the square of a number.
  2. Write a function that returns the bigger of two numbers.

🏠 Homework

  1. Write a function that takes a price and quantity and returns the total.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →