Python Functions MCQs

1 min read

Functions in Python are reusable blocks of code designed to perform a specific task, promoting code modularity, readability, and DRY (Don’t Repeat Yourself) principles. Defined using the def keyword, Python functions support versatile parameter passing including positional arguments, keyword arguments, default parameter values, variable length positional arguments (*args), and variable-length keyword arguments (**kwargs). Python evaluates variable lookup using the LEGB (Local, Enclosing, Global, Built-in) scope hierarchy. Furthermore, Python treats functions as first-class objects, enabling anonymous functions (lambda), higher order function mapping (map, filter, reduce), decorators, and recursive problem solving. This 25-question MCQ quiz evaluates core function mechanics, offering detailed explanations to deepen your proficiency.

1. Which keyword is used to declare a user-defined function in Python?

a) func
b) def
c) function
d) define
Correct Answer: b) def
Explanation:
In Python, the 'def' keyword is used to begin a function definition, followed by the function name, parentheses, and a colon.

2. What is the default return value of a Python function that executes to completion without a return statement?

a) 0
b) False
c) None
d) Undefined
Correct Answer: c) None
Explanation:
If no return statement is encountered or an empty return is used, Python implicitly returns the None object.

3. Which of the following describes the purpose of a function docstring in Python?

a) To speed up function runtime
b) To document the purpose and usage of the function
c) To define parameter variable types at runtime
d) To encrypt the function body
Correct Answer: b) To document the purpose and usage of the function
Explanation:
A docstring is a string literal that occurs as the first statement in a function definition, used to document its behavior.

4. How can you access a function's docstring programmatically at runtime?

a) func.get_doc()
b) func.__doc__
c) func.docstring
d) doc(func)
Correct Answer: b) func.__doc__
Explanation:
The docstring of a function is stored in its special `__doc__` attribute.

5. Which parameter type allows a function to accept an arbitrary number of positional arguments?

a) *args
b) **kwargs
c) &args
d) $args
Correct Answer: a) *args
Explanation:
The `*args` parameter collects extra positional arguments passed to the function into a single tuple.

6. Inside a function, what data type is the parameter `args` when using `*args`?

a) List
b) Dictionary
c) Tuple
d) Set
Correct Answer: c) Tuple
Explanation:
Positional arguments gathered via `*args` are packed into an immutable tuple.

7. Which parameter type allows a function to accept an arbitrary number of keyword arguments?

a) *args
b) **kwargs
c) kwargs()
d) &kwargs
Correct Answer: b) **kwargs
Explanation:
The `**kwargs` parameter syntax gathers arbitrary keyword arguments into a dictionary.

8. Inside a function, what data type is `kwargs` when using `**kwargs`?

a) Tuple
b) Dictionary
c) List
d) Set
Correct Answer: b) Dictionary
Explanation:
Keyword arguments collected using `**kwargs` are stored as key-value pairs inside a standard dictionary.

9. What is the output of calling `greet()` with no arguments given the definition: `def greet(name='Guest'): return f'Hello {name}'`?

a) Hello name
b) Hello Guest
c) Hello None
d) TypeError
Correct Answer: b) Hello Guest
Explanation:
When an argument is omitted during a call, Python falls back to using the parameter's default value ('Guest').

10. What happens if a positional parameter without a default value is defined AFTER a parameter with a default value?

a) The default value is ignored
b) Python raises a SyntaxError
c) The positional parameter gets set to None
d) It executes normally
Correct Answer: b) Python raises a SyntaxError
Explanation:
Non-default parameters must always precede default parameters in a function signature.

11. What is a lambda function in Python?

a) A function that executes in parallel threads
b) An anonymous function defined with a single expression
c) A function that can only accept integer values
d) A function defined inside a class constructor
Correct Answer: b) An anonymous function defined with a single expression
Explanation:
Lambda functions are small, anonymous inline functions created using the `lambda` keyword.

12. Which statement correctly defines a lambda function that calculates the cube of a number?

a) lambda x: x ** 3
b) lambda (x) { return x ** 3; }
c) def lambda(x): return x ** 3
d) lambda x -> x ** 3
Correct Answer: a) lambda x: x ** 3
Explanation:
The syntax for a lambda function is `lambda arguments: expression`, evaluating and returning the result without an explicit `return` keyword.

13. What is the output of evaluating `(lambda a, b: a * b)(4, 5)`?

a) 20
b) 9
c) (4, 5)
d) None
Correct Answer: a) 20
Explanation:
The lambda expression is defined and immediately called with positional parameters `4` and `5`, returning `4 * 5 = 20`.

14. Which of the following defines a recursive function?

a) A function that returns multiple outputs
b) A function that calls itself in its definition
c) A function without parameters
d) A function passed as an argument to another function
Correct Answer: b) A function that calls itself in its definition
Explanation:
A recursive function calls itself directly or indirectly to divide a problem into smaller instances.

15. What is essential in a recursive function to prevent an infinite call loop?

a) A pass statement
b) A base case
c) A global variable
d) A yield statement
Correct Answer: b) A base case
Explanation:
A base case provides a stopping condition that resolves without making further recursive calls.

16. Which exception is raised when a function exceeds Python's maximum recursion limit?

a) StackOverflowError
b) RecursionError
c) MemoryError
d) DepthError
Correct Answer: b) RecursionError
Explanation:
Python raises a `RecursionError` when maximum recursion depth is reached to prevent stack overflow.

17. Which built-in module allows managing and viewing Python's maximum recursion depth?

a) os
b) sys
c) math
d) builtins
Correct Answer: b) sys
Explanation:
The `sys` module provides `sys.getrecursionlimit()` and `sys.setrecursionlimit()` to manage call stack depth.

18. Which keyword is used inside a function to rebind or modify a variable defined at the top level of a module?

a) outer
b) global
c) nonlocal
d) super
Correct Answer: b) global
Explanation:
The `global` keyword declares that a variable belongs to the global (module-level) scope.

19. Which keyword is used inside a nested function to modify a variable in the nearest enclosing non-global scope?

a) global
b) nonlocal
c) outer
d) parent
Correct Answer: b) nonlocal
Explanation:
The `nonlocal` keyword allows binding to variables declared in enclosing outer functions (excluding global scope).

20. What standard acronym represents the order in which Python resolves variable scopes?

a) LEGB
b) LIFO
c) FIFO
d) GELB
Correct Answer: a) LEGB
Explanation:
Python searches scopes in order: Local, Enclosing, Global, and Built-in (LEGB).

21. What is the output of the following code? x = 10 def func(): x = 5 func() print(x)

a) 5
b) 10
c) None
d) UnboundLocalError
Correct Answer: b) 10
Explanation:
Assigning `x = 5` inside `func()` creates a local variable `x`, leaving the global `x` unchanged at 10.

22. What error occurs if you read a variable in local scope before assigning to it, while a global variable of the same name exists?

a) NameError
b) UnboundLocalError
c) TypeError
d) ValueError
Correct Answer: b) UnboundLocalError
Explanation:
If a variable is assigned anywhere in a function, Python treats it as local throughout that function. Referencing it before assignment raises `UnboundLocalError`.

23. What is a closure in Python?

