Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 4 - Functions

4.4 Scope Of Variables

Variable scope determines where variables are accessible within Python programs. There are two main types of variable scope:

  1. Local variable: Defined within a function and only accessible from within that function.
  2. Global variable: Defined outside of any function and can be accessed throughout the entire code.

Let's understand them through a practical example:

global_var = "I'm a global variable"

def example():
    local_var = "I'm a local variable"
    print(global_var)  # Accessing global variable
    print(local_var)   # Accessing local variable

print(global_var)  # Accessing global variable outside the function
# print(local_var)  # This will cause an error because local_var is not accessible here

In this example, the global variable global_var can be accessed from within the function example(), whereas the local variable local_var is only accessible inside the function example(). Attempting to access local_var outside of its defined scope (the example() function) will result in an error.