All lessons
πŸ”

Variable Scope

Local vs global variables

Reward
+40 XP

Local scope

Variables created inside a function only exist within that function.

def my_func():
    x = 10  # local
    print(x)

my_func()
# print(x)  # Error! x is not defined here

Global scope

Variables created outside functions are global β€” accessible everywhere. Use the global keyword to modify a global inside a function.

x = 10

def change():
    global x
    x = 20

change()
print(x)  # 20

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • ⚠Trying to read a global variable that has the same name as a local one.
  • ⚠Overusing global β€” pass values as parameters instead.