Introduction
Global scope means a variable can be used anywhere in the program. It helps share information across different parts of the code.
Jump into concepts and practice - no test required
Global scope means a variable can be used anywhere in the program. It helps share information across different parts of the code.
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.
count = 10 # global variable def show_count(): print(count) # prints 10 show_count()
global.score = 5 def increase_score(): global score score += 1 increase_score() print(score) # prints 6
This program shows how a global variable can be read and changed inside functions.
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()
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.
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.
global keyword do inside a Python function?global keywordglobal keyword tells Python that the variable inside the function refers to the variable defined outside (in global scope).global, assigning a value creates a new local variable. With global, it modifies the existing global variable.global followed by the variable name, separated by a space.count = 5
def increment():
global count
count += 1
increment()
print(count)count is defined globally with value 5. Inside increment(), global count allows modifying this global variable.count, changing it from 5 to 6. Then print(count) outputs 6.total = 10
def add():
total += 5
add()
print(total)add(), total += 5 tries to modify total. Without global total, Python treats total as local but it's used before assignment, causing an error.global total inside add() tells Python to use the global total variable, fixing the error.global inside the function.global, causing error. calls = 0
def func():
global calls
calls += 1
func()
print(calls) correctly uses global calls and increments. calls = 0
def func():
calls = calls + 1
func()
print(calls) tries to read and assign without global, causing UnboundLocalError. calls = 0
def func():
global calls
calls = calls
func()
print(calls) declares global but does not increment.