Understanding Global and Local Variables in Python

 

 

πŸ“Œ Introduction

In Python programming, understanding variable scope is essential for writing clean and effective code.
Two of the most common scopes in Python are local and global.
These determine where a variable can be accessed or modified.

🎯 Objective

The objective of this lesson is to:

  • Differentiate between local and global variables in Python
  • Understand how scope affects variable access and modification
  • Write a Python program that demonstrates both scopes clearly

πŸ’» Python Code Example


# Global variable
x = 10

def local_scope_example():
    # Local variable
    x = 5
    print("Inside local_scope_example, x =", x)

def global_scope_example():
    global x
    x = 20
    print("Inside global_scope_example, x =", x)

# Initial value of x
print("Initial value of x:", x)

# Call function with local scope
local_scope_example()

# Value of x remains unchanged globally
print("After local_scope_example, x:", x)

# Call function with global scope
global_scope_example()

# Global x is changed
print("After global_scope_example, x:", x)
    

πŸ“– Program Explanation

  • x = 10 is defined at the top level, making it a global variable.
  • local_scope_example() creates a new local variable x = 5, which exists only inside the function.
  • global_scope_example() uses the global keyword to modify the global variable x.
  • The changes made by local_scope_example() do not affect the global x.
  • The global_scope_example() function successfully modifies the global x to 20.

πŸš€ How to Run This Program

  1. Copy the Python code above into a file and save it as variable_scope.py.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is saved.
  4. Run the program using: python variable_scope.py
  5. Observe how the value of x changes based on the scope.

 

Leave a Reply

Your email address will not be published. Required fields are marked *