Variable scope in Python (local and global)
In Python, the variables you create inside a function are called local — they exist only while the function is running. The variables you create outside a function are global and available everywhere in that file. It is important to understand the difference so that you avoid mistakes.
Example — a local and a global variable
# scope_example.py
x = 10 # a global variable
def show():
y = 5 # a local variable
print("Inside the function, y =", y)
print("Inside the function, x =", x)
show()
print("Outside the function, x =", x)
# print(y) # THIS will cause an error — y is not defined outside the function
To begin with, we recommend that you avoid changing global variables inside a function — it is better to pass values through parameters and return the result.
Extra practice tasks — Variable scope in Python
These tasks help you practise further how variables behave in different scopes (locally inside a function and globally). They are ordered from easier to harder.
- A global variable
Write a program in which you define the variable
x = 10outside a function, and then print it inside a function as well.x = 10 def display(): # print x pass print(x) display() - A local variable
Write a function that has a local variable
yand try to print it outside the function (it should report an error).def test(): y = 5 print(y) test() # print(y) # what do you think will happen? - A variable in a function changes a global one
Write a function that uses a global variable and changes it with the keyword
global. In the main program check whether the value has changed.a = 5 def change(): # use global a and change it pass change() print(a) - The same names, different scopes
Write a program where you have a variable
zglobally and a variablezinside a function. Print both and check the difference.z = 100 def display_z(): z = 50 print("Inside:", z) display_z() print("Global:", z)Hint: think carefully about why a different value is printed inside and outside the function.
- Competition level — returning a local value
Write a function that has a local counter variable and returns its value from the function. In the main program call the function several times and print the results so that you see that each call is independent.
def call_count(): # use a local counter variable pass print(call_count()) print(call_count()) print(call_count())Hint: in this function the counter is set again on every call — think about what that means for its scope.
Extra explanations: variable scope in Python
In this section we deal with situations that often confuse beginners and can lead to mistakes in programs.
1. What if a local and a global variable have the same name?
Look at the following example:
x = 10 # a global variable
def my_function():
x = 5 # a local variable
print("Inside the function, x =", x)
my_function()
print("Outside the function, x =", x)
Result:
Inside the function, x = 5
Outside the function, x = 10
The local variable x does not change the global one.
Python always looks for a variable in the function's local scope first.
2. The order in which variables are looked up – the LEGB rule
When Python comes across the name of a variable, it looks for it in this order. From the first letters of the names, this is called the LEGB rule:
- L – Local (local scope): inside the function we are in
- E – Enclosing (enclosing scope): in the outer function, if the function is written inside another function
- G – Global (global scope): in the file, outside all functions
- B – Built-in (built-in scope): Python's built-in names, such as
print,lenandrange
Python stops as soon as it finds the name. Look at an example in which all three variables have the same name x:
x = "global" # G – global scope (in the file)
def outer():
x = "enclosing" # E – the outer function's scope
def inner():
x = "local" # L – local scope
print("1:", x)
inner()
print("2:", x)
outer()
print("3:", x)
print("4:", len("abc")) # B – len is a built-in function
Result:
1: local
2: enclosing
3: global
4: 3
Each function sees "its own" x: the inner function finds the local one,
the outer function its own, and the main program the global one. If a variable does not exist in any
of the four scopes, Python reports a NameError.
3. A common mistake: UnboundLocalError
Look at the following code:
x = 10
def increase():
x = x + 1
print(x)
increase()
This program causes an error. Why?
- Python sees the assignment
x = ...in the function - so it treats
xas a local variable - but the local
xhas not been given a value yet
4. Using the keyword global
If you really want to change a global variable from a function, you must say so clearly:
x = 10
def increase():
global x
x = x + 1
increase()
print(x)
Result:
11
⚠ Note: this is allowed, but in practice it is recommended to use global variables as rarely as possible.
5. The keyword nonlocal
The keyword global is used for variables from the file. But what if a function is
written inside another function, and we want to change a variable of the
outer function? Then we use nonlocal:
def counter():
count = 0 # a variable of the outer function
def increase():
nonlocal count # we change count from the outer function
count = count + 1
print("count =", count)
increase()
increase()
increase()
print("In the end, count =", count)
counter()
Result:
count = 1
count = 2
count = 3
In the end, count = 3
Without the line nonlocal count, Python would treat count as a new local
variable of the function increase and would report the same error as in section 3:
UnboundLocalError.
global x– we changexfrom the file (global scope)nonlocal x– we changexfrom the outer function (enclosing scope)- to only read a variable you need neither – Python finds it by the LEGB rule
6. Good practice: instead of globals — use parameters and return
Instead of changing global variables, a better approach is:
def increase(x):
return x + 1
x = 10
x = increase(x)
print(x)
Code like this is:
- more readable
- easier to test
- less prone to mistakes
7. A visual overview of variable scope
MAIN PROGRAM
|
|-- global variables
|
|-- function
|
|-- local variables
|
|-- (when the function ends → they are deleted)
Local variables exist only while the function is running, and then they disappear.
Hidden mini quiz — Variable scope in Python
Click the quiz and check whether you understand the difference between local and global variables, and how variables behave in functions.
Open the quiz
Mini quiz: Variable scope
1. Which variable is global?
x = 10
def f():
print(x)
2. What will happen?
def test():
y = 5
print(y)
3. What will be printed?
a = 3
def f():
a = 7
print(a)
f()
print(a)
4. What is the keyword global used for?
5. What will be printed?
number = 1
def increase():
global number
number = number + 1
increase()
increase()
print(number)
Tasks for independent work — Variable scope (7th and 8th grade)
The tasks are ordered from easier to harder. The goal is to notice on your own the difference between local and global variables and to understand how Python decides the scope of a variable.
- Recognising the scope
Look at the following program and answer: is the variable
alocal or global?a = 7 def show(): print(a) show()Then explain why the value is printed without an error.
- A local variable in a function
Write a function that has a local variable
xinside it and prints it. Try to print that variable outside the function too. - The same name – a different value
Write a program in which there is a global variable
number, and then a function that has a local variable with the same name but a different value. Print both values.Hint: pay attention to the order of execution and where the variable is located.
- Changing a global variable
Write a function that changes the value of a global variable.
Hint: find out how the keyword
globalis used and why the change is impossible without it. - Competition level — a function call counter
Write a program that counts how many times a function has been called.
Hint: think about whether the counter should be a local or a global variable and why. The goal is for the value to be remembered between several calls of the function.
Tip: If you are not sure how a variable behaves, add print()
in different places in the program and follow how it runs.
