2024-05-23 14:06:23 发布
网友
我想知道为什么从函数向字符串添加字母时会出现此错误。local variable 'string' referenced before assignment
local variable 'string' referenced before assignment
def update_string(): string+='d' string='s' update_string()
您正在访问全局变量,需要声明它:
def update_string(): global string # <<< declare `string` as global variable. string+='d' string='s' update_varibles()
旧的“字符串”在函数的本地作用域中没有任何来源,因此python假设您正在讨论来自外部作用域的字符串。
此外,由于字符串是不可变的,通常的模式是创建一个新的字符串并返回它,因此您可能更愿意将函数接口更新为类似于:
def update_string(str_in): return str_in + 'd'
然后你可以用它来代替:
my_string = update_string(my_string)
您正在访问全局变量,需要声明它:
旧的“字符串”在函数的本地作用域中没有任何来源,因此python假设您正在讨论来自外部作用域的字符串。
此外,由于字符串是不可变的,通常的模式是创建一个新的字符串并返回它,因此您可能更愿意将函数接口更新为类似于:
然后你可以用它来代替:
相关问题 更多 >
编程相关推荐