1 Before you start
This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.
What does a function return if you forget to write a return statement?
You define def greet(name, greeting="Hello"): return f"{greeting}, {name}". Which call uses keyword arguments correctly?
Given def greet(name, greeting="Hi"): return f"{greeting}, {name}", what does greet("Sam") return?
Which is equivalent to def square(x): return x**2?
What does sorted([5, -3, 1], key=lambda x: abs(x)) return?
You define def f(*args): print(args). What type is args inside the function?
You define def f(**kwargs): print(kwargs). What type is kwargs inside the function?
A variable is created inside a function with an ordinary assignment (no global keyword). After the function returns, what happens to it?
I can write a function with parameters and a default value, and call it using either positional or keyword arguments.
I can write a lambda to use as the key= argument of sorted, max, or min.
I can read a function signature that uses *args or **kwargs and tell what kind of inputs it accepts.
2 Introduction
As your programs get longer, you often need the same calculation in multiple places. A function lets you write that calculation once, name it and use it whenever needed.
This lesson covers how to write functions, two ways to pass values to them, one-line lambda functions, functions taking any number of values, and which variables a function can see. The next lesson covers files and command-line input.
Try every example in the Python Scratchpad on the right.
3 Functions and parameters
Suppose you calculate a BMI in three places. Each time you type the same expression, you might make a typing mistake.
bmi_a = 72 / (1.75 ** 2)
bmi_b = 60 / (1.62 ** 2)
bmi_c = 85 / (1.80 * 2)
print(bmi_a) # 23.510204081632654
print(bmi_b) # 22.86236854138088
print(bmi_c) # 23.61111111111111The third line has * instead of **. Python reports no error, and 23.6 looks like a normal BMI. The correct value is about 26.2.
A function lets you write the expression once and name it. Here is the BMI calculation as a function:
def calculate_bmi(weight_kg, height_m):
return weight_kg / (height_m ** 2)The first line is the header. It has four parts:
- the
defkeyword, which tells Python you are defining a function; - the function name, here
calculate_bmi; - the parameters inside round brackets, here
weight_kgandheight_m; - a colon
:at the end.
The indented lines under the header are the body. Every line of the body is indented by the same amount, usually four spaces. The return line sends a value back to the code that called the function.

Type the code below into the Python Scratchpad and run it.
Try this snippet in the Python Scratchpad on the right.
def calculate_bmi(weight_kg, height_m):
return weight_kg / (height_m ** 2)
print(calculate_bmi(72, 1.75))
You can call the function again with other values. This time the third result is correct. This is because the expression is written only once.
print(calculate_bmi(72, 1.75)) # 23.510204081632654
print(calculate_bmi(60, 1.62)) # 22.86236854138088
print(calculate_bmi(85, 1.80)) # 26.234567901234566Three words are easy to confuse:
- A parameter is a name in the header, such as
weight_kg. - An argument is a value you pass in a call, such as
72. - A return value is what the function sends back. Without a
returnline, it sends backNone. Code that uses this result can fail or give a wrong answer.
A function can have any number of parameters, even none. A call must pass one value per parameter, in the same order. With too few or too many values, Python reports a TypeError:
print(calculate_bmi(72))
# TypeError: calculate_bmi() missing 1 required positional argument: 'height_m'The error message names the missing parameter. Fix the call in the exercise below.
The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.
def add(a, b):
return a + b
print(add(3))
- Pass two values when you call the function: add(3, 5) ★
- Replace return with print inside the function
- Remove the colon at the end of the def line
A docstring is a one-line description in triple quotes, just under the header. It tells readers what the function does, and help() shows it.
def calculate_bmi(weight_kg, height_m):
"""Return body-mass index from weight in kg and height in metres."""
return weight_kg / (height_m ** 2)
help(calculate_bmi) # shows the docstring4 Positional vs keyword arguments
So far, every call has passed values in order. Python gives the first value to the first parameter, the second to the second, and so on. These are called positional arguments.
def calculate_bmi(weight_kg, height_m):
return weight_kg / (height_m ** 2)
print(calculate_bmi(72, 1.75)) # 23.510204081632654
print(calculate_bmi(1.75, 72)) # 0.00033757716049382714The second call swaps the values, so weight_kg gets 1.75 and height_m gets 72. Python reports no error. It returns a number that makes no sense as a BMI.
A keyword argument names its parameter: you write the name, an equals sign, and the value. The order no longer matters.
print(calculate_bmi(weight_kg=72, height_m=1.75)) # 23.510204081632654
print(calculate_bmi(height_m=1.75, weight_kg=72)) # 23.510204081632654Both calls give the same answer. A reader can also see which number is the weight and which is the height.