a) A block used to auto-close files
b) A nested function that retains access to variables from its enclosing scope even after the outer function finishes execution
c) A method that terminates program execution
d) A class method with global scope
Correct Answer: b) A nested function that retains access to variables from its enclosing scope even after the outer function finishes execution
Explanation:
A closure occurs when a inner function references variables from its lexical environment, preserving them after the outer function returns.

24. What is a decorator in Python?

a) A syntax rule for formatting console output
b) A function that takes another function as an argument and extends its behavior without modifying it directly
c) A method used to clear memory cache
d) A module for drawing graphics
Correct Answer: b) A function that takes another function as an argument and extends its behavior without modifying it directly
Explanation:
Decorators allow wrapping callable objects to modify or enhance their behavior dynamically.

25. Which symbol is used as syntactic sugar to apply a decorator to a function definition?

a) #
b) @
c) $
d) &
Correct Answer: b) @
Explanation:
Placing `@decorator_name` above a function definition decorates that function.

26. Which decorator from `functools` preserves metadata (like `__name__` and `__doc__`) of a decorated function?

a) @functools.wraps
b) @functools.preserve
c) @functools.keep
d) @functools.decorator
Correct Answer: a) @functools.wraps
Explanation:
`functools.wraps` is a decorator applied to the wrapper function inside a custom decorator to copy the original function's attributes.

27. What is the output of the following code? def multiply(a, b=2): return a * b print(multiply(4))

a) 8
b) 4
c) 16
d) TypeError
Correct Answer: a) 8
Explanation:
Parameter `a` receives `4`, and `b` defaults to `2`. The function computes `4 * 2 = 8`.

28. What is the output of the following code? def add_element(item, lst=[]): lst.append(item) return lst print(add_element(1)) print(add_element(2))

a) [1] then [2]
b) [1] then [1, 2]
c) [1, 2] then [1, 2]
d) [1] then []
Correct Answer: b) [1] then [1, 2]
Explanation:
Default parameter values are evaluated once when the function is defined, so mutable defaults like lists persist across calls.

29. What is the recommended Pythonic way to handle default values for mutable objects like lists or dictionaries?

a) Use tuples instead
b) Set default value to None and instantiate inside function body
c) Declare the list as global
d) Use lambda defaults
Correct Answer: b) Set default value to None and instantiate inside function body
Explanation:
Using `None` as a sentinel default value prevents unexpected side-effects caused by shared mutable instances.

30. What is the output of `(lambda *args: sum(args))(1, 2, 3, 4)`?

a) 10
b) (1, 2, 3, 4)
c) 4
d) TypeError
Correct Answer: a) 10
Explanation:
`*args` collects `(1, 2, 3, 4)` into a tuple. `sum(args)` evaluates to `10`.

31. What is the output of the following code? def check_kwargs(**kwargs): return kwargs.get('x', 100) print(check_kwargs(y=50))

a) 50
b) 100
c) 0
d) KeyError
Correct Answer: b) 100
Explanation:
Since key 'x' is not present in `kwargs`, `.get('x', 100)` falls back to returning default value `100`.

32. What does the `/` symbol in a function parameter signature signify?

a) Parameters before `/` must be positional-only
b) Parameters after `/` must be keyword-only
c) Parameters are divided into separate threads
d) Enables floating-point evaluation
Correct Answer: a) Parameters before `/` must be positional-only
Explanation:
In Python 3.8+, parameters before `/` are positional-only and cannot be passed using keyword argument syntax.

33. What does a standalone `*` in a function signature signify?

a) Parameters preceding `*` are positional-only
b) Parameters following `*` must be keyword-only
c) Enables recursive expansion
d) Ignores argument type validation
Correct Answer: b) Parameters following `*` must be keyword-only
Explanation:
A bare `*` indicates that all following parameters can only be supplied as keyword arguments.

34. What occurs when calling `func(1, b=2)` for signature `def func(a, b, /): return a + b`?

a) Returns 3
b) TypeError: b is positional-only
c) SyntaxError
d) ValueError
Correct Answer: b) TypeError: b is positional-only
Explanation:
`b` appears before `/`, making it positional-only. Passing `b=2` as a keyword argument causes a `TypeError`.

35. How are multiple values returned from a single Python function?

a) By using multiple return statements in sequence
b) By comma-separating values in the return statement (returns a tuple)
c) Python can only return one value per function
d) By using yield along with return
Correct Answer: b) By comma-separating values in the return statement (returns a tuple)
Explanation:
Executing `return a, b` packs values into a tuple object returned to the caller.

36. What is the output of the following code? def calculate(a, b): return a + b, a - b x, y = calculate(10, 4) print(x, y)

a) 14 6
b) (14, 6)
c) 10 4
d) TypeError
Correct Answer: a) 14 6
Explanation:
`calculate` returns tuple `(14, 6)`, unpacked into `x = 14` and `y = 6`.

37. What will be printed by this code? def outer(): msg = 'Hello' def inner(): nonlocal msg msg = 'World' inner() return msg print(outer())

a) Hello
b) World
c) None
d) NameError
Correct Answer: b) World
Explanation:
The `nonlocal` keyword allows `inner()` to rebind `msg` in `outer()`'s scope to 'World'.

38. Which built-in function returns a dictionary representing the local symbol table of the current scope?

a) globals()
b) locals()
c) vars()
d) dir()
Correct Answer: b) locals()
Explanation:
`locals()` returns a dictionary containing current local namespace bindings.

39. Which higher-order built-in function applies a given function to all items in an iterable?

a) filter()
b) map()
c) reduce()
d) zip()
Correct Answer: b) map()
Explanation:
`map(func, iterable)` yields an iterator that transforms elements by applying `func` to each.

40. Where was the `reduce()` function relocated in Python 3?

a) builtins
b) functools
c) itertools
d) operator
Correct Answer: b) functools
Explanation:
In Python 3, `reduce()` was moved from built-in scope to the `functools` standard module.

41. What is the result of `list(map(lambda x: x ** 2, [1, 2, 3]))`?

a) [1, 2, 3]
b) [1, 4, 9]
c) [2, 4, 6]
d) [1, 8, 27]
Correct Answer: b) [1, 4, 9]
Explanation:
The lambda squares each element in `[1, 2, 3]`, resulting in `[1, 4, 9]`.

42. What is the result of `list(filter(lambda x: x > 2, [1, 2, 3, 4]))`?

a) [1, 2]
b) [3, 4]
c) [1, 2, 3, 4]
d) [True, True]
Correct Answer: b) [3, 4]
Explanation:
`filter()` retains items where the predicate lambda evaluates to `True` (`x > 2`).

43. What term describes functions that accept other functions as parameters or return them?

a) Pure functions
b) Higher-order functions
c) Anonymous functions
d) Static methods
Correct Answer: b) Higher-order functions
Explanation:
Higher-order functions operate on other functions by receiving them as arguments or returning them.

44. What does it mean that functions are 'first-class citizens' in Python?

a) Functions execute with administrator permissions
b) Functions can be passed as arguments, assigned to variables, and returned from other functions
c) Functions are executed before top-level scripts
d) Functions cannot be modified at runtime
Correct Answer: b) Functions can be passed as arguments, assigned to variables, and returned from other functions
Explanation:
First-class status means functions are treated like any other object value in Python.

45. What is the output of the following code? def double(x): return x * 2 f = double print(f(6))

