简体   繁体   中英

Getting “SyntaxError: Invalid Syntax”, but don't know why

Getting "SyntaxError: Invalid Syntax", but don't know why

  File "cursor4.py", line 138
    global D=-1*((self.meteor_x_coordlist[i]-self.meteor_x_coordlist[i+1])+(self.meteor_y_coordlist[i]-self.meteor_y_coordlist[i+1]))
            ^
SyntaxError: invalid syntax

Here is the code:

for i in range(8):
    if ((self.meteor_x_coordlist[i]-self.meteor_x_coordlist[i+1])+(self.meteor_y_coordlist[i]-self.meteor_y_coordlist[i+1])) < 0:
        global D=-1*((self.meteor_x_coordlist[i]-self.meteor_x_coordlist[i+1])+(self.meteor_y_coordlist[i]-self.meteor_y_coordlist[i+1]))
    if D**0.5<(self.sizelist[i]/2)+(self.sizelist[i+1]/2):
        #print "-----------------------"
        self.meteorlist.remove(self.meteorlist[i])
        if self.meteorlist == []:
            pass   #psu

I think it's because you're using global here in a weird way. Looking at this tutorial , maybe do it like this:

global D
for i in range(8):
    test = ((self.meteor_x_coordlist[i]-self.meteor_x_coordlist[i+1])+(self.meteor_y_coordlist[i]-self.meteor_y_coordlist[i+1]))
    if test < 0:
        D=-1*test
    if D**0.5<(self.sizelist[i]/2)+(self.sizelist[i+1]/2):
        #print "-----------------------"
        self.meteorlist.remove(self.meteorlist[i])
        if self.meteorlist == []:
            pass   #psu 

You can't combine a global statement with an assignment. If you need both, put them on separate lines:

global D
D = whatever

But using global variables is often a bad idea in the first place. Usually you can get by using locals or instance variables in object oriented code. Using instance variables is much better than using globals, as you can have many objects in use at the same time, without them all tripping over each other using the same variable names.

If you just added the global line to fix an issue with D , it's probably because you're only assigning to it conditionally, and the next if test expects it to always have a value. In that case, you probably want to keep D a local variable, you'll just need to initialize it before starting the loop:

D = initial_value

for i in range(8):
    if something:
        D = new_value

    if some_condition(D): # this line requires D to always have a value!
        ... # do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM