Skip to content

Day 9: Python Scopes

Understanding Scopes in Python

In Python, variables are defined by their scope, which determines where they can be accessed within the code. There are two primary types of scope: global and local. Global variables are defined outside of any function and can be accessed from anywhere within the code. Conversely, local variables are defined within a function and can only be accessed from within that specific function.

Global Variables in Python

x = 5  # This is a global variable

def func():
    # The global variable x can be accessed from within this function
    print(x)

func()  # This will output: 5

In the above example, x is a global variable. It is defined outside of any function and can be accessed from anywhere within the code, including inside the function func().

Local Variables in Python

def func():
    x = 5  # This is a local variable
    print(x)

func()  # This will output: 5

In this example, x is a local variable. It is defined within the function func() and can only be accessed from within that function. Attempting to print x outside of the function would result in an error, as x is not defined in that scope.

# This will cause an error, because x is not defined outside of the function
print(x)

By understanding the difference between global and local variable scope in Python, you can write more efficient and error-free code.

Learn More

Want to learn more about Python for Machine Learning? Check out the full course HERE.


Need help mastering Machine Learning?

Don't just follow along — join me! Get exclusive access to me, your instructor, who can help answer any of your questions. Additionally, get access to a private learning group where you can learn together and support each other on your AI journey.