a) 12
b) 6
c) TypeError
d) None
Correct Answer: a) 12
Explanation:
Assigning `f = double` creates a reference alias to `double`. Calling `f(6)` yields `12`.

46. Which definition best describes a 'pure function'?

a) A function that has no parameters
b) A function that produces deterministic outputs for identical inputs with no observable side-effects
c) A function written without return statements
d) A function compiled into machine binary
Correct Answer: b) A function that produces deterministic outputs for identical inputs with no observable side-effects
Explanation:
Pure functions depend exclusively on input arguments and do not mutate global state.

47. Which `functools` class allows creating partial function applications by fixing a portion of arguments?

a) partial
b) freeze
c) curry
d) wrap
Correct Answer: a) partial
Explanation:
`functools.partial(func, *args, **keywords)` returns a new callable object with fixed arguments.

48. What is the output of the following code? from functools import partial def power(base, exponent): return base ** exponent square = partial(power, exponent=2) print(square(5))

a) 10
b) 25
c) 32
d) TypeError
Correct Answer: b) 25
Explanation:
`square` fixes `exponent=2`. Calling `square(5)` sets `base=5`, computing `5 ** 2 = 25`.

49. What is the output of `func(2, c=30)` for `def func(a, b=10, c=20): return a + b + c`?

a) 42
b) 52
c) 32
d) TypeError
Correct Answer: a) 42
Explanation:
`a=2`, `b` uses default `10`, `c` is passed as `30`. Sum: `2 + 10 + 30 = 42`.

50. What occurs when using `func(**d)` where `d = {'a': 3, 'b': 4}` and `def func(a, b): return a * b`?

a) Passes dictionary `d` to argument `a`
b) Unpacks dictionary keys as keyword arguments `a=3, b=4`, returning 12
c) Raises a SyntaxError
d) Unpacks keys as positional strings
Correct Answer: b) Unpacks dictionary keys as keyword arguments `a=3, b=4`, returning 12
Explanation:
The `**` operator unpacks dictionary key-value pairs into matching keyword parameters.

51. What is the output of `func(*p)` where `p = (8, 2)` and `def func(x, y): return x // y`?

a) 4
b) 0
c) (8, 2)
d) TypeError
Correct Answer: a) 4
Explanation:
The `*` operator unpacks sequence tuple `(8, 2)` into positional arguments `x=8` and `y=2`, computing `8 // 2 = 4`.

52. Which keyword turns a standard function into a generator function?

a) generate
b) yield
c) return
d) async
Correct Answer: b) yield
Explanation:
Presence of the `yield` statement inside a function turns it into a generator function.

53. What happens when execution encounters a `yield` statement inside a generator?

a) Terminates the function completely
b) Pauses execution, saves state, and returns value to caller
c) Raises StopIteration immediately
d) Restarts generator from the beginning
Correct Answer: b) Pauses execution, saves state, and returns value to caller
Explanation:
`yield` suspends generator state and emits a value, allowing resumption on the next `next()` call.

54. What exception indicates that a generator iterator has no more elements to produce?

a) GeneratorExit
b) StopIteration
c) EndIteration
d) IndexError
Correct Answer: b) StopIteration
Explanation:
When a generator function completes execution without yielding further, Python raises `StopIteration`.

55. What is the output of the following code? def my_gen(): yield 10 yield 20 g = my_gen() print(next(g), next(g))

a) 10 10
b) 10 20
c) 20 20
d) StopIteration
Correct Answer: b) 10 20
Explanation:
The first `next(g)` yields `10`; the second `next(g)` resumes and yields `20`.

56. Which construct introduced in Python 3.5 declares asynchronous coroutines?

a) async def
b) def async()
c) coroutine def
d) thread def
Correct Answer: a) async def
Explanation:
Coroutines are defined using `async def` syntax.

57. Which keyword pauses coroutine execution until an awaitable object yields a result?

a) wait
b) await
c) pause
d) yield from
Correct Answer: b) await
Explanation:
The `await` keyword suspends execution of an `async def` coroutine until the target complete.

58. What is the output of the following code? x = 1 def outer(): x = 2 def inner(): global x x = 3 inner() return x print(outer(), x)

a) 2 3
b) 3 3
c) 2 1
d) 3 1
Correct Answer: a) 2 3
Explanation:
`inner()` updates global `x` to 3. `outer()`'s local `x` stays 2. Thus `outer()` returns 2 and global `x` prints 3.

59. Which syntax feature allows attaching parameter and return value type hints to functions?

a) Function decorators
b) Function annotations
c) Docstrings
d) Class metadata
Correct Answer: b) Function annotations
Explanation:
Function annotations provide type hint syntax, e.g., `def add(a: int) -> int:`.

60. Under which attribute are function type annotations stored?

a) func.__doc__
b) func.__annotations__
c) func.__types__
d) func.__hints__
Correct Answer: b) func.__annotations__
Explanation:
Type annotations are accessible via the `__annotations__` dictionary attribute.

61. Does standard Python enforce function type annotations at runtime?

a) Yes, raises TypeError on type mismatch
b) No, annotations are ignored at runtime and used by static type analyzers
c) Yes, in debug mode only
d) Only inside lambda expressions
Correct Answer: b) No, annotations are ignored at runtime and used by static type analyzers
Explanation:
Python does not automatically enforce type annotations at runtime; they serve as metadata for analyzers like mypy.

62. What happens when executing `def add(a: int, b: int) -> int: return a + b` called with `add('Py', 'thon')`?

a) Raises TypeError at runtime
b) Returns 'Python'
c) Returns None
d) SyntaxError
Correct Answer: b) Returns 'Python'
Explanation:
Because annotations are unenforced metadata at runtime, string concatenation occurs normally.

63. What is the output of the following code? def make_adder(n): return lambda x: x + n add_five = make_adder(5) print(add_five(10))

a) 15
b) 5
c) 10
d) TypeError
Correct Answer: a) 15
Explanation:
`make_adder(5)` creates a closure with `n=5`. Calling `add_five(10)` returns `10 + 5 = 15`.

64. What optimization technique caches previous outputs of expensive function calls based on arguments?

a) Memoization
b) Garbage collection
c) Trampolining
d) Reflection
Correct Answer: a) Memoization
Explanation:
Memoization optimizes execution speed by storing computed call results indexed by input arguments.

65. Which `functools` decorator provides built-in LRU memoization caching for functions?

a) @functools.lru_cache
b) @functools.memoize
c) @functools.cache_all
d) @functools.remember
Correct Answer: a) @functools.lru_cache
Explanation:
`functools.lru_cache` wraps functions with a Least Recently Used lookup cache.

66. What is Tail Call Optimization (TCO)?

a) Optimization where recursive calls in tail position reuse current stack frames
b) Automatic loop unrolling in all functions
c) Memory clearing for unused global variables
d) Converting recursive functions to lambda expressions
Correct Answer: a) Optimization where recursive calls in tail position reuse current stack frames
Explanation:
TCO prevents stack frame growth when recursive calls form the final execution action in a function.

67. Does standard CPython support automatic Tail Call Optimization?

a) Yes, for all functions
b) No, CPython intentionally omits TCO to preserve full stack traces
c) Yes, when run with -O flag
d) Only inside generator expressions
Correct Answer: b) No, CPython intentionally omits TCO to preserve full stack traces
Explanation:
CPython does not implement TCO, prioritizing accurate stack frame debugging information.

