Error solution about python:ocal variable 'xxx' referenced before assignment

The code example is as follows:
write picture description here
define a variable xxx outside the function, then reference this variable inside the function and change its value, the compiler prompts:
Unresolved reference 'xxx'
This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.
It probably means that the check finds that the variable has not been defined before the reference, because the dynamic assignment As well as the wrong input, the variable may be a local variable but is meant to be used. Top-level and class-level items have better support than instance items. (Improper translation, probably this is what it means)
After calling this function in the code and running it, I get an error:
write picture description here
After deleting the latter xxx = 'after'sentence, the code will not have problems:
write picture description here
After inquiring on the Internet, I learned that python has A keyword globle is used to refer to global variables. After trying, the problem is successfully solved:
write picture description here
in python functions, the modification operation should be for local variables. If there is a variable with the same name as the global variable, it will naturally appear before the modification. Such an error is not defined. If you are sure to refer to a global variable and modify it, you must add the global keyword

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764273&siteId=291194637