Invalid syntax on '='

我是研究僧i 提交于 2020-01-30 08:47:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/18800004/invalid-syntax-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!