Why does Python says that 'foo' is a local variable despite the fact that I have declared it global?
本问题已经有最佳答案,请猛点这里访问。
我在写一个小游戏,在游戏中你会在脑海中猜测一个介于0和100之间的数字,电脑会尝试去猜测它。下面是一段代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import random global foo foo=input() global k k=random.randint(0,100) def f(): if foo.lower()=='too low': k=random.randint(k,100) foo=input('The number that I guessed is' + ' ' + str(k) +'. Please give your comment.') print(k) f() |
它抛出一个错误,说:
UnboundLocalError: local variable ‘foo’ referenced before assignment
本站其他帖子建议使用
将EDOCX1[0]从全局范围移动到函数内部,如下所示:
1 2 3 4 5 6 7 8 9 10 11 | import random foo=input() k=random.randint(0,100) def f(): global foo global k if foo.lower()=='too low': k=random.randint(k,100) foo=input('The number that I guessed is' + ' ' + str(k) +'. Please give your comment.') print(k) |