68. What is the output of the following code? def f(x=[]): x.append(1) return x print(f(), f())

a) [1] [1]
b) [1, 1] [1, 1]
c) [1] [1, 1]
d) TypeError
Correct Answer: b) [1, 1] [1, 1]
Explanation:
`f()` shares a single default list instance. Both calls mutate this instance, and both printed values reference the same updated list (`[1, 1]`).

69. What is the output of `f(*t)` where `t = (10, 20)` and `def f(a, b): print(a, b)`?

a) 10 20
b) (10, 20) None
c) TypeError
d) 20 10
Correct Answer: a) 10 20
Explanation:
`*t` unpacks tuple values into positional arguments `a = 10` and `b = 20`.

70. What will be printed by this code? funcs = [] for i in range(3): funcs.append(lambda: i) for f in funcs: print(f(), end=' ')

a) 0 1 2
b) 2 2 2
c) 0 0 0
d) 1 2 3
Correct Answer: b) 2 2 2
Explanation:
Lambdas bind to variable `i` lazily. When called after the loop finishes, `i` evaluates to 2 for all stored lambdas.

71. How can you fix late-binding issues when creating lambdas inside loops?

a) Use default parameter arguments: `lambda i=i: i`
b) Use global statements inside lambda
c) Use nonlocal statements inside lambda
d) Cast loop variable to tuple
Correct Answer: a) Use default parameter arguments: `lambda i=i: i`
Explanation:
Setting default arguments `i=i` binds current loop value immediately during iteration.

72. What is the output of the fixed code snippet: `funcs = [lambda i=i: i for i in range(3)]; [print(f(), end=' ') for f in funcs]`?

a) 2 2 2
b) 0 1 2
c) 0 0 0
d) 3 3 3
Correct Answer: b) 0 1 2
Explanation:
Default argument evaluation binds values at function creation time, capturing 0, 1, and 2.

73. In Python 3.3+, where is the return value of a generator stored when a return statement executes inside it?

a) On the `value` attribute of the raised `StopIteration` exception
b) It is discarded completely
c) In `sys.last_value`
d) In the generator docstring
Correct Answer: a) On the `value` attribute of the raised `StopIteration` exception
Explanation:
When a generator returns a value, Python attaches that object to `StopIteration.value`.

74. What does the `yield from` expression accomplish in generator functions?

a) Delegates generation iteration to a subgenerator or iterable
b) Clears the generator memory cache
c) Yields values from global scope
d) Converts generator to list
Correct Answer: a) Delegates generation iteration to a subgenerator or iterable
Explanation:
`yield from ` delegates iteration directly to another generator or iterable sequence.

75. What is the output of `list(gen())` given `def sub(): yield 1; yield 2` and `def gen(): yield from sub(); yield 3`?

a) [1, 2, 3]
b) [1, 3]
c) [sub, 3]
d) TypeError
Correct Answer: a) [1, 2, 3]
Explanation:
`yield from sub()` exhausts yields 1 and 2, followed by `yield 3`, giving `[1, 2, 3]`.

76. What will be printed by this code? def decorator(f): def wrapper(): return f().upper() return wrapper @decorator def greet(): return 'hello' print(greet())

a) hello
b) HELLO
c) None
d) AttributeError
Correct Answer: b) HELLO
Explanation:
The decorator replaces `greet` with `wrapper`, which transforms the return value to uppercase.

77. What happens to a function's `__name__` when wrapped by a simple decorator WITHOUT using `functools.wraps`?

a) It remains unchanged
b) It changes to the wrapper function's name ('wrapper')
c) It raises an AttributeError
d) It becomes None
Correct Answer: b) It changes to the wrapper function's name ('wrapper')
Explanation:
Without `@wraps`, the original function attributes are shadowed by the inner wrapper function.

78. Which function delegates method calls to parent or sibling classes according to Method Resolution Order (MRO)?

a) super()
b) parent()
c) base()
d) this()
Correct Answer: a) super()
Explanation:
`super()` returns a proxy object delegating method calls to parent/sibling classes in MRO.

79. Which attribute of a function object references its underlying compiled bytecode object?

a) func.__code__
b) func.__bytecode__
c) func.__compiled__
d) func.__asm__
Correct Answer: a) func.__code__
Explanation:
The executable compiled code object of a function is stored in its `__code__` attribute.

80. Which attribute on a function's code object lists local variable names?

a) func.__code__.co_varnames
b) func.__code__.co_locals
c) func.__code__.co_names
d) func.__code__.co_vars
Correct Answer: a) func.__code__.co_varnames
Explanation:
`co_varnames` is a tuple containing local variable names starting with function parameters.

81. Which attribute on a function stores a tuple of cell objects binding closure free variables?

a) func.__closure__
b) func.__env__
c) func.__captured__
d) func.__nonlocal__
Correct Answer: a) func.__closure__
Explanation:
If a function is a closure, `__closure__` contains cell objects holding bound free variables.

82. What is the output of `f(5).__closure__[0].cell_contents` for `def f(x): return lambda: x`?

a) 5
b) x
c) None
d) TypeError
Correct Answer: a) 5
Explanation:
`cell_contents` retrieves the bound object (`5`) enclosed inside the cell.

83. Which standard module provides live introspection tools to analyze function signatures and parameters?

a) inspect
b) sys
c) ast
d) dis
Correct Answer: a) inspect
Explanation:
The `inspect` module provides functions like `inspect.signature()` to introspect parameters and callables.

84. What is returned by `inspect.signature(func)`?

a) A Signature object mapping parameters and return annotations
b) A string copy of docstring
c) A list of bytecode instructions
d) A memory address integer
Correct Answer: a) A Signature object mapping parameters and return annotations
Explanation:
`inspect.signature()` extracts structured parameter and return annotation metadata.

85. What is the output of `len(inspect.signature(f).parameters)` for `def f(a, b=10, *args): pass`?

a) 3
b) 2
c) 1
d) 4
Correct Answer: a) 3
Explanation:
The `parameters` mapping tracks 'a', 'b', and 'args', giving a length of 3.

86. What happens if a positional argument is passed AFTER a keyword argument in function invocation?

a) Positional argument takes priority
b) Raises SyntaxError: positional argument follows keyword argument
c) Keyword argument is discarded
d) Executes normally
Correct Answer: b) Raises SyntaxError: positional argument follows keyword argument
Explanation:
Syntax rules require positional arguments to precede keyword arguments during invocation.

87. What is the output of calling `test(a=1, 2)`?

a) SyntaxError
b) 1 2
c) TypeError
d) 2 1
Correct Answer: a) SyntaxError
Explanation:
Positional argument `2` appears after keyword argument `a=1`, causing a `SyntaxError`.

88. What is the output of `add_all()` given `def add_all(*numbers): return sum(numbers)`?

a) 0
b) None
c) TypeError
d) ValueError
Correct Answer: a) 0
Explanation:
`*numbers` receives an empty tuple `()`. `sum(())` evaluates to `0`.

89. Which function signature accepts any arbitrary combination of positional and keyword arguments?

