Functions & default arguments
Computer Science · Python
Question 1 of 10
0What does this Python code print? def add(x, y=8): return x + y print(add(6, 6))
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Functions & default arguments explained
A default argument is a value a function uses when the caller does not supply that argument. Defaults make functions easier to call, but a default that is a mutable object such as a list is shared between calls and can cause surprising bugs.
In Python you give a parameter a default with an equals sign in the definition, for example def greet(name, greeting="Hello"). Callers can then write greet("Ana") or greet("Ana", "Hi"). Parameters with defaults must come after parameters without defaults.
Arguments can also be passed by keyword, so greet(greeting="Hi", name="Ana") works in any order.
The default value is evaluated once, when the function is defined, not each time it is called. This matters for mutable objects. If the default is an empty list, every call that changes it changes the same list. The standard fix is to use None as the default and create a new list inside the function when it is None.
Immutable defaults such as numbers, strings and tuples are safe, because they cannot be changed in place.
Worked example
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("pear"))
- The first call appends "apple" to the default list and returns ['apple'].
- The second call uses the same default list, which already holds "apple", so it appends "pear" and returns ['apple', 'pear'].
The second result has 2 items, not 1. Using basket=None and writing if basket is None: basket = [] inside the function gives each call its own list.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this Python code print? def add(x, y=9): return x + y print(add(8, 3))
Medium
What does this Python code print? def area(w, h=3, scale=2): return w * h * scale print(area(6, 4))
Hard
What does this Python code print? def add_item(item, bag=[]): bag.append(item) return len(bag) print(add_item(8, [])) print(add_item(3, [])) print(add_item(9, [])) print(add_item(8)) print(add_item(4)) What is the last number printed?