What if your function could magically update variables everywhere without confusing copies?
Why Global keyword in Python? - Purpose & Use Cases
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.
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 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.
count = 0 def increase(): count = 1 # This creates a new local variable increase() print(count) # Still 0
count = 0 def increase(): global count count = count + 1 # Changes the global variable increase() print(count) # Now 1
It lets you safely and clearly update shared data across different parts of your program.
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.
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.