Junior — Middle
Kuidas hallata globaalmuutuja ulatust, töötades kahe funktsiooniga Pythonis?
sobes.tech AI
Vastus AI-lt
In Python, a global variable is declared outside of functions and is available for reading inside functions by default. To modify a global variable inside a function, the global keyword must be used.
Example:
x = 10 # global variable
def func1():
global x
x = 20 # changes the global variable
def func2():
print(x) # prints the current value of the global variable
func1()
func2() # will print 20
If global is not used, then within the function, assigning a value creates a local variable with the same name, and the global variable remains unchanged.