How to modify global variable?

QuestionsQuestions8 SkillsProDec, 25 2025
094

To modify a global variable from inside a function in Python, you need to use the global keyword.

Here is a quick breakdown of how it works:

1. The Problem

Usually, if you just assign a value to a variable inside a function, Python treats it as a local variable. It won't change the variable with the same name outside the function.

2. The Solution: Using global

By using the global keyword inside your function, you tell Python: "Hey, don't create a new local variable; use the one that already exists in the global scope."

Example

You can see this in your current scope.py file:

eggs = 'global' # This is a global variable

def spam():
    global eggs  # 1. Declare that we want to use the global 'eggs'
    eggs = 'spam'  # 2. Now this changes the variable outside the function

print(f"Before: {eggs}")
spam()
print(f"After: {eggs}")

Key Steps:

  1. Define the variable outside the function.
  2. Inside the function, write global variable_name before you try to change it.
  3. Assign the new value.

If you don't use the global statement, Python will create a local variable named eggs inside the function, and the global eggs will remain unchanged.

Give it a try in your terminal by running python3 scope.py to see the change in action

0 Comments

no data
Be the first to share your comment!