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
3099 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
1961 I want to connect to the webcam from WSL(ubuntu)
1759 Error in x, y, and format string must not be None
1766 I want to run pyautogui without remote connection on Windows 10 in the cloud
2582 I want to display multiple lines with FFmpeg subtitles.
© 2026 OneMinuteCode. All rights reserved.