0
0
Pythonprogramming~20 mins

Why scope matters in Python - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Scope Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this code with variable scope?

Look at the code below. What will it print?

Python
x = 10

def func():
    x = 5
    print(x)

func()
print(x)
A10\n5
B10\n10
C5\n5
D5\n10
Attempts:
2 left
๐Ÿ’ก Hint

Remember, variables inside a function are local unless declared global.

โ“ Predict Output
intermediate
2:00remaining
What error does this code raise due to scope?

What error will this code produce?

Python
def func():
    print(x)
    x = 3

func()
AUnboundLocalError
BNameError
CSyntaxError
DNo error, prints 3
Attempts:
2 left
๐Ÿ’ก Hint

Python treats variables assigned in a function as local, even if used before assignment.

โ“ Predict Output
advanced
2:00remaining
What is the output when modifying a global variable inside a function?

What will this code print?

Python
count = 0

def increment():
    global count
    count += 1

increment()
increment()
print(count)
A2
B0
CNameError
D1
Attempts:
2 left
๐Ÿ’ก Hint

Using global allows modifying the variable outside the function.

โ“ Predict Output
advanced
2:00remaining
What is the output of nested function scope?

What will this code print?

Python
def outer():
    x = 'outer'
    def inner():
        nonlocal x
        x = 'inner'
    inner()
    print(x)

outer()
ASyntaxError
Binner
Couter
DNameError
Attempts:
2 left
๐Ÿ’ก Hint

nonlocal lets inner functions modify variables in the nearest enclosing scope.

๐Ÿง  Conceptual
expert
2:00remaining
Why does this code produce an error related to scope?

Consider this code:

def f():
    print(a)
    a = 5
f()

Why does it raise an error?

ABecause <code>a</code> is not defined anywhere globally
BBecause <code>print</code> cannot be used inside functions
CBecause <code>a</code> is used before assignment in the local scope
DBecause Python does not allow variable assignment inside functions
Attempts:
2 left
๐Ÿ’ก Hint

Think about how Python decides if a variable is local or global.