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
1952 M2 Mac fails to install rbenv install 3.1.3 due to errors
3159 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
1858 I want to run pyautogui without remote connection on Windows 10 in the cloud
2717 I want to display multiple lines with FFmpeg subtitles.
© 2026 OneMinuteCode. All rights reserved.