Python Practice Test: Functions
- Defining and Calling Functions
- 10 questions
- 14 minutes
Ten questions on defining and calling functions. Tip: watch for what the function returns and which variable names are local.
Tap an option to mark your answer. You can change your mind, or tap the same option again to leave the question blank. The correct answers and explanations appear when you finish the test.Tap an option to answer; tap it again to leave the question blank.
Your result
- 0 correct
- 0 wrong
- 0 blank
-
Question 1
def add(a, b=2):
return a + b
print(add(3))What does the code print?
Correct answer: B
b falls back to its default value of 2 because only one argument is passed.
-
Question 2
def f():
x = 1
print(f())What does the code print?
Correct answer: D
A function without a return statement returns None.
-
Question 3
def total(*args):
return sum(args)
print(total(1, 2, 3))What does the code print?
Correct answer: A
*args collects the extra positional arguments into a tuple, and sum adds them up.
-
Question 4
x = 10
def f():
x = 5
f()
print(x)What does the code print?
Correct answer: C
Assigning to x inside the function creates a separate local variable. The global x stays 10.
-
Question 5
def greet(name, greeting="Hi"):
return greeting + ", " + name
print(greet(greeting="Yo", name="Sam"))What does the code print?
Correct answer: B
Keyword arguments are matched by name, so the order in the call does not matter.
-
Question 6
def add(item, bag=[]):
bag.append(item)
return bag
add(1)
print(add(2))What does the code print?
Correct answer: A
The default list is created once when the function is defined and shared by all calls, so the first call's item stays in it.
-
Question 7
print(sorted(["pear", "fig", "apple"], key=len))
What does the code print?
Correct answer: D
With key=len the words are ordered by length: fig (3), pear (4), apple (5).
-
Question 8
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5))What does the code print?
Correct answer: C
5 x 4 x 3 x 2 x 1 equals 120. The recursion stops when n reaches 1.
-
Question 9
def mm(values):
return min(values), max(values)
lo, hi = mm([3, 9, 1])
print(lo, hi)What does the code print?
Correct answer: B
The function returns a tuple, which is unpacked into lo and hi.
-
Question 10
count = 0
def inc():
global count
count += 1
inc()
inc()
print(count)What does the code print?
Correct answer: A
The global statement makes the function change the module-level count. Without it, count += 1 would fail.
Questions you leave blank are not counted as wrong.