In Python, you can use the global
keyword to access and modify global variables from within a function. Here’s an example:
x = 10 # a global variable
def my_func():
global x
x += 1 # modify the global variable
print(x)
my_func() # Output: 11
In this example, we define a global variable x
with a value of 10. Then we define a function my_func()
that uses the global
keyword to access and modify the value of x
. Inside the function, we increment x
by 1 and print its new value.
When we call my_func()
, it outputs the new value of x
, which is 11. Note that without the global
keyword, we would get a NameError
because x
is not defined within the function’s local scope.
It’s generally recommended to avoid using global variables whenever possible, because they can make code more difficult to understand and debug. Instead, you can pass variables as arguments to functions and return values from functions as needed.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.