Functions and Scope Flashcards
7 cards from real Python practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Functions and Scope flashcards as text
What does the `global` keyword do inside a function?
Answer: Declares that a variable refers to the global scope
The `global` keyword tells Python that assignments to that name should affect the module-level variable, not create a new local one.
What is the output of: `def f(x=[]): x.append(1); return x` called three times?
Answer: [1], [1,1], [1,1,1]
Mutable default arguments are created once and shared across calls, so the list grows with each call.
Which LEGB scope is checked first when resolving a variable name in Python?
Answer: Local
Python's LEGB rule checks Local scope first, then Enclosing, then Global, then Built-in.
What does `*args` capture in a function definition?
Answer: Positional arguments as a tuple
`*args` collects any extra positional arguments passed to the function into a tuple.
What is a closure in Python?
Answer: A nested function that remembers its enclosing scope's variables
A closure is an inner function that retains access to variables from its enclosing function's scope even after that function has returned.
What will `print(type(lambda x: x))` output?
Answer:
Lambda expressions create regular function objects; their type is `function`, the same as functions defined with `def`.
Which statement about `nonlocal` is correct?
Answer: It allows a nested function to assign to an enclosing (non-global) variable
`nonlocal` lets an inner function rebind a variable in the nearest enclosing scope that is not the global scope.