The source code
num = 1
def test():
num += 1
return num
print(test())
Error details
Possible reasons for
Undeclared variables appear in Python, and PY finds the scope of a variable by following a simple rule: If there is an assignment to a variable within a function, the variable is considered local and can be modified normally. However, if the variable is not defined inside the function, and there is no variable scope declaration (to call the external variable), the program cannot find the corresponding variable inside the function, so the error message of undefined variable will appear.
The solution
Declare variables as global variables, use global keywords when calling, and you can access them normally. The correct code is as follows:
num = 1
def test():
global num
num = num + 1
return num
print(test()) # output is:2
Read More:
- Global variable error: unboundlocalerror: local variable ‘l’ referenced before assignment
- Python error: local variable ‘XXXX’ referenced before assignment
- Solving Python error: local variable ‘a’ referenced before assignment
- Differences between shell script variable assignment and C language variable assignment
- non-static variable this cannot be referenced from a static context
- Can’t find Python executable “D:\python3\python.exe”, you can set the PYTHON env variable.
- Python Numpy.ndarray ValueError:assignment destination is read-only
- Error: global variable is ambiguous (conflict between using namespace STD and global variable)
- Python error type error: ‘range’ object does not support item assignment, solution
- Error in installing Matplotlib Library: permissionerror: [errno 13] permission denied: ‘/ usr / local / lib / python3.6’
- Cannot remove entries from nonexistent file /usr/local/bin/anaconda2/lib/python2.7/site-packages/eas
- Using the decorator may prompt property assignment expected. Vetur (1136)
- Assignment under multiple single edges is not supported for synthesis
- Error lnk1120: 2 unresolved external commands: vtkrenderingopengl_ Autoinit (construct, destroy), which is referenced in
- Arrow function should not return assignment no-return-assign
- Error: transfer of control bypasses initialization of: variable XXX solution
- The spring boot project directly replaces the referenced jar package
- error Expected an assignment or function call and instead saw an expression
- Node configuration environment variable and global installation of webapck
- MySQL error code 1217 (ER_ROW_IS_REFERENCED): Cannot delete or update a parent row: a foreign key co