a) def f(*args, **kwargs): pass
b) def f(args, kwargs): pass
c) def f(all): pass
d) def f(*kwargs, **args): pass
Correct Answer: a) def f(*args, **kwargs): pass
Explanation:
Combining `*args` and `**kwargs` allows capturing any positional and keyword parameters.

90. What is the output of `func(1, z=5)` for `def func(a, b=2, c=3): return a + b + c`?

a) SyntaxError
b) TypeError
c) 8
d) 6
Correct Answer: b) TypeError
Explanation:
Signature defines `c`, but keyword argument passes `z=5`, raising a `TypeError: got an unexpected keyword argument 'z'`.

91. What happens when a parameter name in a function scope matches a global variable name?

a) Global variable takes priority inside function
b) Parameter shadows the global variable within function scope
c) Raises NameError
d) Raises SyntaxError
Correct Answer: b) Parameter shadows the global variable within function scope
Explanation:
Local parameters shadow outer variables of the same identifier name inside function scope.

92. What will be printed by this code? x = 5 def f(x): x = x + 1 return x f(10) print(x)

a) 11
b) 5
c) 10
d) UnboundLocalError
Correct Answer: b) 5
Explanation:
Assigning to local parameter `x` alters local scope only, leaving global `x` set to `5`.

93. Which built-in function yields the unique integer memory address identity of a function object?

a) id()
b) hash()
c) addr()
d) ref()
Correct Answer: a) id()
Explanation:
`id()` returns the unique memory address identity of an object.

94. What is the result of `type(def_func)` for `def def_func(): pass`?

a)
b)
c)
d)
Correct Answer: a)
Explanation:
User-defined functions belong to instance type ``.

95. Which restriction applies strictly to lambda functions in Python?

a) Cannot accept parameters
b) Restricted to evaluating a single expression
c) Cannot return integer values
d) Cannot be assigned to variables
Correct Answer: b) Restricted to evaluating a single expression
Explanation:
Lambda function bodies are limited to a single expression that evaluates to a return value.

96. What is the output of `f()` for `f = lambda: 'Yes'`?

a) Yes
b)
c) None
d) SyntaxError
Correct Answer: a) Yes
Explanation:
A parameterless lambda evaluates and returns string literal `'Yes'` when invoked.

97. What is the default return value of `dict.get('key')` when 'key' is absent?

a) None
b) 0
c) False
d) KeyError
Correct Answer: a) None
Explanation:
`dict.get()` returns `None` by default when the target key is missing.

98. What is the output of `f(b=2, a=8)` for `def f(a, b): return a / b`?

a) 4.0
b) 0.25
c) TypeError
d) 4
Correct Answer: a) 4.0
Explanation:
Keyword arguments map explicit parameter names regardless of order: `a=8, b=2`, computing `8 / 2 = 4.0`.

99. Which attribute on a function object contains default positional parameter values?

a) func.__defaults__
b) func.__args__
c) func.__kwdefaults__
d) func.__parameters__
Correct Answer: a) func.__defaults__
Explanation:
Positional default argument values are saved as a tuple in `__defaults__`.

100. Which attribute on a function object contains default keyword-only parameter values?

a) func.__kwdefaults__
b) func.__defaults__
c) func.__dict__
d) func.__annotations__
Correct Answer: a) func.__kwdefaults__
Explanation:
`__kwdefaults__` stores a dictionary of default values for keyword-only parameters.

101. What is the output of `f.__kwdefaults__` for `def f(*, a=1, b=2): return a + b`?

a) {'a': 1, 'b': 2}
b) (1, 2)
c) None
d) TypeError
Correct Answer: a) {'a': 1, 'b': 2}
Explanation:
`__kwdefaults__` returns a dictionary mapping keyword-only parameter names to default values.

102. What exception occurs if a required keyword-only argument is omitted during invocation?

a) TypeError
b) KeyError
c) ValueError
d) AttributeError
Correct Answer: a) TypeError
Explanation:
Failing to supply a non-default keyword-only parameter raises a `TypeError`.

103. What is the output of `f(1, 2, 3, c=4)` for `def f(a, *b, c): return a + sum(b) + c`?

a) 10
b) 6
c) 4
d) TypeError
Correct Answer: a) 10
Explanation:
`a=1`, `b=(2, 3)`, `c=4`. Sum: `1 + (2 + 3) + 4 = 10`.

104. Can function keyword parameters be unpacked directly from dictionary keys in Python?

a) Yes, using the `**` operator in function calls
b) No, parameters must be extracted manually first
c) Only if keys are integers
d) Only inside class declarations
Correct Answer: a) Yes, using the `**` operator in function calls
Explanation:
Passing `func(**my_dict)` maps dictionary keys directly to matching keyword arguments.

105. What is the result of `list(filter(None, [0, 1, False, 2, '', 'a']))`?

a) [1, 2, 'a']
b) [0, False, '']
c) [0, 1, False, 2, '', 'a']
d) TypeError
Correct Answer: a) [1, 2, 'a']
Explanation:
Passing `None` as predicate to `filter()` removes falsey items, keeping truthy items (`[1, 2, 'a']`).

106. What design pattern allows calling multiple methods sequentially (`obj.step1().step2()`)?

a) Method chaining
b) Recursion
c) Decorators
d) Currying
Correct Answer: a) Method chaining
Explanation:
Method chaining relies on methods returning object references (`return self`) to allow consecutive calls.

107. What will be printed by this code? def f(): yield 1 return 'done' g = f() next(g) try: next(g) except StopIteration as e: print(e.value)

a) done
b) 1
c) None
d) StopIteration
Correct Answer: a) done
Explanation:
The value returned from a generator is stored on the `value` attribute of the raised `StopIteration` exception.

108. What is the output of `apply(double, 5)` where `def double(x): return x * 2` and `def apply(func, val): return func(val)`?

a) 10
b) 25
c) 5
d) TypeError
Correct Answer: a) 10
Explanation:
`apply` receives reference to `double` and invokes `double(5)`, returning `10`.

109. What happens if a decorator fails to return a wrapper function or replacement object?

a) The decorated function name gets bound to None
b) The decorated function executes normally
c) Raises SyntaxError
d) Python auto-injects a return statement
Correct Answer: a) The decorated function name gets bound to None
Explanation:
Decorators replace decorated functions with their return value. If no return statement is executed, `None` is returned.

110. What is the output of accessing `add` in: `def my_dec(f): pass; @my_dec def add(a, b): return a + b`?

a) None
b)
c) TypeError
d) NameError
Correct Answer: a) None
Explanation:
`my_dec` returns `None`. Thus, variable binding for `add` becomes `None`.

111. How are arguments passed into decorators themselves (decorator factories)?

a) By adding an extra enclosing function layer that takes parameters and returns a decorator
b) By using `@decorator(args)` directly without additional wrappers
c) By passing arguments into `*args` of the inner wrapper
d) By using global variables
Correct Answer: a) By adding an extra enclosing function layer that takes parameters and returns a decorator
Explanation:
A decorator factory uses three nested function levels: factory(args) -> decorator(func) -> wrapper(*args).

112. What is the output of calling `inc()` decorated by `@repeat(3)` where `repeat` executes the target function 3 times?

a) Executes target 3 times
b) Executes target 1 time
c) Raises TypeError
d) Executes target endlessly
Correct Answer: a) Executes target 3 times
Explanation:
A decorator factory parameterizes wrapper execution loops, repeating function invocation.

