0
0
Pythonprogramming~20 mins

Local scope in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Local Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of variable inside a function
What is the output of this code?
Python
def greet():
    message = "Hello"
    print(message)

greet()
AHello
BNone
CNameError
Dmessage
Attempts:
2 left
๐Ÿ’ก Hint
Look where the variable message is defined and where it is used.
โ“ Predict Output
intermediate
2:00remaining
Accessing local variable outside function
What happens when you run this code?
Python
def show():
    number = 10

show()
print(number)
ANone
B10
CNameError
D0
Attempts:
2 left
๐Ÿ’ก Hint
Think about where number is defined and where you try to print it.
โ“ Predict Output
advanced
2:00remaining
Local variable shadowing global variable
What is the output of this code?
Python
value = 5

def test():
    value = 10
    print(value)

test()
print(value)
A10\n10
B5\n10
C5\n5
D10\n5
Attempts:
2 left
๐Ÿ’ก Hint
Check which value is printed inside and outside the function.
โ“ Predict Output
advanced
2:00remaining
Modifying global variable inside function without global keyword
What error or output does this code produce?
Python
count = 0

def increment():
    count += 1
    print(count)

increment()
AUnboundLocalError
B1
C0
DNameError
Attempts:
2 left
๐Ÿ’ก Hint
Think about how Python treats variables assigned inside functions.
โ“ Predict Output
expert
3:00remaining
Understanding local scope with nested functions
Consider this code. What is the output when outer() is called?
Python
def outer():
    x = 'local'
    def inner():
        x = 'nonlocal'
        print(x)
    inner()
    print(x)

outer()
Alocal\nlocal
Bnonlocal\nnonlocal
Clocal\nnonlocal
Dnonlocal\nlocal
Attempts:
2 left
๐Ÿ’ก Hint
Look at where x is assigned inside inner() and how it affects outer().