Python 莫名其妙的语法错误
在我试图定义一个n维向量类的过程中,我在定义乘法时遇到了一个“语法”错误,我真的不知道如何处理这个错误Python 莫名其妙的语法错误,python,python-3.x,syntax-error,Python,Python 3.x,Syntax Error,在我试图定义一个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:
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
文件“”,第40行
[int,float]中的elif类型(其他):
^
SyntaxError:无效语法
我已经多次使用缩进和elif语句,但我真的看不出问题是什么
提前感谢。问题肯定是压痕错误。我想这就是你的意图:
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
相同的缩进级别此elif
语句应属于哪个if
语句?它的缩进方式必须与随附的if
语句相同。是的,实际上一切都很混乱,谢谢你的帮助