问题
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