2017-03-17 44 views
-2

在我試圖定義一個n維向量類,定義乘法,我真的不知道怎麼去解決,當我碰到一個「語法」錯誤...莫名的語法錯誤

class Vector: 
def __init__(self, v): 
    if len(v)==0: self.v = (0,0) 
    else: self.v = v 

#bunch of functions in between here.... 

def __mul__(self, other): 
    if type(other) == Vector: 
     if len(self.v) != len(other.v): 
      raise AssertionError 

    dotprod = 0 
    for i in range(len(self.v)): 
     dotprod += self.v[i+1] * other.v[i+1] 
    return dotprod 

elif type(other) in [int, float]: 

    new = [] 
    for component in self.v: 
     new.append(component*other) 
    return Vector(tuple(new)) 
else: 
    raise AssertionError 

錯誤如下:

File "<ipython-input-52-50a37fd0919a>", line 40 
elif type(other) in [int, float]: 
^
SyntaxError: invalid syntax 

我與縮進和ELIF語句多次玩耍了,我實在看不出是什麼問題。

在此先感謝。

+3

這個'elif'屬於哪個'if'語句?它必須按照隨附的if語句縮進。 – languitar

回答

3

問題肯定是縮進錯誤。我認爲這是您的本意:

def __mul__(self, other): 
    if type(other) == Vector: 
     if len(self.v) != len(other.v): 
      raise AssertionError 

     dotprod = 0 
     for i in range(len(self.v)): 
      dotprod += self.v[i+1] * other.v[i+1] 
     return dotprod 

    elif type(other) in [int, float]: 

     new = [] 
     for component in self.v: 
      new.append(component*other) 
     return Vector(tuple(new)) 
    else: 
     raise AssertionError 

這使elif有相同的縮進水平爲if

+0

是啊一切都真的很混亂,謝謝你的幫助 – dejz