Learn Python
Lesson 1 - Introduction To Python
Lesson 2 - Basic Python Syntax
Lesson 3 - Control Flow
Lesson 5 - Basic Data Structures
Lesson 6 - Exception Handling
Lesson 7 - Modules And Packages
Lesson 8 - Basic String Operations
Lesson 9 - Object-Oriented Programming (OOP)
Variable scope determines where variables are accessible within Python programs. There are two main types of variable scope:
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 example() 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.