Functions in Python
A function is a named block of code that runs only when you call it. You define one with def, give it parameters for the values it needs, and send a result back with return. A function without a return statement gives back None.
Key facts
def greet():followed by an indented block defines a function namedgreet, andgreet()calls it.- Parameters are the names in the
defline. Arguments are the values passed in the call. returnsends a value back to the caller and ends the function at once.- A function with no
returnstatement returnsNone. - The
defmust run before the first call, or Python raisesNameError.
What is a function in Python?
A function is a named block of code that runs only when you call it. You write the code once, give it a name, and run it from anywhere later in the program by writing that name followed by parentheses.
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()Hello! Welcome to Python. Hello! Welcome to Python.
The def block on its own prints nothing. Python stores the function under the name greet and moves on, so the output only appears at the two calls at the bottom. You have been calling functions since the first lesson, because print(), len() and input() are functions too.
Functions that work without any import, like those three, are called built-in functions, and the ones you write are user-defined. Writing your own keeps a program short, because code used in several places lives in one function, and a fix to it applies everywhere.
How do I define and call a function in Python?
Define the function with def, then call it by name with parentheses. The definition has to come first, because Python runs a file from top to bottom.
- Write the def line. Start with
def, then the function's name, a pair of parentheses and a colon, as indef show_line():. Function names follow the rules for variable names and, by convention, are written in lowercase with underscores between words. - Indent the body. Indent every line of the body, usually by four spaces. The first line that isn't indented is outside the function.
- Call the function. Write its name with parentheses, such as
show_line(), on a line below the definition. Each call runs the body again from the top.
def show_line():
print("-" * 20)
show_line()
print("Report")
show_line()-------------------- Report --------------------
The two calls print the same row of dashes above and below Report. Changing "-" * 20 in the function changes both rows.
What is the difference between a parameter and an argument?
A parameter is a name in the def line, and an argument is the value you pass in the call. While the function runs, each parameter holds its argument, like a variable that exists only inside the function.
def greet(name):
print(f"Hello, {name}!")
greet("Ada")
greet("Grace")Hello, Ada! Hello, Grace!
Here name is the parameter, and "Ada" and "Grace" are the arguments. A function can have several parameters separated by commas, and the arguments fill them in order. The function arguments lesson covers default values and passing arguments by name.
What does return do in a Python function?
return sends a value back to the code that called the function and ends the function at once. The call then stands for that value, so you can store it, print it or use it in a calculation.
def add(a, b):
return a + b
total = add(2, 3)
print(total)
print(add(10, 5) * 2)5 30
add(2, 3) runs the body with a set to 2 and b set to 3, and the call gives back 5, which is stored in total. In the last line, the returned 15 is doubled before print() receives it.
Because return ends the function, a function can have several return statements, and only the first one Python reaches runs.
def sign(n):
if n > 0:
return "positive"
if n < 0:
return "negative"
return "zero"
print(sign(5))
print(sign(-2))
print(sign(0))positive negative zero
When n is 5, the first return runs and the function stops there, so the later checks never happen and sign() needs no elif or else.
A return inside a loop ends the loop and the function together. Inside nested loops it leaves all of them at once, which break can't do, as the break and continue lesson showed.
def first_negative(numbers):
for n in numbers:
if n < 0:
return n
return None
print(first_negative([4, 7, -2, 9, -5]))
print(first_negative([1, 2, 3]))-2 None
The last line of the function runs only when no number is negative. return None could be left out, because a function that reaches its end returns None anyway, but writing it makes the not-found result clear.
What is the difference between return and print in Python?
return hands a value back to the program, and print() only shows it on the screen. A function that prints without returning gives the caller None, Python's value for nothing.
def show_double(n):
print(n * 2)
def double(n):
return n * 2
result = show_double(4)
print(result)
result = double(4)
print(result)8 None 8
show_double(4) prints 8 from inside the function, but result gets None, because the function has no return statement. double(4) prints nothing itself, and its 8 appears only because the program printed the returned value.
| Question | return | print() |
|---|---|---|
| What is it? | A statement that ends the function | A built-in function |
| Where does the value go? | Back to the code that made the call | To the screen |
| Can the program use the value? | Yes, it can store it or calculate with it | No, it only becomes text on the screen |
| Does the function keep running? | No, it stops at once | Yes, the next line runs |
| Use it when | Other code needs the result | A person needs to see the value |
Most functions should return their result and leave the printing to the code that calls them, which can then print it, store it or pass it to another function.
Can a Python function return more than one value?
Yes. Write the values after return separated by commas, and Python returns them together as one tuple. Unpack the tuple into separate variables at the call, the way the tuples lesson unpacks a point.
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([4, 1, 9, 7])
print(low, high)
print(min_max([4, 1, 9, 7]))1 9 (1, 9)
The first call unpacks the tuple into low and high. The second prints the tuple itself, which shows that the function returned a single tuple holding two values.
How do I write a docstring for a function?
Put a string in triple quotes on the first line of the function's body. That string is the docstring, and it says what the function does.
def celsius_to_fahrenheit(celsius):
"""Convert a temperature from Celsius to Fahrenheit."""
return celsius * 9 / 5 + 32
print(celsius_to_fahrenheit(100))
print(celsius_to_fahrenheit.__doc__)212.0 Convert a temperature from Celsius to Fahrenheit.
Python stores the docstring in the function's __doc__ attribute, a value attached to the function and read with a dot. help(celsius_to_fahrenheit) prints it along with the parameter list.
PEP 257, the docstring style guide, recommends writing it as a command, such as "Convert..." or "Return...". The comments lesson compares docstrings with # comments.
Common mistakes with functions in Python
These four mistakes come up most with functions. The last one is the hardest to spot, because the program runs without any message.
- NameError: name 'say_hi' is not defined. The call runs before the
def, or the name is misspelled. Move the definition above the first call. - TypeError: greet() missing 1 required positional argument: 'name'. The call passed fewer arguments than the function has parameters. Pass one value for each parameter.
- TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. The function printed its result instead of returning it, so the call gave back
None. Changeprint()toreturn. - Forgetting the parentheses.
greetwithout parentheses refers to the function but doesn't call it, so nothing runs.print(greet)shows something like<function greet at 0x...>instead of a result.
Run the three broken programs to see the messages, then fix each one in the editor. Each report is a traceback. Its last line names the error, and the line that starts with File gives the line number.
say_hi()
def say_hi():
print("Hi!")Traceback (most recent call last):
File "main.py", line 1, in <module>
say_hi()
^^^^^^
NameError: name 'say_hi' is not defineddef greet(name):
print(f"Hello, {name}!")
greet()Traceback (most recent call last):
File "main.py", line 4, in <module>
greet()
~~~~~^^
TypeError: greet() missing 1 required positional argument: 'name'def double(n):
print(n * 2)
result = double(4) + 1
print(result)8
Traceback (most recent call last):
File "main.py", line 4, in <module>
result = double(4) + 1
~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'Exercise
Change square() so it returns the result instead of printing it, and the program prints 58. The starter prints 9 and 49 and then stops with a TypeError, because square() has no return statement and each call gives back None.
def square(n):
print(n * n)
total = square(3) + square(7)
print(total)
58
Show the solution
def square(n):
return n * n
total = square(3) + square(7)
print(total)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
def f(): return 1 print("done") print(f())return ends the function, so the print() line after it never runs. The program prints the returned 1.
-
2What does this program print?
def show(n): n * 2 print(show(5))The function calculates n * 2 but never returns it, so the call gives back None. Adding return in front of n * 2 would make it print 10.
-
3A function starts with def add(a, b). What are a and b called?
The names in the def line are parameters. The values passed in a call, such as the 2 and 3 in add(2, 3), are the arguments.
-
4What happens when Python runs a def statement?
def creates the function and gives it a name. The body runs only when the function is called, and every call runs it again.
-
5What does this program print?
def add(a, b): return a + b print(add("3", "4"))The arguments are strings, so + joins them into 34, and print() shows a string without its quotes. Given numbers, the same function would add them.























