2017-03-17 21 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