Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)