使用全局时“="上的语法无效 [英] Invalid syntax on '=' when using global
本文介绍了使用全局时“="上的语法无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
f=1定义跳过(i):全局 f +=i返回
怎么了?
我不知道
<预><代码>>>>F1>>>跳过(3)回溯(最近一次调用最后一次):文件<pyshell#10>",第 1 行,在 <module> 中跳过(3)文件C:/Users/PC/Desktop/game.py",第 4 行,跳过f +=iUnboundLocalError:赋值前引用了局部变量f" 解决方案
global
语句位于单独的行:
def 跳过(i):全局 ff += i
return
在这里是多余的;我已经放弃了.
global
声明 将函数中的名称标记"为全局;这是一个独特的声明,你只能给它一个或多个名称(用逗号分隔):
全局 foo, bar, baz
将它们放在函数中的哪个位置并不重要,只要它们在自己的一行上即可.该语句适用于整个函数.因此,在顶部粘贴 global
语句是有意义的,以避免混淆.
f=1
def skip(i):
global f +=i
return
What's wrong?
I don't know
>>> f
1
>>> skip(3)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
skip(3)
File "C:/Users/PC/Desktop/game.py", line 4, in skip
f +=i
UnboundLocalError: local variable 'f' referenced before assignment
解决方案
The global
statement goes on a separate line:
def skip(i):
global f
f += i
The return
is redundant here; I've left it off.
The global
statement 'marks' names in a function as global; it is a distinct statement and you can only give it one or more names (separated by commas):
global foo, bar, baz
It doesn't really matter where in the function you put them, as long as they are on a line of their own. The statement applies to the whole function. As such it makes sense to stick a global
statement at the top, to avoid confusion.
这篇关于使用全局时“="上的语法无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文