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:
-
x
is defined as a global variable with the value"awesome"
. -
myfunc()
accesses the global variablex
and 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
x
has the value"awesome"
. - Inside
myfunc()
, a new local variablex
is defined with the value"fantastic"
. This shadows the global variablex
within the function's scope. - After calling
myfunc()
, the globalx
remains 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,
x
is a global variable with the value"awesome"
. -
myfunc()
modifiesx
by 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:
-
counter
is a global variable. -
increment()
incrementscounter
by 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
message
is initially set to"original"
. -
outer()
defines a local variablemessage
with the value"outer"
. -
inner()
is defined withinouter()
and modifies the globalmessage
to"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)