113. Which of the following is true regarding parameter variables in Python?

a) Function parameters are local to function scope
b) Function parameters belong to global scope
c) Function parameters persist in memory indefinitely
d) Function parameters can be accessed directly outside function execution
Correct Answer: a) Function parameters are local to function scope
Explanation:
Parameters act as local variables initialized upon function call and discarded upon return.

114. What is the output of `print(f(1), f('a'))` given `def f(x): return x`?

a) 1 a
b) 1 1
c) a a
d) TypeError
Correct Answer: a) 1 a
Explanation:
Python dynamically handles passing different object types as function parameters.

115. What occurs when calling `func(1, a=2)` for `def func(a): pass`?

a) TypeError: got multiple values for argument 'a'
b) Keyword argument overrides positional argument
c) Positional argument overrides keyword argument
d) Returns tuple (1, 2)
Correct Answer: a) TypeError: got multiple values for argument 'a'
Explanation:
Passing both a positional argument and keyword argument for the same parameter name causes a `TypeError`.

116. What is the output of `f(2, c=4)` for `def f(a, b=2, c=3): return a * b * c`?

a) 16
b) 24
c) 12
d) TypeError
Correct Answer: a) 16
Explanation:
`a=2`, default `b=2`, passed `c=4`. Product: `2 * 2 * 4 = 16`.

117. Which operator unpacks sequence iterables into positional arguments?

a) *
b) **
c) &
d) @
Correct Answer: a) *
Explanation:
The single asterisk `*` operator unpacks iterables into positional arguments.

118. Which operator unpacks dictionaries into keyword arguments?

a) **
b) *
c) $
d) ->
Correct Answer: a) **
Explanation:
The double asterisk `**` operator unpacks dictionaries into keyword arguments.

119. What is the output of `type(f(1, 2))` given `def f(x, y): return x, y`?

a)
b)
c)
d)
Correct Answer: a)
Explanation:
Multiple comma-separated values in a return statement are automatically packed into a tuple.

120. What action occurs when appending empty parentheses `()` to a function variable?

a) Invokes function execution
b) Prints function memory address
c) Deletes function instance
d) Returns function reference
Correct Answer: a) Invokes function execution
Explanation:
Parentheses `()` execute the callable object.

121. What happens if you reference a function name `f` WITHOUT trailing parentheses?

a) Evaluates to the function object reference without calling it
b) Calls function with default arguments
c) Raises SyntaxError
d) Returns None
Correct Answer: a) Evaluates to the function object reference without calling it
Explanation:
Omitting parentheses accesses the function object directly.

122. What is the output of `a()` given `def greet(): return 'Hi'; a = greet`?

a) Hi
b)
c) None
d) TypeError
Correct Answer: a) Hi
Explanation:
`a` stores a reference alias to `greet`. Invoking `a()` executes `greet()`, returning 'Hi'.

123. What is the default start parameter value in `sum(iterable, start=0)`?

a) 0
b) 1
c) None
d) False
Correct Answer: a) 0
Explanation:
The `sum()` function initializes the summation with `start=0` by default.

124. What is the output of `sum([1, 2, 3], 10)`?

a) 16
b) 6
c) 10
d) TypeError
Correct Answer: a) 16
Explanation:
`start` is set to `10`. Sum: `10 + (1 + 2 + 3) = 16`.

125. What is the output of `f(0)` for `def f(x): return 'zero' if x == 0 else 'non-zero'`?

a) zero
b) non-zero
c) None
d) 0
Correct Answer: a) zero
Explanation:
The expression evaluates `x == 0` as `True`, returning string `'zero'`.

126. What happens when multiple return statements exist in a function's execution branch?

a) Terminates execution upon encountering the first executable return statement
b) Combines outputs into a list
c) Raises SyntaxError
d) Executes last return statement only
Correct Answer: a) Terminates execution upon encountering the first executable return statement
Explanation:
Executing a return statement immediately terminates function execution and exits to the caller.

127. What is the output of `f()` for `def f(): return 1; return 2`?

a) 1
b) 2
c) (1, 2)
d) None
Correct Answer: a) 1
Explanation:
The function returns `1` immediately, ignoring the unreachable `return 2` statement.

128. Can Python functions be defined inside other functions?

a) Yes, known as inner or nested functions
b) No, function definitions must strictly be top-level module statements
c) Only inside class methods
d) Only when using lambda expressions
Correct Answer: a) Yes, known as inner or nested functions
Explanation:
Python supports nested function declarations within outer function scopes.

129. What is the output of `outer()` for `def outer(): def inner(): return 'Inner'; return inner()`?

a) Inner
b)
c) None
d) NameError
Correct Answer: a) Inner
Explanation:
`outer()` invokes nested function `inner()`, returning string `'Inner'`.

130. What happens if you attempt to invoke `inner()` directly from global scope after defining it inside `outer()`?

a) Raises NameError: name 'inner' is not defined
b) Executes inner function normally
c) Returns None
d) AttributeError
Correct Answer: a) Raises NameError: name 'inner' is not defined
Explanation:
`inner` is scoped locally to `outer()` and invisible to global scope.

131. What structure manages active function calls and local execution context frames?

a) Call stack
b) Heap array
c) Generator buffer
d) Global symbol table
Correct Answer: a) Call stack
Explanation:
The call stack manages active execution frames representing nested function invocations.

132. Which function in the `inspect` module retrieves active call stack frame records?

a) inspect.stack()
b) inspect.frames()
c) inspect.current()
d) inspect.trace()
Correct Answer: a) inspect.stack()
Explanation:
`inspect.stack()` returns a list of frame records for the caller's stack.

133. What is the output of `f.__code__.co_argcount` for `def f(a, b, c=3): pass`?

a) 3
b) 2
c) 1
d) 0
Correct Answer: a) 3
Explanation:
`co_argcount` tracks total positional parameters (including default parameters).

134. Are `*args` and `**kwargs` included in `co_argcount`?

a) No, variable argument collectors are not included in `co_argcount`
b) Yes, each adds 1 to `co_argcount`
c) Only `*args` is included
d) Only `**kwargs` is included
Correct Answer: a) No, variable argument collectors are not included in `co_argcount`
Explanation:
Variable argument parameters (`*args`, `**kwargs`) are stored separately in code object flags.

135. What is the output of `f.__code__.co_argcount` for `def f(*args): pass`?

a) 0
b) 1
c) -1
d) None
Correct Answer: a) 0
Explanation:
The function has 0 positional parameters; `*args` does not increment `co_argcount`.

136. Which descriptor method binds function instances to class objects creating bound methods?

a) __get__
b) __bind__
c) __call__
d) __init__
Correct Answer: a) __get__
Explanation:
Functions implement the descriptor protocol via `__get__` to return bound method objects.

137. What distinguishes a bound method from an unbound function in Python 3?

a) A bound method automatically passes instance object as first argument `self`
b) Functions accept parameters while methods do not
c) Methods are defined using lambda expressions
d) Functions cannot be defined inside class definitions
Correct Answer: a) A bound method automatically passes instance object as first argument `self`
Explanation:
Bound methods bind an instance reference (`self`) automatically as the first parameter.

