0
0
Pythonprogramming~5 mins

Global keyword in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the global keyword do in Python?
The global keyword tells Python that a variable inside a function refers to the variable defined outside the function, at the global level. It allows you to change the global variable from inside the function.
Click to reveal answer
beginner
Why do you need the global keyword to modify a global variable inside a function?
Without global, Python treats variables assigned inside a function as local. Using global tells Python to use the variable from outside the function, so changes affect the global variable.
Click to reveal answer
beginner
What happens if you try to modify a global variable inside a function without using global?
Python creates a new local variable with the same name inside the function. The global variable remains unchanged outside the function.
Click to reveal answer
beginner
Show a simple example of using global to change a global variable inside a function.
Example:
count = 0

def increment():
    global count
    count += 1

increment()
print(count)  # Output: 1
Click to reveal answer
intermediate
Can the global keyword be used to create a new global variable inside a function?
Yes. If the global variable does not exist yet, using global inside a function and assigning a value will create it at the global level.
Click to reveal answer
What does the global keyword do inside a function?
AAllows modifying a variable defined outside the function
BCreates a new local variable
CDeletes a global variable
DImports a module globally
What happens if you assign a value to a variable inside a function without using global?
AThe variable becomes read-only
BThe global variable is changed
CPython throws an error
DA new local variable is created
Which keyword do you use to tell Python to use the global variable inside a function?
Alocal
Bextern
Cglobal
Dnonlocal
Can you create a new global variable inside a function using global?
AYes, by declaring it global and assigning a value
BNo, global variables must be defined outside functions
COnly if the variable name starts with 'g_'
DOnly in Python 2
What will this code print?
count = 5
def change():
    count = 10
change()
print(count)
A10
B5
CError
DNone
Explain how the global keyword affects variable scope inside a function.
Think about how Python treats variables inside functions by default.
You got /4 concepts.
    Describe a situation where you would need to use the global keyword in your code.
    Consider when a function needs to update a value defined outside it.
    You got /4 concepts.