You can mix the two styles, but positional arguments must come first. calculate_bmi(72, height_m=1.75) works. calculate_bmi(weight_kg=72, 1.75) is a SyntaxError. Fix it in the exercise below.
The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.
def calculate_bmi(weight_kg, height_m):
return weight_kg / (height_m ** 2)
print(calculate_bmi(weight_kg=72, 1.75))
- Make both arguments keyword so order no longer matters: print(calculate_bmi(weight_kg=72, height_m=1.75)) ★
- Swap to positional first, keep the keyword second: print(calculate_bmi(1.75, weight_kg=72))
- Give the first parameter a default in the definition: def calculate_bmi(weight_kg=72, height_m):
A parameter can also have a default value, written in the header with an equals sign. A call that leaves the parameter out gets the default. This suits a setting that is usually the same, such as how often a drug is given.
def prescribe(patient_id, drug, dose_mg, frequency="daily"):
print(f"{patient_id}: {dose_mg}mg {drug}, {frequency}")
prescribe("P01", "metformin", 500) # prints: P01: 500mg metformin, daily
prescribe("P02", "metoprolol", 50, "twice daily") # prints: P02: 50mg metoprolol, twice dailyThe first call gets the default, "daily". The second call passes "twice daily" instead.
Parameters with a default must follow those without one, or Python reports a SyntaxError when reading the def line.
Keyword arguments also let you change one default while keeping others. Type the code below into the Python Scratchpad and run it. The third call changes the route but keeps the default frequency.
Try this snippet in the Python Scratchpad on the right.
def prescribe(patient_id, drug, dose_mg, frequency="daily", route="oral"):
print(f"{patient_id}: {dose_mg}mg {drug}, {frequency}, {route}")
prescribe("P01", "metformin", 500)
prescribe("P02", "metoprolol", 50, "twice daily")
prescribe("P03", "enoxaparin", 40, route="subcutaneous")
5 Anonymous functions with lambda
For a very small function that you use once, writing a def and a name is unnecessary.
A lambda is a function with no name, written on one line as lambda parameters: expression. It makes a function, just as def does, and returns the value of the expression.
You will most often see a lambda as the key= argument of sorted(), max() or min(). It tells Python which part of each item to compare.
results = [("P11", 4.8), ("P12", 3.9), ("P13", 5.4)]
print(sorted(results)) # [('P11', 4.8), ('P12', 3.9), ('P13', 5.4)]
print(sorted(results, key=lambda pair: pair[1])) # [('P12', 3.9), ('P11', 4.8), ('P13', 5.4)]Each pair is a patient ID and a potassium result in mmol/L. Without a key, sorted() compares the IDs. With the key, it compares the results. The key only decides the order: each item in the new list is still the whole pair.
Type the next example into the Python Scratchpad and run it. It sorts patients by BMI.
Try this snippet in the Python Scratchpad on the right.
patients = [("Alice", 27.3), ("Bob", 22.1), ("Chen", 31.5)]
patients.sort(key=lambda p: p[1])
print(patients)
The next example sorts patients by age, finds the oldest with max(), and writes the same small function using lambda and def.
Try this snippet in the Python Scratchpad on the right.
patients = [
{"id": "P001", "age": 54},
{"id": "P002", "age": 38},
{"id": "P003", "age": 72},
]
by_age = sorted(patients, key=lambda p: p["age"])
print(by_age)
oldest = max(patients, key=lambda p: p["age"])
print(oldest)
get_age = lambda p: p["age"]
def get_age_def(p):
return p["age"]
print(get_age(patients[0]), get_age_def(patients[0]))

