Python functions MCQ questions with answers
Arguments, defaults, scope and return values, including the classic traps.
0 of 20 answered
Question 1 · Easy
What is the output of this code?
def greet(name, greeting="Hello"): return greeting + ", " + name print(greet("Asha")) print(greet("Ravi", "Hi"))
Show the answer
Answer: A
Run this code in the editorgreetinguses its default "Hello" only when the call leaves it out. The second call passes "Hi", which replaces the default for that call only. Thereturnline always puts the greeting before the name.Question 2 · Easy
What is the output of this code?
def show(x): print(x * 2) print(show(4))
Show the answer
Answer: C
Run this code in the editorshow(4)prints 8 while it runs, then returnsNonebecause it has noreturnstatement. The outerprintthen prints thatNoneon the next line.Question 3 · Easy
What is the output of this code?
def describe(name, age, city): print(name, age, city) describe("Meera", city="Pune", age=16)
Show the answer
Answer: D
Keyword arguments are matched by name, not by position, so
Run this code in the editoragegets 16 andcitygets "Pune" whatever order they are written in.printwith several values separates them with single spaces.Question 4 · Easy
What is the output of this code?
def fact(n): if n <= 1: return 1 return n * fact(n - 1) print(fact(5))
Show the answer
Answer: B
fact(5) = 5 * fact(4) = 5 * 4 * 3 * 2 * fact(1), and fact(1) returns 1, so the result is 120. 24 is fact(4), 720 is fact(6), and 15 would be the sum 1 + 2 + 3 + 4 + 5.
Run this code in the editorQuestion 5 · Medium
What is the output of this code?
def show(first, *rest): print(first, rest) show(1, 2, 3) show(4)
Show the answer
Answer: A
Run this code in the editor*restcollects the extra positional arguments into a tuple, not a list. With no extra arguments it is an empty tuple(), neverNone.Question 6 · Medium
What is the output of this code?
def info(**details): for key, value in details.items(): print(key, "=", value) info(lang="Python", level=3)
Show the answer
Answer: C
Run this code in the editor**detailsgathers the keyword arguments into a dictionary, in the order they were passed. The loop prints each key and value, andprintputs a space between its three arguments, so the lines readlang = Pythonandlevel = 3.Question 7 · Medium
What is the output of this code?
x = 5 def change(): global x x = x * 3 def local_change(): x = 100 change() local_change() print(x)
Show the answer
Answer: D
Run this code in the editorchange()declaresglobal x, so it updates the module-level x from 5 to 15.local_change()has noglobalstatement, so itsx = 100creates a local variable that disappears when the function returns.Question 8 · Medium
What is the output of this code?
def outer(): n = 0 def inner(): nonlocal n n += 1 return n inner() inner() return inner() print(outer())
Show the answer
Answer: B
Run this code in the editornonlocal nmakesinnerchange thenthat belongs toouter, so every call adds 1 to the same variable. After three calls n is 3, and the third call's return value is whatouterreturns. Withoutnonlocal,n += 1would raise UnboundLocalError.Question 9 · Medium
What is the output of this code?
def countdown(n): if n == 0: return countdown(n - 1) print(n, end=" ") countdown(3)
Show the answer
Answer: A
The recursive call comes before the
Run this code in the editorprint, socountdown(3)waits forcountdown(2), which waits forcountdown(1). The prints happen as the calls return, deepest first: 1, then 2, then 3. The call with n == 0 returns without printing.Question 10 · Hard
What is the output of this code?
def add(x, items=[]): items.append(x) return len(items) print(add(1), add(2), add(3, []), add(4))
Show the answer
Answer: C
The default list is created once, when
Run this code in the editordefruns, and every call that leaves outitemsshares it. Calls 1, 2 and 4 append to that one list (lengths 1, 2, 3). The call that passes its own[]uses a fresh list, returns 1 and leaves the shared list alone.Question 11 · Hard
What is the output of this code?
rate = 5 def interest(amount, r=rate): return amount * r / 100 rate = 10 print(interest(200))
Show the answer
Answer: B
A default value is evaluated once, when the
Run this code in the editordefstatement runs. At that momentratewas 5, sorstays 5 even afterratechanges to 10. 200 * 5 / 100 is 10.0, a float because/always returns a float.Question 12 · Hard
What is the output of this code?
def modify(items): items.append(4) items = [9, 9] items.append(5) data = [1, 2, 3] modify(data) print(data)
Show the answer
Answer: D
Run this code in the editoritemsstarts as another name for the listdatarefers to, soappend(4)changesdata.items = [9, 9]then points the local name at a new list; the laterappend(5)changes only that new list, notdata.Question 13 · Easy
Which error does this code raise?
def area(length, width): return length * width print(area(5))
Show the answer
Answer: A, TypeError: area() missing 1 required positional argument: 'width'
A parameter without a default must receive an argument.
Run this code in the editorarea(5)giveslengththe 5 and nothing towidth, so the call raises TypeError. It is not a SyntaxError, because the code is valid Python until the call runs.Question 14 · Medium
Which error does this code raise?
def book(title, price=100, author): return f"{title} by {author}: {price}" print(book("Python Basics", author="Rao"))
Show the answer
Answer: C, SyntaxError: parameter without a default follows parameter with a default
Parameters with default values must come after all parameters without defaults. Python checks this when it compiles the
Run this code in the editordef, so the program stops with SyntaxError before any line runs, even though the call passesauthorby name.Question 15 · Medium
Which error does this code raise?
total = 0 def add(n): total = total + n return total print(add(5))
Show the answer
Answer: B, UnboundLocalError: cannot access local variable 'total'
Because
Run this code in the editoraddassigns tototal, Python treatstotalas a local variable in the whole function. The right sidetotal + nthen reads that local before it has a value, raising UnboundLocalError. Addingglobal totalas the first line would make it print 5.Question 16 · Easy
What does a function return if it ends without a
returnstatement?Show the answer
Answer: D, None
Every function returns something. When execution reaches the end of the body, or a bare
return, the function returnsNone. Python does not return the last expression the way some other languages do.Question 17 · Medium
In which order does Python look up a name used inside a nested function?
Show the answer
Answer: A, Local, Enclosing, Global, Built-in
This is the LEGB rule: the function's own names first, then those of any enclosing function, then the module's global names, and finally built-ins such as
len. The first match wins, which is why a local variable hides a global one with the same name.Question 18 · Hard
Given
def send(msg, *, retries):, how mustretriesbe passed?Show the answer
Answer: C, Only by keyword, as in
send("hi", retries=3)A bare
*in the parameter list makes every parameter after it keyword-only, sosend("hi", 3)raises TypeError. Unlike*args, a bare*collects nothing; it only marks where the keyword-only parameters start.retrieshas no default, so it is required.Question 19 · Easy
Which definition lets both
total(1, 2, 3)andtotal(5)work and return the sum of the numbers passed?Show the answer
Answer: B
*numspacks any number of positional arguments into a tuple, whichsumadds up. A plainnumsparameter accepts one argument only, and**numscollects keyword arguments, sototal(1, 2, 3)raises TypeError with those.Question 20 · Easy
Which function correctly returns 1 + 2 + ... + n for any whole number n of 0 or more?
Show the answer
Answer: D
A recursive function needs a base case that stops the calls and a step that moves toward it. Without the
if, the calls never stop and Python raises RecursionError. The second option forgets to add n and the third multiplies by 0 in the end, so both always return 0.
Keep going
- Read the lesson behind these questions: Functions in the PythonBook
- Next topic: Python lambda, map and filter MCQ questions with answers
- Before this: Python list comprehension MCQ questions with answers
- Write the code yourself in the Python coding challenges, which check your solution with tests.