138. What is returned by `type(a.m)` where `a` is an instance of class `A` containing method `m`?

a)
b)
c)
d)
Correct Answer: a)
Explanation:
Accessing a method via an instance returns a bound `` object.

139. What is returned by `type(A.m)` when accessed via class `A` directly in Python 3?

a)
b)
c)
d)
Correct Answer: a)
Explanation:
Accessing a method directly through the class `A.m` yields an unbound standard ``.

140. Which decorator binds a method parameter to the class object (`cls`) rather than an instance?

a) @classmethod
b) @staticmethod
c) @property
d) @instancemethod
Correct Answer: a) @classmethod
Explanation:
`@classmethod` transforms a method into a class method receiving `cls` as its first parameter.

141. Which decorator prevents automatic parameter binding of `self` or `cls`?

a) @staticmethod
b) @classmethod
c) @property
d) @abstractmethod
Correct Answer: a) @staticmethod
Explanation:
`@staticmethod` prevents descriptor binding behavior, behaving like a standard function residing inside a class namespace.

142. What is the output of `Math.add(3, 4)` given `class Math: @staticmethod def add(a, b): return a + b`?

a) 7
b) TypeError
c) None
d) 12
Correct Answer: a) 7
Explanation:
Invoking the static method passes `a=3` and `b=4`, returning `7`.

143. What is the `@property` decorator used for in Python classes?

a) To define getter methods that can be accessed like attributes
b) To mark methods as private
c) To optimize computation speed
d) To auto-generate unit tests
Correct Answer: a) To define getter methods that can be accessed like attributes
Explanation:
`@property` enables attribute-access syntax (`obj.attr`) that transparently calls underlying getter functions.

144. What is the output of `c.x` given `class C: @property def x(self): return 42; c = C()`?

a) 42
b)
c) TypeError
d) None
Correct Answer: a) 42
Explanation:
Accessing property `c.x` invokes the underlying getter method, returning `42`.

145. What exception is raised when assigning a value to a read-only property without a defined setter?

a) AttributeError: can't set attribute
b) TypeError
c) ValueError
d) KeyError
Correct Answer: a) AttributeError: can't set attribute
Explanation:
Attempting to assign a value to a property lacking a setter method raises an `AttributeError`.

146. Which statement serves as a null placeholder inside empty function definitions?

a) pass
b) continue
c) break
d) skip
Correct Answer: a) pass
Explanation:
`pass` serves as a syntactically valid null operation placeholder.

147. Is an Ellipsis literal (`...`) syntactically valid as a body placeholder inside Python functions?

a) Yes, `...` is syntactically valid in function bodies
b) No, causes SyntaxError
c) Only inside class methods
d) Only when type hints are present
Correct Answer: a) Yes, `...` is syntactically valid in function bodies
Explanation:
The `...` (Ellipsis) literal is a valid statement placeholder in function bodies.

148. What is the output of `f()` given `def f(): ...`?

a) None
b) Ellipsis
c) SyntaxError
d) ...
Correct Answer: a) None
Explanation:
A function with body `...` executes to completion without return, implicitly returning `None`.

149. What is the output of `f.__doc__` for `def f(x): '''Sample''' return x`?

a) Sample
b) None
c) x
d) f
Correct Answer: a) Sample
Explanation:
The docstring string literal is stored in and retrieved from the `__doc__` attribute.

150. What is the output of `callable(print)`?

a) True
b) False
c) None
d) TypeError
Correct Answer: a) True
Explanation:
Built-in `print` is a callable function object, so `callable(print)` returns `True`.

151. Which built-in function checks whether an object appears callable?

a) callable()
b) is_func()
c) can_call()
d) executable()
Correct Answer: a) callable()
Explanation:
`callable(obj)` returns `True` if the argument object implements a `__call__()` method.

152. Which special dunder method allows instances of a class to be invoked like functions?

a) __call__()
b) __invoke__()
c) __run__()
d) __exec__()
Correct Answer: a) __call__()
Explanation:
Defining `__call__()` on a class makes its instances callable using parentheses.

153. What is the output of `add5(10)` given `class Adder: def __init__(self, v): self.v = v; def __call__(self, x): return self.v + x; add5 = Adder(5)`?

a) 15
b) 5
c) 10
d) TypeError
Correct Answer: a) 15
Explanation:
Calling `add5(10)` triggers `__call__(10)`, returning `5 + 10 = 15`.

154. What process fixes a subset of arguments on a multi-argument function to create a new callable?

a) Partial function application
b) Function compilation
c) Method override
d) Type casting
Correct Answer: a) Partial function application
Explanation:
Partial application binds argument values to produce a callable with fewer remaining parameters.

155. What is currying in functional programming?

a) Translating evaluation of a function with multiple arguments into a sequence of functions taking single arguments
b) Merging multiple functions into a single list
c) Converting function parameters to strings
d) Optimizing loop speed
Correct Answer: a) Translating evaluation of a function with multiple arguments into a sequence of functions taking single arguments
Explanation:
Currying transforms `f(a, b, c)` into a chain of single-argument calls `f(a)(b)(c)`.

156. What is the output of `curried_add(3)(4)` given `curried_add = lambda a: lambda b: a + b`?

a) 7
b) 12
c) 34
d) TypeError
Correct Answer: a) 7
Explanation:
`curried_add(3)` returns a lambda with `a=3`. Invoking it with `(4)` computes `3 + 4 = 7`.

157. What happens if two functions are defined with identical names in the same scope?

a) The second function overwrites the first definition
b) Python raises a RedefinitionError
c) Both function bodies are merged
d) The first definition is preserved
Correct Answer: a) The second function overwrites the first definition
Explanation:
Function definitions bind names to objects; defining a duplicate identifier rebinds the variable to the new function.

158. What is the output of calling `f()` given `def f(): return 'first'` followed by `def f(): return 'second'`?

a) second
b) first
c) SyntaxError
d) TypeError
Correct Answer: a) second
Explanation:
The second definition rebinds name `f`, so `f()` returns `'second'`.

159. Does Python support native compile-time function overloading based on argument types?

a) No, subsequent function definitions overwrite earlier ones with the same name
b) Yes, functions automatically overload by parameter type
c) Yes, but only for integer parameters
d) Only inside class definitions
Correct Answer: a) No, subsequent function definitions overwrite earlier ones with the same name
Explanation:
Python does not support traditional compile-time function overloading out of the box.

160. Which `functools` decorator provides single-dispatch generic function behavior based on the type of the first argument?

a) @functools.singledispatch
b) @functools.overload
c) @functools.dispatch
d) @functools.multimethod
Correct Answer: a) @functools.singledispatch
Explanation:
`@singledispatch` transforms a function into a generic function with single-dispatch type implementations.

161. What is the purpose of `@typing.overload` in Python?

a) To supply type checker hints for multiple call signatures without providing runtime implementations
b) To enforce runtime function signature checks
c) To convert recursive functions into loops
d) To optimize RAM consumption
Correct Answer: a) To supply type checker hints for multiple call signatures without providing runtime implementations
Explanation:
`@typing.overload` provides stub definitions for static analyzers like mypy.

162. What parameter passing mechanism does Python use?

