0
0
Pythonprogramming~5 mins

Global scope in Python

Choose your learning style9 modes available
Introduction

Global scope means a variable can be used anywhere in the program. It helps share information across different parts of the code.

When you want to use the same data in many functions without passing it around.
When you have a setting or value that should stay the same everywhere.
When you want to keep track of a value that changes but is needed in multiple places.
Syntax
Python
variable_name = value  # This is a global variable

def some_function():
    print(variable_name)  # Access global variable

# To change a global variable inside a function, use 'global' keyword:

def change_global():
    global variable_name
    variable_name = new_value

Global variables are created outside of functions.

Use the global keyword inside a function to modify a global variable.

Examples
This example shows reading a global variable inside a function.
Python
count = 10  # global variable

def show_count():
    print(count)  # prints 10

show_count()
This example shows changing a global variable inside a function using global.
Python
score = 5

def increase_score():
    global score
    score += 1

increase_score()
print(score)  # prints 6
Sample Program

This program shows how a global variable can be read and changed inside functions.

Python
message = "Hello, world!"  # global variable

def greet():
    print(message)  # use global variable

def change_message():
    global message
    message = "Hi, everyone!"  # change global variable

greet()
change_message()
greet()
OutputSuccess
Important Notes

Be careful with global variables because changing them can affect many parts of your program.

Try not to use too many global variables to keep your code easy to understand.

Summary

Global variables can be used anywhere in the program.

Use global keyword inside functions to change global variables.

Global scope helps share data but use it carefully.