Lesson 21: Functions: defining, calling and returning values
A function is a named block of code you can run as often as you like. def creates it, a call runs it, and return sends a value back to whoever called.
In short
- A function is a named block of code that runs only when you call it.
- `def name(parameters):` declares it, and `name(arguments)` runs it.
- `return` sends a value back and ends the function immediately; without it the function returns None.
- A docstring in triple quotes describes the function and shows up in `help()`.
0
times the body runs until you call the function
Python docs
1
value return can send back, unless it is a tuple
Python docs
What a function is
A function is a named block of code that does one job. Nothing inside it happens until the function is called. This is what lets you write the logic once and use it many times, in many places.
A parameter is a name in the definition; an argument is the value you pass in the call.
The program
# functions.py — one job per function
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area(4, 5)) # 20
print(area(7, 3)) # 21
def greet(name):
print("Hello", name)
result = greet("Asha") # the function prints
print(result) # None: greet returns nothing
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, average = stats([45, 67, 89])
print(low, high, round(average, 2))
How it works, step by step
def area(width, height):declares the function. The body is indented under the colon.- The docstring on the next line is a description, not code. It is available later through
help(area). area(4, 5)passes 4 towidthand 5 toheight, runs the body, and gives the returned 20 back toprint().greet()prints but has noreturn, so its result isNone. Printing and returning are different things.stats()returns three values separated by commas, which Python packs into a tuple. The caller unpacks them into three names.
What it prints
20 21 Hello Asha None 45 89 67.0
print or return?
print() | return | |
|---|---|---|
| Effect | Shows text on screen | Sends a value back to the caller |
| Reusable in a calculation | No | Yes |
| When the function has no return | — | The result is None |
Rule of thumb: return the answer, print it at the place that called the function. That keeps the function testable and usable inside other functions.
Common mistakes
- Printing inside the function and then trying to use the result:
x = greet("Asha") + 1fails, because the result isNone. - Forgetting the brackets.
arearefers to the function;area(4, 5)calls it. - Indenting the body incorrectly, so lines that should run on every call end up running once at definition time.
- Defining a function after the line that calls it in a script. Define first, call later.
Practice
Try these before moving on. Each one uses only what this lesson covered.
- Program 10: write a function that checks whether a number is prime, and call it for 7, 9 and 29.
- Program 13: write a function with two parameters that returns the larger of them, and call it three times.
- Write a function `is_even(n)` that returns True or False, then print the result for 4 and 7.
- Write a function that takes a list of marks and returns the average.
Sources
Frequently asked questions
What is a function in Python?
A named block of code that performs one task and runs only when called. It can take parameters, return a value, and be reused anywhere in the program.
What is the difference between a parameter and an argument?
A parameter is the name written in the function definition. An argument is the actual value passed when the function is called. In def area(w, h), w and h are parameters; in area(4, 5), 4 and 5 are arguments.
What happens if a function has no return statement?
It returns None. The work may still have happened, for example printing text, but there is no value to store or calculate with.
Can a function return more than one value?
Yes. return a, b returns a tuple, and the caller can unpack it with x, y = function(). It is one value that happens to contain several.