x = 0
def A():
x = 10 # Local variable of A x
def B():
global x # Use the global variable outside of the current function
Allocate 20 to the regional variable x of x = 20 # A
B()
print(x) # Local variable of A x output
A()
print(x)
I think the result will be 20, 20, If you print it out, 10, 20 comes out.
I have no idea! Is there a master who can explain it.
python global-variable
Because x in the A function is not a global variable!
Declaring global x means a global variable.
If you want to use x in the A function in the subscope, you can use the nonlocal keyword
© 2024 OneMinuteCode. All rights reserved.