Sobes.tech
Junior — Middle

How can the scope of a global variable be managed when working with two functions in Python?

sobes.tech AI

Answer from AI

In Python, a global variable is declared outside of functions and is accessible for reading inside functions by default. To modify a global variable inside a function, you need to use the global keyword.

Example:

x = 10  # global variable

def func1():
    global x
    x = 20  # modify the global variable

def func2():
    print(x)  # prints the current value of the global variable

func1()
func2()  # will output 20

If you do not use global, then assigning a value to a variable inside a function creates a local variable with the same name, and the global variable remains unchanged.