Skip to content Skip to sidebar Skip to footer

Invalid Syntax On '=' When Using 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 '', line

Solution 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.


Post a Comment for "Invalid Syntax On '=' When Using Global"