a) Pass-by-assignment (Pass-by-object-reference)
b) Pass-by-value strictly
c) Pass-by-reference strictly
d) Pass-by-name
Correct Answer: a) Pass-by-assignment (Pass-by-object-reference)
Explanation:
Python passes object references by value. Modifying mutable arguments affects caller state, whereas reassigning local names does not.

163. What is the output of `modify(nums)` given `def modify(lst): lst.append(42); nums = [1, 2]`?

a) [1, 2, 42]
b) [1, 2]
c) [42]
d) TypeError
Correct Answer: a) [1, 2, 42]
Explanation:
Mutating a passed mutable list (`lst.append(42)`) modifies the referenced object in caller scope.

164. What is the output of `rebind(nums)` given `def rebind(lst): lst = [100]; nums = [1, 2]`?

a) [1, 2]
b) [100]
c) [1, 2, 100]
d) []
Correct Answer: a) [1, 2]
Explanation:
Rebinding local reference parameter `lst` does not affect caller variable `nums`.

165. What is the output of `modify_int(val)` given `def modify_int(x): x += 10; val = 5`?

a) 5
b) 15
c) 10
d) UnboundLocalError
Correct Answer: a) 5
Explanation:
Integers are immutable. `x += 10` rebinds local parameter `x`, leaving caller variable `val` set to `5`.

166. Which built-in function provides interactive documentation and help output in terminal sessions?

a) help()
b) info()
c) doc()
d) show()
Correct Answer: a) help()
Explanation:
`help(func)` formats and outputs documentation string, signature, and module context.

167. What is the output of `f(5)` for `def f(x, y=10, /): return x + y`?

a) 15
b) 5
c) TypeError
d) 10
Correct Answer: a) 15
Explanation:
`x` gets positional argument `5`, `y` takes positional default `10`. Result = `15`.

168. What primary benefit do positional-only parameters (`/`) offer library maintainers?

a) Allows refactoring parameter names without breaking caller keyword code
b) Increases execution speed
c) Prevents recursion leaks
d) Enforces type checking
Correct Answer: a) Allows refactoring parameter names without breaking caller keyword code
Explanation:
Positional-only parameters decouple API parameter naming from public caller keyword syntax contracts.

169. Can function definitions be placed inside conditional execution blocks (like `if-else`)?

a) Yes, function definitions execute at runtime
b) No, function definitions are static compile-time statements
c) Only inside class declarations
d) Only when using lambda syntax
Correct Answer: a) Yes, function definitions execute at runtime
Explanation:
In Python, `def` is an executable statement defining functions at runtime when executed.

170. Which function attribute stores the string module identifier where the function was defined?

a) func.__module__
b) func.__file__
c) func.__name__
d) func.__package__
Correct Answer: a) func.__module__
Explanation:
`__module__` stores the string name of the module containing the function definition.

171. What value is assigned to `func.__module__` for functions defined directly inside top-level executable scripts?

a) '__main__'
b) 'main'
c) 'builtins'
d) 'root'
Correct Answer: a) '__main__'
Explanation:
Top-level main scripts assign string `'__main__'` to `__module__`.

172. What is the value of `__name__` attribute for lambda functions?

a) ''
b) 'lambda'
c) ''
d) None
Correct Answer: a) ''
Explanation:
Anonymous lambda functions assign string `''` to `__name__`.

173. Which attribute stores the fully qualified dotted name path for class methods or nested functions?

a) func.__qualname__
b) func.__fullname__
c) func.__path__
d) func.__route__
Correct Answer: a) func.__qualname__
Explanation:
`__qualname__` holds the qualified dotted path string leading to the function.

174. Which built-in function returns an object's attribute dictionary `__dict__`?

a) vars()
b) dir()
c) get_attr()
d) dict()
Correct Answer: a) vars()
Explanation:
`vars(obj)` returns the `__dict__` attribute dictionary of an object.

175. Can custom user attributes be assigned dynamically to function objects?

a) Yes, function objects have a `__dict__` attribute allowing dynamic property assignment
b) No, function attributes are read-only
c) Only when inheriting from object
d) Only inside class scope
Correct Answer: a) Yes, function objects have a `__dict__` attribute allowing dynamic property assignment
Explanation:
Python functions support custom user properties stored in their `__dict__` dictionary.

176. What is the output of setting `f.version = '1.0'` followed by `print(f.version)` on function `def f(): pass`?

a) 1.0
b) AttributeError
c) None
d) TypeError
Correct Answer: a) 1.0
Explanation:
Dynamic attribute `version` assigns value `'1.0'` directly to `f.__dict__`.

177. What is the result of `functools.reduce(add, [1, 2, 3, 4])` where `add = lambda x, y: x + y`?

a) 10
b) 24
c) 1
d) TypeError
Correct Answer: a) 10
Explanation:
`reduce` applies cumulative addition: `((1 + 2) + 3) + 4 = 10`.

178. What is the output of `functools.reduce(lambda x, y: x * y, [1, 2, 3], 10)`?

a) 60
b) 6
c) 10
d) TypeError
Correct Answer: a) 60
Explanation:
With initializer `10`: `((10 * 1) * 2) * 3 = 60`.

179. What exception occurs if `reduce()` is called on an empty sequence without an initial value?

a) TypeError
b) ValueError
c) IndexError
d) StopIteration
Correct Answer: a) TypeError
Explanation:
Reducing an empty iterable without providing an initial value raises a `TypeError`.

180. What is the result of `all(map(lambda x: x > 0, [1, 2, 3]))`?

a) True
b) False
c) None
d) TypeError
Correct Answer: a) True
Explanation:
Map evaluates element testing to `[True, True, True]`. Built-in `all()` returns `True`.

181. What type hint syntax from `typing` specifies a function accepting `[int, str]` returning `bool`?

a) Callable[[int, str], bool]
b) Callable(int, str) -> bool
c) Callable[int, str, bool]
d) Function[int, str, bool]
Correct Answer: a) Callable[[int, str], bool]
Explanation:
`Callable[[ParamTypes], ReturnType]` defines function type hints.

182. What type hint from `typing` indicates a function that NEVER returns (e.g. raises exception or exits system)?

a) NoReturn
b) NeverReturn
c) None
d) Void
Correct Answer: a) NoReturn
Explanation:
`typing.NoReturn` annotates functions that terminate execution or unconditionally raise exceptions.

183. What is the output of `add_five(2)` given `make_mult = lambda n: lambda x: x * n; add_five = make_mult(5)`?

a) 10
b) 7
c) 25
d) TypeError
Correct Answer: a) 10
Explanation:
`make_mult(5)` creates closure with `n=5`. Calling `add_five(2)` computes `2 * 5 = 10`.
← Previous: Python Control Flow MCQs
Next →: Python OOP MCQs
NewPython Control Flow MCQs

Python Control Flow MCQs

Control flow statements regulate the order in which individual code statements are evaluated and executed in a Python program. Python…

By MCQs Generator
NewTop Python Fundamentals MCQs & Answers for Beginners

Top Python Fundamentals MCQs & Answers for Beginners

Python is a dynamically typed, high-level programming language created by Guido van Rossum in 1991. Renowned for its clear syntax…

By MCQs Generator
NewLatest Python Loops MCQs

Latest Python Loops MCQs

Loops in Python provide the fundamental mechanism for executing a block of code repeatedly until a specified condition is met…

By MCQs Generator