← All PCEP Flashcard Decks

Variable Scope and the `global` keyword Flashcards

7 cards from real PCEP practice questions. Tap to flip, then mark Knew It or Still Learning — missed cards come back until you master them.

Read the first 7 Variable Scope and the `global` keyword flashcards as text
  1. What is the output? result = [] for i in range(3): result.append(i) print(i)

    Answer: 2

    The loop variable i persists in module scope after the loop and holds its last value, 2.

  2. What does the nonlocal keyword do in a nested function?

    Answer: Allows the inner function to rebind a variable in the nearest enclosing function's scope

    nonlocal targets the nearest enclosing (non-global) scope, letting the inner function modify that variable.

  3. Which of the following correctly modifies a global list inside a function WITHOUT using the global keyword?

    Answer: my_list.append(1)

    Calling a method like append() mutates the object in place without rebinding the name, so global is not needed.

  4. What is the output? x = 5 def show(): print(x) show() x = 10 show()

    Answer: 5 10

    Each call to show() reads x from global scope at the time of the call: first 5, then 10.

  5. What is the scope of a variable defined inside an if block at module level?

    Answer: Module (global) scope — if blocks don't create a new scope

    Python has no block scope; variables created inside if, for, or with blocks belong to the enclosing function or module scope.

  6. What will this code print? def make_counter(): count = 0 def inc(): nonlocal count count += 1 return count return inc c = make_counter() print(c(), c())

    Answer: 1 2

    nonlocal count lets inc() modify make_counter's count, which persists between calls, yielding 1 then 2.

  7. If a name is not found in local, enclosing, or global scopes, where does Python look next?

    Answer: Built-in scope

    The final step in LEGB is the built-in scope, which contains names like print, len, and range.