0
0
Pythonprogramming~5 mins

Global keyword in Python

Choose your learning style9 modes available
Introduction

The global keyword lets you change a variable outside a function from inside it. Without it, you can only read the outside variable, not change it.

You want to update a setting or counter that is used in many parts of your program.
You have a variable defined outside functions and want to change its value inside a function.
You want to keep track of a total or score that changes as your program runs.
You want to share data between different functions without passing it as a parameter.
Syntax
Python
global variable_name

Use global inside a function before changing the variable.

If you don't use global, Python treats the variable as new inside the function.

Examples
This changes the global variable x from 5 to 10 inside the function.
Python
x = 5

def change():
    global x
    x = 10

change()
print(x)
Each time add_one() runs, it increases the global count by 1.
Python
count = 0

def add_one():
    global count
    count += 1

add_one()
add_one()
print(count)
Without global, the global value stays 3 because the function only changes a local variable.
Python
value = 3

def try_change():
    value = 7  # This creates a new local variable

try_change()
print(value)
Sample Program

This program shows how the global keyword lets the function increase_score change the global score variable.

Python
score = 0

def increase_score():
    global score
    score += 5

print(f'Score before: {score}')
increase_score()
print(f'Score after: {score}')
OutputSuccess
Important Notes

Use global only when you really need to change a global variable.

Too much use of global can make your code harder to understand.

For many cases, passing variables as function parameters is clearer.

Summary

The global keyword lets you change variables outside functions.

Without global, variables inside functions are local by default.

Use global carefully to keep your code easy to read.