AI Workshop: learn to build apps with AI →
Modules and Advanced Concepts: Variables scope

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


When you declare a variable, that variable is visible in parts of your program, depending on where you declare it.

If you declare it outside of any function, the variable is visible to any code running after the declaration, including functions:

age = 8

def test():
    print(age)

print(age) # 8
test() # 8

We call it a global variable.

If you define a variable inside a function, that variable is a local variable, and it is only visible inside that function. Outside the function, it is not reachable:

def test():
    age = 8
    print(age)

test() # 8

print(age)
# NameError: name 'age' is not defined

Lessons in this unit:

0: Introduction
1: Modules
2: The Standard Library
3: Installing packages with pip
4: Virtual environments
5: ▶︎ Variables scope
6: Decorators
7: Docstrings
8: Introspection
9: Annotations