Python course · Module 5: Functions · Lesson 22 of 63
Quick answer: A function is a named block of code that you can run again and again. Define it with def, a name, brackets and a colon, then call it with its name and brackets: greet(). Values passed in the brackets go into its parameters, and return sends a result back to the caller, for example def line_total(price, quantity): return price * quantity. A function with no return gives back None.
In this lesson you will learn:
- how to define a function with
defand call it - the difference between parameters and arguments
- why
returnis not the same asprint() - how to return several values and unpack them
- why you sometimes get
None, and how to write a docstring
Before you start: finish Lesson 21, Python List, Dict and Set Comprehensions with if, else and Nested Loops. You have already called many functions, such as print(), len() and input(); now you will write your own. All examples were tested on Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, apart from one memory address.
Table of Contents
Define and call a function
A function definition starts with the keyword def, then the function’s name, brackets and a colon. The lines inside are indented, like the blocks of an if or a loop (Lesson 4):
def greet():
print("Welcome to the shop!")
greet()
greet()
Welcome to the shop!
Welcome to the shop!
greet() is a call: it runs the code inside the function. We called it twice, so the message appears twice. If the message changes, you edit it in one place. Function names follow the naming rules for variables from Lesson 5. The PEP 8 style guide says they “should be lowercase, with words separated by underscores”.
A function runs only when you call it
Defining a function does not run it:
print("Start")
def greet():
print("Welcome to the shop!")
print("Function defined")
greet()
print("End")
Start
Function defined
Welcome to the shop!
End
Python reads the def block and remembers the function, but the message only appears when greet() is called. The language reference says: “The function definition does not execute the function body; this gets executed only when the function is called.” This is also why the def must come before the first call in a script.
Parameters and arguments
Most functions need some input. Put names inside the brackets of the def line:
def greet(name):
print(f"Welcome, {name}!")
greet("Sara")
greet("Omar")
customer = "Hina"
greet(customer)
Welcome, Sara!
Welcome, Omar!
Welcome, Hina!
Two words describe the two sides:
- A parameter is the name in the definition:
nameindef greet(name):. - An argument is the value you pass in the call:
"Sara","Omar", or the value ofcustomer.
When greet("Sara") runs, the parameter name gets the value "Sara". The Python FAQ puts it this way: “Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it.”
The number of arguments must match. With no argument, Python stops:
def greet(name):
print(f"Welcome, {name}!")
greet()
Traceback (most recent call last):
File "/home/learner/python-course/err1_missing_argument.py", line 4, in <module>
greet()
~~~~~^^
TypeError: greet() missing 1 required positional argument: 'name'
With one argument too many, greet("Sara", "Omar") gives TypeError: greet() takes 1 positional argument but 2 were given. Lesson 23 shows how to make arguments optional with default values.
return sends a value back
print() only shows a value on the screen. To use a function’s result in your program, the function must return it:
def line_total(price, quantity):
return price * quantity
total = line_total(450, 3)
print(total)
print(line_total(60, 10) + line_total(40, 2))
bill = line_total(450, 3) + line_total(60, 10)
print(f"Bill: {bill} rupees")
1350
680
Bill: 1950 rupees
A call to line_total(450, 3) is replaced by the value it returns, 1350, so you can store it, add two calls together or use it in an f-string, just like a number.
return ends the function
return stops the function at once, even in the middle. Code after it does not run:
def delivery_fee(total):
if total >= 2000:
return 0
return 250
print("This line never runs")
print(delivery_fee(3200))
print(delivery_fee(450))
0
250
For 3200 the first return runs and the function ends. For 450 the if is false, so Python reaches return 250. The print() line is never reached. This “return early” pattern is a clean way to write the delivery rule from Lesson 11.
return vs print
Compare a function that prints with one that returns:
def show_total(price, quantity):
print(price * quantity)
def line_total(price, quantity):
return price * quantity
a = show_total(450, 3)
b = line_total(450, 3)
print("a is", a)
print("b is", b)
1350
a is None
b is 1350
show_total() printed 1350 while it ran, but it gave nothing back, so a is None. line_total() printed nothing, but b holds 1350. Now see what happens when we try to add two printed results:
def show_total(price, quantity):
print(price * quantity)
bill = show_total(450, 3) + show_total(60, 10)
1350
600
Traceback (most recent call last):
File "/home/learner/python-course/err3_print_not_return.py", line 4, in <module>
bill = show_total(450, 3) + show_total(60, 10)
~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'
Both functions ran and printed their numbers, and then the program crashed: None + None is not allowed. A good rule: functions that calculate something should return it, and the code that calls them decides whether to print.
Returning several values
A function can return several values separated by commas. Python packs them into one tuple, and you can unpack it, as in Lesson 16:
def cheapest_and_dearest(prices):
return min(prices), max(prices)
result = cheapest_and_dearest([450, 60, 40, 3200])
print(result)
print(type(result))
low, high = cheapest_and_dearest([450, 60, 40, 3200])
print(f"Cheapest: {low}, dearest: {high}")
(40, 3200)
<class 'tuple'>
Cheapest: 40, dearest: 3200
min() and max() give the smallest and largest price. The function really returns one value, the tuple (40, 3200), and low, high = ... unpacks it into two variables. The Python FAQ calls returning a tuple “almost always the clearest solution” when a function has several results. The number of names on the left must match: three names for two values gives ValueError: not enough values to unpack (expected 3, got 2).
None: what you get without return
Every function call gives back a value. If the function has no return, or a return with nothing after it, that value is None:
def greet(name):
print(f"Welcome, {name}!")
result = greet("Sara")
print(result)
def do_nothing():
return
print(do_nothing())
def label(price):
if price < 100:
return "cheap"
print(label(60))
print(label(450))
Welcome, Sara!
None
None
cheap
None
The Python tutorial says: “return without an expression argument returns None. Falling off the end of a function also returns None.” The last call is a classic bug. label(450) does not match the if, the function ends without reaching any return, and you get None instead of a label. Make sure every path through a function ends in a return; here an extra return "expensive" at the end would fix it.
This also explains a puzzle from Lesson 21: print() itself returns None, so [print(name) for name in names] built a list of None values.
Docstrings: describe your function
The first line inside a function can be a string that says what the function does. This is called a docstring, and it is usually written with triple quotes:
def line_total(price, quantity):
"""Return the price times the quantity."""
return price * quantity
print(line_total.__doc__)
help(line_total)
Return the price times the quantity.
Help on function line_total in module __main__:
line_total(price, quantity)
Return the price times the quantity.
The glossary explains that Python puts the docstring in the function’s __doc__ attribute. As the output shows, help() prints it together with the parameters. The tutorial’s advice for the first line: it “should always be a short, concise summary of the object’s purpose” and “should begin with a capital letter and end with a period”. For a longer docstring, leave the second line blank and add details below it.
In a terminal, help() may show the text in a pager, a scrolling viewer. The pydoc page says help() uses pydoc, which “attempts to paginate the output” on the console. In most pagers, q closes it. Our run saved the output to a file, so it printed straight away.
Putting functions together
Functions can call other functions. Here is the shop’s order total, built from the pieces above:
def line_total(price, quantity):
"""Return the price times the quantity."""
return price * quantity
def delivery_fee(total):
"""Return the delivery fee: free from 2000 rupees."""
if total >= 2000:
return 0
return 250
def order_total(lines):
"""Return the cost of an order, including delivery.
lines is a list of (price, quantity) tuples.
"""
total = 0
for price, quantity in lines:
total += line_total(price, quantity)
return total + delivery_fee(total)
print(order_total([(450, 3), (60, 10)]))
print(order_total([(3200, 1)]))
help(order_total)
2200
3200
Help on function order_total in module __main__:
order_total(lines)
Return the cost of an order, including delivery.
lines is a list of (price, quantity) tuples.
The first order costs 1350 + 600 = 1950, which is under 2000, so 250 is added for delivery: 2200. The second order is 3200 with free delivery. Each function does one small job with a clear name. The for loop (Lesson 12) unpacks each tuple, as in Lesson 16.
Try it yourself
Exercise 1: Temperature
Write a function to_fahrenheit(celsius) that returns celsius * 9 / 5 + 32. Use a loop to print the result for 0, 37 and 100.
Exercise 2: Three results
Write min_max_average(numbers) that returns the smallest number, the largest number and the average. Unpack the result for [45, 78, 90, 33, 61] into three variables and print them.
Exercise 3: Grades
Write grade(mark) with a docstring. It returns "A" for 80 or more, "B" for 60 or more, "C" for 50 or more, and "F" otherwise. Print the grades for [45, 78, 90, 33, 61] with a list comprehension, then print the docstring.
Solutions
Solution 1
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
for c in [0, 37, 100]:
print(c, "C is", to_fahrenheit(c), "F")
0 C is 32.0 F
37 C is 98.6 F
100 C is 212.0 F
The function returns a number, so the loop can print it with other values; / always gives a float.
Solution 2
def min_max_average(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, average = min_max_average([45, 78, 90, 33, 61])
print(f"Lowest {low}, highest {high}, average {average}")
Lowest 33, highest 90, average 61.4
Three values are returned as one tuple and unpacked into three names.
Solution 3
def grade(mark):
"""Return the letter grade for a mark from 0 to 100."""
if mark >= 80:
return "A"
if mark >= 60:
return "B"
if mark >= 50:
return "C"
return "F"
print([grade(mark) for mark in [45, 78, 90, 33, 61]])
print(grade.__doc__)
['F', 'B', 'A', 'F', 'B']
Return the letter grade for a mark from 0 to 100.
Each return ends the function, so no elif is needed, and the last line makes sure every mark gets a grade.
Common mistakes
- Printing instead of returning. The caller gets
None, and adding two results givesTypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'. - Forgetting the brackets.
greetalone does nothing, andprint(greet)shows something like<function greet at 0x7f8b9fe33530>(the address changes on every run). Writegreet(). - Calling a function before its
def. A script that callsgreet()on line 1 and defines it later stops withNameError: name 'greet' is not defined. - Putting
returninside the loop. Withreturn totalindented inside theforloop,order_total([(450, 3), (60, 10)])returns 1350 after the first item instead of 1950. Putreturnafter the loop. - Unpacking the wrong number of values.
low, high, middle = cheapest_and_dearest(...)givesValueError: not enough values to unpack (expected 3, got 2).
Frequently asked questions
What is the difference between return and print in Python?
print() shows a value on the screen for a person to read. return hands a value back to the code that called the function, so the program can store it, add it or pass it on. A function without return gives back None, even if it printed something.
Can a Python function return multiple values?
Yes. Write return a, b and Python returns one tuple holding both values. Unpack it with x, y = my_function(), and use the same number of names as values.
Why does my Python function return None?
The function ended without reaching a return with a value. This happens when there is no return at all, when return has nothing after it, or when an if path skips the return. Check every path through the function, and return the value instead of printing it.
Summary
def name(parameters):defines a function;name(arguments)calls it, and the body runs only on a call.- Parameters are the names in the definition; arguments are the values in the call, and their number must match.
returnsends a value back and ends the function;print()only shows text.return a, breturns a tuple that you can unpack; a function with noreturngivesNone.- A docstring on the first line describes the function and is shown by
help().
Next lesson
Next: Lesson 23, Python Function Arguments: Defaults, Keyword Arguments, *args and **kwargs.
Sources
- More Control Flow Tools: defining functions and documentation strings (Python tutorial)
- Compound statements: function definitions (Python language reference)
- Programming FAQ: arguments vs parameters, returning several values (Python docs)
- Glossary: argument, parameter and docstring (Python docs)
- PEP 8: function and variable names (python.org)
- pydoc: documentation generator and help() (Python docs)
- Python downloads page (python.org)





