0
0
Pythonprogramming~10 mins

Global keyword in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to modify the global variable inside the function.

Python
count = 0

def increment():
    global [1]
    count += 1

increment()
print(count)
Drag options to blanks, or click blank then click option'
Aglobal
Bcount
Cincrement
Dvalue
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Forgetting to use the global keyword causes an error or no change to the global variable.
Using a wrong variable name after global.
2fill in blank
medium

Complete the code to correctly update the global variable inside the function.

Python
total = 10

def add_five():
    global [1]
    total += 5

add_five()
print(total)
Drag options to blanks, or click blank then click option'
Asum
Badd_five
Cfive
Dtotal
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a different variable name after global than the one declared globally.
Not using global keyword and expecting the global variable to change.
3fill in blank
hard

Fix the error by completing the code to modify the global variable inside the function.

Python
counter = 5

def reset():
    [1] counter
    counter = 0

reset()
print(counter)
Drag options to blanks, or click blank then click option'
Aglobal
Blocal
Cnonlocal
Ddef
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using nonlocal instead of global when the variable is global.
Not using any keyword and trying to assign to the global variable.
4fill in blank
hard

Fill in the blank to correctly modify two global variables inside the function.

Python
x = 1
y = 2

def update():
    [1] x, y
    x += 10
    y += 20

update()
print(x, y)
Drag options to blanks, or click blank then click option'
Anonlocal
Blocal
Cglobal
Ddef
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using nonlocal instead of global.
Declaring only one variable as global and not the other.
5fill in blank
hard

Fill in the blank to correctly use the global keyword and modify variables inside the function.

Python
a = 5
b = 10
c = 15

def change_values():
    [1] a, b, c
    a += 1
    b += 2
    c += 3

change_values()
print(a, b, c)
Drag options to blanks, or click blank then click option'
Aglobal
Ba
Cb
Dc
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Not declaring all variables as global.
Using variable names without the global keyword.