0
0
Pythonprogramming~3 mins

Why Global keyword in Python? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your function could magically update variables everywhere without confusing copies?

The Scenario

Imagine you have a program where you want to change a number stored outside a function, but inside the function, you create a new number instead of changing the original one.

The Problem

Without the global keyword, changing a variable inside a function only changes a local copy. This means your original number stays the same, causing confusion and bugs. You have to write extra code or use tricky workarounds.

The Solution

The global keyword tells Python you want to use the variable defined outside the function. This way, you can change the original number directly inside the function, making your code clearer and easier to manage.

Before vs After
Before
count = 0

def increase():
    count = 1  # This creates a new local variable

increase()
print(count)  # Still 0
After
count = 0

def increase():
    global count
    count = count + 1  # Changes the global variable

increase()
print(count)  # Now 1
What It Enables

It lets you safely and clearly update shared data across different parts of your program.

Real Life Example

Think of a game where you keep track of the player's score. Using global lets you update the score from different functions like when the player earns points or loses lives.

Key Takeaways

Without global, functions can't change variables outside them.

Global keyword links a function variable to the outside one.

This makes updating shared data simple and clear.