Editor

Python functions MCQ questions with answers

Arguments, defaults, scope and return values, including the classic traps.

0 of 20 answered

  1. 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

    greeting uses its default "Hello" only when the call leaves it out. The second call passes "Hi", which replaces the default for that call only. The return line always puts the greeting before the name.

    Run this code in the editor
  2. Question 2 · Easy

    What is the output of this code?

    def show(x):
        print(x * 2)
    
    print(show(4))
    Show the answer

    Answer: C

    show(4) prints 8 while it runs, then returns None because it has no return statement. The outer print then prints that None on the next line.

    Run this code in the editor
  3. 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 age gets 16 and city gets "Pune" whatever order they are written in. print with several values separates them with single spaces.

    Run this code in the editor
  4. 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 editor
  5. Question 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

    *rest collects the extra positional arguments into a tuple, not a list. With no extra arguments it is an empty tuple (), never None.

    Run this code in the editor
  6. 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

    **details gathers the keyword arguments into a dictionary, in the order they were passed. The loop prints each key and value, and print puts a space between its three arguments, so the lines read lang = Python and level = 3.

    Run this code in the editor
  7. 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

    change() declares global x, so it updates the module-level x from 5 to 15. local_change() has no global statement, so its x = 100 creates a local variable that disappears when the function returns.

    Run this code in the editor
  8. 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

    nonlocal n makes inner change the n that belongs to outer, so every call adds 1 to the same variable. After three calls n is 3, and the third call's return value is what outer returns. Without nonlocal, n += 1 would raise UnboundLocalError.

    Run this code in the editor
  9. 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 print, so countdown(3) waits for countdown(2), which waits for countdown(1). The prints happen as the calls return, deepest first: 1, then 2, then 3. The call with n == 0 returns without printing.

    Run this code in the editor
  10. 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 def runs, and every call that leaves out items shares 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.

    Run this code in the editor
  11. 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 def statement runs. At that moment rate was 5, so r stays 5 even after rate changes to 10. 200 * 5 / 100 is 10.0, a float because / always returns a float.

    Run this code in the editor
  12. 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

    items starts as another name for the list data refers to, so append(4) changes data. items = [9, 9] then points the local name at a new list; the later append(5) changes only that new list, not data.

    Run this code in the editor
  13. 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. area(5) gives length the 5 and nothing to width, so the call raises TypeError. It is not a SyntaxError, because the code is valid Python until the call runs.

    Run this code in the editor
  14. 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 def, so the program stops with SyntaxError before any line runs, even though the call passes author by name.

    Run this code in the editor
  15. 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 add assigns to total, Python treats total as a local variable in the whole function. The right side total + n then reads that local before it has a value, raising UnboundLocalError. Adding global total as the first line would make it print 5.

    Run this code in the editor
  16. Question 16 · Easy

    What does a function return if it ends without a return statement?

    Show the answer

    Answer: D, None

    Every function returns something. When execution reaches the end of the body, or a bare return, the function returns None. Python does not return the last expression the way some other languages do.

  17. 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.

  18. Question 18 · Hard

    Given def send(msg, *, retries):, how must retries be 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, so send("hi", 3) raises TypeError. Unlike *args, a bare * collects nothing; it only marks where the keyword-only parameters start. retries has no default, so it is required.

  19. Question 19 · Easy

    Which definition lets both total(1, 2, 3) and total(5) work and return the sum of the numbers passed?

    Show the answer

    Answer: B

    *nums packs any number of positional arguments into a tuple, which sum adds up. A plain nums parameter accepts one argument only, and **nums collects keyword arguments, so total(1, 2, 3) raises TypeError with those.

  20. 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