Using global variables within functions in Python can be handy for sharing common data across various parts of a program. However, it's crucial to use them judiciously to maintain code clarity and avoid unintended side effects. Here are five examples to illustrate different scenarios involving global variables.
Example 1: Accessing a Global Variable
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Explanation:
-
xis defined as a global variable with the value"awesome". -
myfunc()accesses the global variablexand prints"Python is awesome".
Output:
Python is awesome
Example 2: Local Variable Shadowing Global Variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Explanation:
- The global variable
xhas the value"awesome". - Inside
myfunc(), a new local variablexis defined with the value"fantastic". This shadows the global variablexwithin the function's scope. - After calling
myfunc(), the globalxremains unchanged.
Output:
Python is fantastic
Python is awesome
Example 3: Modifying Global Variable Inside a Function
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Explanation:
- Initially,
xis a global variable with the value"awesome". -
myfunc()modifiesxby declaring it as global within the function and then changing its value to"fantastic". - The change is reflected globally.
Output:
Python is fantastic
Example 4: Using Global Variables Across Multiple Functions
counter = 0
def increment():
global counter
counter += 1
def print_counter():
print("Counter:", counter)
increment()
increment()
print_counter()
Explanation:
-
counteris a global variable. -
increment()incrementscounterby 1 each time it is called. -
print_counter()prints the current value ofcounter. - Calling
increment()twice and thenprint_counter()reflects the globalcounter's value.
Output:
Counter: 2
Example 5: Global Variable and Local Scope
message = "original"
def outer():
message = "outer"
def inner():
global message
message = "inner"
print("Before inner():", message)
inner()
print("After inner():", message)
outer()
print("In global scope:", message)
Explanation:
- The global variable
messageis initially set to"original". -
outer()defines a local variablemessagewith the value"outer". -
inner()is defined withinouter()and modifies the globalmessageto"inner". - The prints demonstrate the scope of changes at each step.
Output:
Before inner(): outer
After inner(): outer
In global scope: inner
These examples demonstrate how global variables interact with local scopes and how the global keyword is used to modify global variables within functions. They show the importance of understanding scope to manage variables effectively in Python.
Top comments (0)