6 Flexible arguments with *args and **kwargs
Sometimes a function must accept any number of values. Two special parameters do this:
*argscollects any extra positional arguments into a tuple.**kwargscollects any extra keyword arguments into a dictionary.
The names args and kwargs are only a convention. The * and ** do the work, so you can choose names that describe your data.
def count_samples(*sample_ids):
return len(sample_ids)
def print_readings(**readings):
for name, value in readings.items():
print(name, "=", value)
print(count_samples("S01")) # 1
print(count_samples("S01", "S02", "S03")) # 3
print_readings(pulse=72, temp_c=37.1) # prints pulse = 72, then temp_c = 37.1sample_ids holds every value passed in, so len() counts them. readings holds each name and value, and the loop prints them.
Most machine learning libraries end a function's header with *args and **kwargs, to collect extra arguments and pass them on. *args comes before **kwargs, which always comes last. The header is also called the function's signature.

Now arrange the lines below into a working function.
All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.
Task: Define a function that takes a patient ID, any number of symptoms, and any number of named admission details, then call it for one patient.
admit_patient("P042", ward="A3", "fever", "cough")def admit_patient(patient_id, **details, *symptoms):admit_patient("P042", "fever", "cough", ward="A3", priority="urgent")def admit_patient(patient_id, *symptoms, **details):print(f"Admitting {patient_id}")print(f"Symptoms: {symptoms}")print(f"Details: {details}")print(f"Symptoms: *symptoms")
- Drop lines here, in order.
Type the code below into the Python Scratchpad and run it. It uses *args, then **kwargs, then both.
Try this snippet in the Python Scratchpad on the right.
def mean(*values):
return sum(values) / len(values)
print(mean(54, 61, 47, 72))
print(mean(1, 2, 3))
def describe_patient(**fields):
for key, value in fields.items():
print(f"{key}: {value}")
describe_patient(id="P001", age=54, weight_kg=72)
# Combining both - the standard signature you will see in ML libraries
def fit(model, X, y, *args, **kwargs):
print("model:", model)
print("extra positional:", args)
print("extra keyword:", kwargs)
fit("logreg", [[1,2]], [0], "fast", verbose=True, max_iter=100)
7 Variable scope (local and global)
Variables created inside a function, including its parameters, exist only while it runs. This is called local scope.
Local scope makes a function safe to reuse. Each call has its own variables, so calls from twenty places in your code do not affect each other.
The cost is that code outside the function cannot use them. Type the code below into the Python Scratchpad and run it.
Try this snippet in the Python Scratchpad on the right.
def calculate_bmi(weight_kg, height_m):
bmi = weight_kg / (height_m ** 2)
return bmi
print(calculate_bmi(72, 1.75))
print(bmi)
The first print line works. This is because the function returns the value. The second fails with NameError: name 'bmi' is not defined. This is because bmi existed only inside the function. Use return to get a value out.
Variables created outside every function, at the top level of a program, are in global scope.

8 Check your understanding
You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.
What does a function return if you forget to write a return statement?
You define def greet(name, greeting="Hello"): return f"{greeting}, {name}". Which call uses keyword arguments correctly?
Given def greet(name, greeting="Hi"): return f"{greeting}, {name}", what does greet("Sam") return?
Which is equivalent to def square(x): return x**2?
What does sorted([5, -3, 1], key=lambda x: abs(x)) return?
You define def f(*args): print(args). What type is args inside the function?
You define def f(**kwargs): print(kwargs). What type is kwargs inside the function?
A variable is created inside a function with an ordinary assignment (no global keyword). After the function returns, what happens to it?
I can write a function with parameters and a default value, and call it using either positional or keyword arguments.
I can write a lambda to use as the key= argument of sorted, max, or min.
I can read a function signature that uses *args or **kwargs and tell what kind of inputs it accepts.
9 Your results
Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?