Python:赋值前引用的局部变量“字符串”

Cri*_*spy 1 python string variables function

我想知道为什么从函数向该字符串添加字母时会出现此错误。
local variable 'string' referenced before assignment

代码

def update_string():
    string+='d'


string='s'

update_string()
Run Code Online (Sandbox Code Playgroud)

Hai*_* Vu 5

您正在访问全局变量,需要声明它:

def update_string():
    global string # <<< declare `string` as global variable.
    string+='d'


string='s'

update_varibles()
Run Code Online (Sandbox Code Playgroud)

  • 如果这是通过“update_string”的输入参数来完成的,那就更好了。“global”通常不是最好的选择 (2认同)