Functions & Scope · Question 19 · Hard
Which statement about the nonlocal keyword in Python is correct?
- It makes a name refer to a variable of the nearest enclosing function, and it is a SyntaxError if no such variable exists
- It lets a nested function rebind a variable defined at module level
- It creates a new variable in the enclosing function if one does not already exist
- It is required even when a nested function only reads an enclosing variable
Answer and explanation
Answer: A. It makes a name refer to a variable of the nearest enclosing function, and it is a SyntaxError if no such variable exists
Explanation: nonlocal binds to an existing variable in an enclosing function scope, never to a module-level one (that is the job of global). It cannot create the variable, and it is only needed for assignment, not for reading.
Previous: The recursive function below counts how many moves a number needs to reach 1… · Next: Inside update, one list is changed with append and the other name is…
Practise functions & scope
Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.
More functions & scope questions
- The enclosing variable x is reassigned after the inner function is defined but…
- A default parameter value refers to a module-level variable that is changed…
- The recursive function below counts how many moves a number needs to reach 1…
- Inside update, one list is changed with append and the other name is…
More python practice
Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge