0
0
Pythonprogramming~20 mins

Global keyword in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Global Scope Master
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 using global keyword?

Look at the code below. What will it print?

Python
x = 5

def change():
    global x
    x = 10

change()
print(x)
A5
BNameError
C10
DUnboundLocalError
Attempts:
2 left
๐Ÿ’ก Hint

Think about what the global keyword does inside a function.

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

What error will this code produce?

Python
count = 0

def increment():
    count += 1

increment()
AUnboundLocalError
BNameError
CSyntaxError
DNo error
Attempts:
2 left
๐Ÿ’ก Hint

Look at how count is used inside the function without global.

๐Ÿ”ง Debug
advanced
2:00remaining
Why does this code print 0 instead of 1?

Fix the code so that print(x) outputs 1.

Python
x = 0

def set_x():
    x = 1

set_x()
print(x)
AAdd <code>global x</code> inside <code>set_x()</code> before assignment
BRemove the assignment inside <code>set_x()</code>
CChange <code>x = 1</code> to <code>return 1</code> and assign outside
DDeclare <code>x</code> as a parameter of <code>set_x()</code>
Attempts:
2 left
๐Ÿ’ก Hint

Think about how to modify the global variable inside a function.

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

What will this code print?

Python
count = 0

def outer():
    def inner():
        global count
        count += 1
    inner()

outer()
print(count)
A0
BUnboundLocalError
CNameError
D1
Attempts:
2 left
๐Ÿ’ก Hint

Notice the use of global inside the inner function.

๐Ÿง  Conceptual
expert
2:00remaining
Which option causes an error due to incorrect global usage?

Which code snippet will raise an error because of wrong use of the global keyword?

A
def f():
    global b
    print(b)

b = 3
f()
B
def f():
    global c
    c += 1

f()
C
def f():
    global a
    a = 5

f()
print(a)
D
def f():
    global d
    d = d + 1

d = 0
f()
Attempts:
2 left
๐Ÿ’ก Hint

Consider if the global variable is initialized before use.