Bird
Raised Fist0
Pythonprogramming~10 mins

Enclosing scope in Python - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print the value of the outer variable inside the inner function.

Python
def outer():
    x = 10
    def inner():
        print([1])
    inner()
outer()
Drag options to blanks, or click blank then click option'
A10
Bx
Cinner
Douter
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the function name instead of the variable name.
Trying to print a variable not defined in the inner function.
2fill in blank
medium

Complete the code to modify the outer variable inside the inner function using the correct keyword.

Python
def outer():
    count = 0
    def inner():
        [1] count
        count += 1
        print(count)
    inner()
    inner()
outer()
Drag options to blanks, or click blank then click option'
Anonlocal
Bglobal
Clocal
Douter
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global instead of nonlocal.
Not using any keyword and causing an error.
3fill in blank
hard

Fix the error in the code by completing the blank with the correct keyword to modify the outer variable.

Python
def counter():
    num = 5
    def increment():
        [1] num
        num += 2
        return num
    return increment()
print(counter())
Drag options to blanks, or click blank then click option'
Alocal
Bouter
Cglobal
Dnonlocal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global which causes an error here.
Not using any keyword causing an UnboundLocalError.
4fill in blank
hard

Fill both blanks to create a closure that remembers the value of start and adds step each time.

Python
def make_adder(start):
    step = 0
    def adder():
        nonlocal [1]
        [2] += 1
        return start + [2]
    return adder

add = make_adder(5)
print(add())
print(add())
Drag options to blanks, or click blank then click option'
Astep
Bstart
Ccount
Dadder
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using start instead of step.
Not declaring the variable as nonlocal.
5fill in blank
hard

Fill all three blanks to create a function that counts calls using an enclosing variable and returns the count.

Python
def call_counter():
    count = 0
    def counter():
        [1] count
        count [2] 1
        return [3]
    return counter

c = call_counter()
print(c())
print(c())
Drag options to blanks, or click blank then click option'
Anonlocal
B+=
Ccount
Dglobal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using global instead of nonlocal.
Forgetting to return the updated count.

Practice

(1/5)
1. What does enclosing scope mean in Python functions?
easy
A. Inner functions can access variables from outer functions
B. Variables inside a function are always global
C. Functions cannot access variables outside their own block
D. Only global variables can be used inside functions

Solution

  1. Step 1: Understand function nesting

    In Python, functions can be defined inside other functions, creating an inner and outer function relationship.
  2. Step 2: Access rules for variables

    Inner functions can use variables defined in their outer functions, which is called the enclosing scope.
  3. Final Answer:

    Inner functions can access variables from outer functions -> Option A
  4. Quick Check:

    Enclosing scope = inner function accesses outer variables [OK]
Hint: Inner functions see outer variables unless shadowed [OK]
Common Mistakes:
  • Thinking all variables inside functions are global
  • Believing inner functions cannot use outer variables
  • Confusing local and global scopes
2. Which of the following is the correct syntax to modify an outer variable inside an inner function?
easy
A. Just assign the variable directly without any keyword
B. Use global keyword inside the inner function
C. Use nonlocal keyword inside the inner function
D. Use outer keyword inside the inner function

Solution

  1. Step 1: Understand variable modification rules

    To change a variable from an outer (enclosing) function inside an inner function, Python requires the nonlocal keyword.
  2. Step 2: Differentiate from global

    global is for variables at the module level, not enclosing functions.
  3. Final Answer:

    Use nonlocal keyword inside the inner function -> Option C
  4. Quick Check:

    Modify outer variable = use nonlocal [OK]
Hint: Change outer function vars with 'nonlocal' inside inner function [OK]
Common Mistakes:
  • Using 'global' instead of 'nonlocal' for outer function variables
  • Trying to assign without any keyword causing UnboundLocalError
  • Using a non-existent 'outer' keyword
3. What is the output of this code?
def outer():
    x = 5
    def inner():
        return x + 3
    return inner()
print(outer())
medium
A. 3
B. 5
C. Error
D. 8

Solution

  1. Step 1: Trace variable usage

    Variable x is defined in outer() as 5. The inner function returns x + 3, which is 8.
  2. Step 2: Function call and return

    outer() calls inner() and returns its result, so print(outer()) prints 8.
  3. Final Answer:

    8 -> Option D
  4. Quick Check:

    Inner uses outer x=5, returns 5+3=8 [OK]
Hint: Inner function can read outer variables directly [OK]
Common Mistakes:
  • Expecting an error due to variable scope
  • Confusing inner return value with outer variable
  • Thinking inner cannot access outer variables
4. What is wrong with this code?
def outer():
    x = 10
    def inner():
        x = x + 5
        return x
    return inner()
print(outer())
medium
A. It will print 15
B. UnboundLocalError because inner tries to modify x without nonlocal
C. SyntaxError due to wrong indentation
D. NameError because x is not defined anywhere

Solution

  1. Step 1: Analyze variable assignment in inner()

    Inside inner(), x = x + 5 tries to modify x. Python treats x as local but it is used before assignment.
  2. Step 2: Understand error cause

    This causes an UnboundLocalError because x is referenced before assignment locally. The fix is to declare nonlocal x.
  3. Final Answer:

    UnboundLocalError because inner tries to modify x without nonlocal -> Option B
  4. Quick Check:

    Modify outer var inside inner needs nonlocal [OK]
Hint: Assigning outer var inside inner needs 'nonlocal' keyword [OK]
Common Mistakes:
  • Assuming it prints 15 without error
  • Confusing UnboundLocalError with NameError
  • Ignoring the need for 'nonlocal' when modifying outer vars
5. Consider this code:
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment
c = counter()
print(c())
print(c())
print(c())

What will be the output?
hard
A. [1, 2, 3]
B. [0, 1, 2]
C. [1, 1, 1]
D. Error due to missing global keyword

Solution

  1. Step 1: Understand closure with nonlocal

    The counter() function returns increment(), which modifies count using nonlocal. This keeps count persistent across calls.
  2. Step 2: Trace calls to c()

    Each call to c() increases count by 1 and returns it. So outputs are 1, then 2, then 3.
  3. Final Answer:

    [1, 2, 3] -> Option A
  4. Quick Check:

    Closure with nonlocal increments count each call [OK]
Hint: Use nonlocal to keep and update outer variable state [OK]
Common Mistakes:
  • Expecting count to reset each call
  • Confusing nonlocal with global
  • Thinking it will raise an error without global