← 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? x = 'global' def test(): global x x = 'local' test() print(x)

    Answer: local

    global x inside test() makes the assignment modify the module-level x, so it becomes 'local'.

  2. Can a function declare multiple names global in a single statement?

    Answer: Yes: global a, b, c

    A single global statement can list multiple comma-separated names: global a, b, c.

  3. What happens when you use the global keyword on a name that does not yet exist at module level?

    Answer: Python creates the variable at module level when it is assigned inside the function

    global just declares intent; the global variable is created upon the first assignment inside the function.

  4. What is the output of the following code? def outer(): x = 1 def inner(): x = 2 inner() print(x) outer()

    Answer: 1

    inner() creates its own local x = 2 without nonlocal, so outer()'s x stays 1.

  5. Which scope level is searched LAST in the LEGB rule?

    Answer: Built-in

    Python searches Local → Enclosing → Global → Built-in, so Built-in is the last resort.

  6. What will this code output? total = 0 def add(n): total = total + n return total print(add(5))

    Answer: UnboundLocalError

    Python sees total = ... and marks it local, so reading total before assignment raises UnboundLocalError.

  7. Where is a variable defined inside a for loop (at module level) accessible?

    Answer: Anywhere in the module after the loop runs

    Python loops do not create a new scope; the loop variable leaks into the enclosing (module-level) namespace.