Python Functions
What you will learn
- What a function is, and why to write one
- How to define a function with
defand call it - The difference between printing and returning a value
- What a function returns when it has no
return - Early return and returning several values
- How functions call other functions, and the first errors
1. Why functions?
A function is a named block of code that you can run whenever you like, as many times as you like. You have used built-in functions all along: print, len, max, range. Now you will write your own.
Functions give you three things:
- No repeating yourself. Write the code once, use it everywhere.
- Names that explain.
is_even(n)says more thann % 2 == 0scattered through a program. - Small pieces to test and fix. You can check a function on its own.
Quick check: name two built-in functions you already know.
For example print and len. (max, min, sum, abs, round and range are others.)
2. Defining and calling
You define a function with the word def, a name, brackets, a colon, and an indented block:
def greet():
print("Hello!")
greet()
greet()
Hello!
Hello!
def greet():defines the function. Nothing is printed yet: defining only stores the instructions under the namegreet.greet()calls the function. The brackets are what run it. The block runs once for each call.
The brackets matter. greet alone is just the function object (lesson 11.7), and does not run it:
print(greet)
print(type(greet), greet.__name__, callable(greet))
<function greet at 0x000002301E871440>
<class 'function'> greet True
(The address after at will differ on your computer.)
3. Parameters and arguments
A function can take inputs. The names in the brackets of the def line are parameters. The values you pass in a call are arguments:
def greet_name(name):
return "Hello, " + name + "!"
print(greet_name("Rina"))
print(greet_name("Sam"))
Hello, Rina!
Hello, Sam!
Here name is the parameter, and "Rina" and "Sam" are arguments. Each call gives name a different value. Lesson 11.2 goes into this in detail.
4. Returning a value: return
return sends a value back to the place where the function was called, and ends the function. The caller can use the result like any value:
def square(n):
return n * n
print(square(4))
print(square(2.5), square(-3))
print(square(square(2)))
16
6.25 9
16
square(square(2)) works out the inner call first (4), and then squares that.
print is not return
This is the most important distinction in the chapter. print shows a value on the screen. return gives a value to the program:
def show(n):
print(n * n)
v = show(5)
print(v)
25
None
show(5) printed 25, but it returned nothing, so v holds None (lesson 2.3). You cannot do anything with the 25 afterwards: you cannot add to it, store it or test it. A function that calculates something should almost always return it, and let the caller decide whether to print.
print(x) |
return x |
|
|---|---|---|
| shows on screen | yes | no |
| gives a value to the caller | no (the caller gets None) |
yes |
| ends the function | no | yes |
5. No return means None
A function that never reaches a return gives back None:
r = greet()
print(r)
def todo():
pass
print(todo())
Hello!
None
The same happens when a function has a return inside an if that is not taken:
def no_else(n):
if n > 0:
return "pos"
print(no_else(1), no_else(-1))
pos None
For -1, nothing was returned, so the answer is None. This is a common source of surprises: make sure every path through the function returns what you mean.
6. Early return
return ends the function at once. You can use it to leave early, which often avoids deep nesting:
def sign(n):
if n > 0:
return "positive"
if n < 0:
return "negative"
return "zero"
print(sign(5), sign(-2), sign(0))
positive negative zero
After a return runs, the lines below it in the function are skipped. A loop can return from inside too, to stop at the first match (lesson 6.3):
def early(n):
for i in range(n):
if i == 3:
return i
return -1
print(early(10), early(2))
3 -1
7. Returning several values
A function can return several values, separated by commas. Python packs them into a tuple (lesson 8.2), which the caller can unpack:
def min_max(values):
return min(values), max(values)
lo, hi = min_max([4, 9, 1])
print(lo, hi)
print(min_max([5]))
1 9
(5, 5)
8. Functions calling functions
A function can call any other function, including ones you defined. Large programs are built from small functions that call each other:
def area(w, h):
return w * h
def describe(w, h):
return f"{w} x {h} = {area(w, h)}"
print(describe(3, 4))
3 x 4 = 12
A function must be defined before it is called. The def must have been run by then. Using a name that does not exist yet is a NameError:
undefined_function()
NameError: name 'undefined_function' is not defined
(Inside a function body you may mention a function defined later in the file, as long as that def has run before the call happens.)
9. Variables inside a function
Names created inside a function exist only inside it. They are local, and they do not disturb names outside:
x = 10
def uses_local():
x = 5
return x
print(uses_local(), x)
5 10
The x inside the function is a separate variable. Lesson 11.5 explains these scope rules fully.
10. The first errors
| Mistake | What you see |
|---|---|
| too few arguments | TypeError: add() missing 1 required positional argument: 'b' |
| too many arguments | TypeError: add() takes 2 positional arguments but 3 were given |
| calling a name that does not exist | NameError: name '...' is not defined |
| forgetting the brackets | the function runs not at all; you just get the function object |
| forgetting the colon or the indentation | SyntaxError or IndentationError (lesson 5.2) |
def add(a, b):
return a + b
print(add(2, 3), add("ab", "cd"), add([1], [2]))
add(1)
5 abcd [1, 2]
TypeError: add() missing 1 required positional argument: 'b'
Notice that the same add works on numbers, text and lists: Python does not check types in the def line. What + does depends on what you pass.
11. Naming functions
- Use lower-case words joined by underscores (
snake_case):is_even,celsius_to_f. - Start with a verb for actions (
show_total) andis_orhas_for yes/no answers (is_even). - Make the name say what it does, so the call reads like English.
Worked example: temperature conversion
Write a function that converts degrees Celsius to Fahrenheit, and use it on several values.
def celsius_to_f(c):
return c * 9 / 5 + 32
print(celsius_to_f(0))
print(celsius_to_f(100))
print(celsius_to_f(-40))
print(round(celsius_to_f(36.6), 1))
temps = [0, 25, 37]
print([celsius_to_f(t) for t in temps])
32.0
212.0
-40.0
97.9
[32.0, 77.0, 98.6]
| Part | What it does |
|---|---|
def celsius_to_f(c): |
defines the function with one parameter |
return c * 9 / 5 + 32 |
gives the result back (it does not print it) |
celsius_to_f(0) |
calls it; the result is used by print |
[celsius_to_f(t) for t in temps] |
calls it for each value in a list (lesson 12.1) |
The function returns the number, so one function serves all four uses: showing it, rounding it, and putting it in a list. -40 is the famous point where both scales agree.
Common mistakes
- Using
printwhere you meantreturn, and gettingNoneback. - Forgetting the brackets when calling:
greetdoes not run the function. - Forgetting that a function without
returngivesNone. - Passing the wrong number of arguments.
- Writing code after a
return, which never runs. - Calling a function before it is defined.
Key takeaways
def name(parameters):followed by an indented block defines a function;name(arguments)calls it.return valuesends a value to the caller and ends the function;printonly shows something.- A function with no
return(or a path that does not reach one) returnsNone. - Return several values with commas: you get a tuple to unpack.
- Variables made inside a function are local; define a function before you call it.
Practice
1. Write a function double(n) that returns twice n.
Show answer
def double(n):
return n * 2
2. What is v after this code? def f(): print("hi") then v = f()
Show answer
None. The function printed hi but returned nothing.
3. Write is_even(n) that returns True or False.
Show answer
def is_even(n):
return n % 2 == 0
4. Why does greet (without brackets) not print anything?
Show answer
Without brackets it is only the function object. The brackets are what call it and run its block.
5. Write circle_area(r) using math.pi.
Show answer
import math
def circle_area(r):
return math.pi * r ** 2
6. What does min_max([3, 7, 5]) give if it returns min(values), max(values)?
Show answer
The tuple (3, 7).