Functions
Organizing code into reusable units with def, parameters and return values.
Defining a function
def accuracy(correct, total):
"""Returns the proportion of correct answers."""
if total == 0:
return 0.0
return correct / total
print(accuracy(45, 50)) # 0.9The text between triple quotes is the docstring, and it appears when you type help(accuracy).
Default and keyword arguments
def train(epochs=10, lr=0.01):
print(epochs, lr)
train() # 10 0.01
train(lr=0.001) # 10 0.001*args and **kwargs
def mean(*values):
return sum(values) / len(values)
def show(**options):
for k, v in options.items():
print(k, "=", v)
mean(1, 2, 3) # 2.0
show(model="CNN", depth=3)Scope
threshold = 0.5 # a global variable
def classify(p):
label = 1 if p >= threshold else 0 # label is local
return labelA global variable can be read inside the function, but it is better to pass values as parameters to make the function independent and easy to test.
lambda functions
Short, nameless functions often used as an argument to other functions:
pairs = [("a", 0.7), ("b", 0.9)]
pairs.sort(key=lambda t: t[1], reverse=True)Type hints
def scale(x: float, factor: float = 2.0) -> float:
return x * factorHints are not enforced at run time, but they help editors and static checking tools.
A common pitfall
Do not use a mutable object as a default value:
def add(item, bag=None):
if bag is None:
bag = []
bag.append(item)
return bagLesson terms
- The function
- A named block of code that carries out a specific task and can be called many times with different inputs.
- Scope
- The region of the program in which a variable name is defined and available.
Abstract
A function is a named block of code defined with the keyword def; it receives parameters and returns a value with the keyword return. Python supports default and keyword arguments, *args and **kwargs, and variables have a local scope inside the function. Documenting the function with a docstring and type hints improves readability.
Review questions
-
What does a function without return return?
It returns None.
-
Why is it better not to use a list as a parameter's default value?
Because the default value is created once when the function is defined and shared between calls, so changes to it accumulate.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate