In Python how to Use global variables in a function?

0
0

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.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.