FunctionsChapter 48 of 114
Functions
Name a piece of work once and run it whenever you need it.
Defining and calling
def, a name, brackets, a colon, and an indented body:
def greet():
print("Hello")
greet()
greet()Output
Hello Hello
Defining a function does not run it. The body runs only when you call it, which is what the brackets do.
def greet():
print("Hello")
print("defined, not called")
greet
greet()Output
defined, not called Hello
The bare greet on its own line is the function object itself. It is a value like any other, and evaluating it does nothing.
Parameters and arguments
A parameter is the name in the definition. An argument is the value you pass in:
def greet(name):
print("Hello,", name)
greet("Ada")
greet("Grace")Output
Hello, Ada Hello, Grace
Pass the wrong number and Python says so rather than guessing:
def greet(name):
print("Hello,", name)
try:
greet()
except TypeError as problem:
print("TypeError:", problem)Output
TypeError: greet() missing 1 required positional argument: 'name'
Returning a value
print shows something to a person. return hands a value back to the code that called the function. They are not interchangeable:
def double(n):
return n * 2
result = double(5)
print(result)
print(double(result))Output
10 20
A function with no return gives back None:
def shout(word):
print(word.upper())
value = shout("hey")
print(value)Output
HEY None
Why bother
Three reasons, in order of how much they matter:
- A name.
calculate_vat(total)explains itself; six lines of arithmetic do not. - One place to change. Fix a bug once rather than in nine copies.
- Testable. A function that takes input and returns output can be checked.
def vat(amount, rate=0.2):
return round(amount * rate, 2)
print(vat(100))
print(vat(100, 0.05))Output
20.0 5.0
Docstrings
A string on the first line of the body documents the function, and help() and your editor both read it:
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area.__doc__)Output
Return the area of a rectangle.
Functions are values
You can pass a function to another function, which is what sorted(key=...) has been doing all along:
def shout(word):
return word.upper()
def apply_twice(fn, value):
return fn(fn(value))
print(apply_twice(shout, "hey"))
print(sorted(["bb", "a", "ccc"], key=len))Output
HEY ['a', 'bb', 'ccc']
Note there are no brackets after shout when passing it. Adding them would call it and pass the result instead.
Test yourself
2 questionsWhat is the difference between print and return inside a function?
Show the answer
print shows something; return hands a value back to the caller — A function that prints but does not return gives back None, which is the classic mix-up.
What does 'greet' on its own line do, with no brackets?
Show the answer
Nothing; it is just the function object — The brackets are what call it. That is also why you pass sorted(key=len) without brackets.
Arguments
Positional and keyword arguments, and how Python matches them up.