Python Functions
A function is a named block of code that you can run whenever you need it. Functions let you avoid repeating yourself, give a name to an idea, and break a big problem into small, testable pieces.
Defining and calling a function
Use the def keyword, a name, parentheses and a colon. The indented body runs only when the function is called:
def greet():
print("Hello!")
print("Welcome to Python.")
greet()
greet()Hello!
Welcome to Python.
Hello!
Welcome to Python.
Parameters and arguments
Values you pass in are called arguments; the names that receive them inside the function are parameters:
def greet(name, greeting):
print(f"{greeting}, {name}!")
greet("Hoa", "Good morning")
greet("Khanh", "Hi")Good morning, Hoa!
Hi, Khanh!
Calling a function with the wrong number of arguments is a TypeError.
Returning a value
return sends a value back to the caller and ends the function immediately. A function without return gives back None:
def area(width, height):
return width * height
def say(text):
print(text)
room = area(4, 5)
print("Room area:", room)
print("Two rooms:", area(4, 5) + area(3, 3))
result = say("hi")
print(result)Room area: 20
Two rooms: 29
hi
None
Tip: Prefer functions that return results over functions that print them. A returned value can be printed, stored, tested or passed on; printed text can only be read.
Default values and keyword arguments
A parameter can have a default value that's used when the caller leaves it out. Callers can also pass arguments by name, in any order:
def make_coffee(size="medium", sugar=0, milk=False):
extras = f"{sugar} sugar" + (", milk" if milk else "")
return f"{size} coffee ({extras})"
print(make_coffee())
print(make_coffee("large"))
print(make_coffee(milk=True, sugar=2))medium coffee (0 sugar)
large coffee (0 sugar)
medium coffee (2 sugar, milk)
Note: Never use a mutable value like
[]or{}as a default. The same object is reused for every call. UseNoneand create the list inside the function instead. The Arguments lesson shows why.
Early return
return can appear anywhere, which is useful for handling special cases first:
def safe_divide(a, b):
if b == 0:
return None
return a / b
print(safe_divide(10, 4))
print(safe_divide(1, 0))2.5
None
Docstrings
Describe what a function does in a docstring, the first string inside the body. Editors and help() show it:
def bmi(weight_kg, height_m):
"""Return the body-mass index for the given weight and height."""
return weight_kg / height_m ** 2Functions are objects
In Python a function is a value like any other. You can store it in a variable, put it in a list or pass it to another function:
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
for style in [shout, whisper]:
print(style("Hello"))
print(sorted(["kiwi", "fig", "banana"], key=len))HELLO!
hello...
['fig', 'kiwi', 'banana']
Passing len as key= is exactly this idea — the sorting function calls the function you hand it.
Vocabulary
| Term | Meaning |
|---|---|
| definition | the def …: block that creates the function |
| call | running it: name(...) |
| parameter | a name in the definition: def f(x) |
| argument | a value in the call: f(5) |
| return value | what the call evaluates to |
Test yourself
What does a function return if it has no return statement?
- 0
- An empty string
- None
- It raises an error
In def f(x, y=3):, what is f(2)'s value of y?
- 2
- 3
- None
- Error: missing argument
Which keyword starts a function definition?
- function
- func
- def
- fn