gpt4 book ai didi

Python SyntaxError :'return' 外部函数

转载 作者:太空狗 更新时间:2023-10-29 20:37:25 24 4
gpt4 key购买 nike

编译器显示:

File "temp.py", line 56
return result
SyntaxError: 'return' outside function

我哪里错了?

class Complex (object):
def __init__(self, realPart, imagPart):
self.realPart = realPart
self.imagPart = imagPart

def __str__(self):
if type(self.realPart) == int and type(self.imagPart) == int:
if self.imagPart >=0:
return '%d+%di'%(self.realPart, self.imagPart)
elif self.imagPart <0:
return '%d%di'%(self.realPart, self.imagPart)
else:
if self.imagPart >=0:
return '%f+%fi'%(self.realPart, self.imagPart)
elif self.imagPart <0:
return '%f%fi'%(self.realPart, self.imagPart)

def __div__(self, other):
r1 = self.realPart
i1 = self.imagPart
r2 = other.realPart
i2 = other.imagPart
resultR = float(float(r1*r2+i1*i2)/float(r2*r2+i2*i2))
resultI = float(float(r2*i1-r1*i2)/float(r2*r2+i2*i2))
result = Complex(resultR, resultI)
return result

c1 = Complex(2,3)
c2 = Complex(1,4)
print c1/c2

这个呢?

class Complex (object):
def __init__(self, realPart, imagPart):
self.realPart = realPart
self.imagPart = imagPart

def __str__(self):
if type(self.realPart) == int and type(self.imagPart) == int:
if self.imagPart >=0:
return '%d+%di'%(self.realPart, self.imagPart)
elif self.imagPart <0:
return '%d%di'%(self.realPart, self.imagPart)
else:
if self.imagPart >=0:
return '%f+%fi'%(self.realPart, self.imagPart)
elif self.imagPart <0:
return '%f%fi'%(self.realPart, self.imagPart)

def __div__(self, other):
r1 = self.realPart
i1 = self.imagPart
r2 = other.realPart
i2 = other.imagPart
resultR = float(float(r1*r2+i1*i2)/float(r2*r2+i2*i2))
resultI = float(float(r2*i1-r1*i2)/float(r2*r2+i2*i2))
result = Complex(resultR, resultI)
return result

c1 = Complex(2,3)
c2 = Complex(1,4)
print c1/c2

最佳答案

我会检查我的缩进,它看起来不对。你可能混合制表符和空格吗? PEP8 (Python Style Guide)建议使用 4 spaces only .与其他语言不同,白色空格在 Python 中有很大的不同,因此一致性很重要。

以上还提出以下建议:

When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

特别是,你的第二个 else 似乎关闭了(可能应该缩进),这个方法 def __div__(self, other): 也是(我会think 应该与您的其他 def 处于同一级别 - 即“移出”而不是缩进)。

混合制表符/空格很容易出现问题,因为这两个字符都是“不可见的”。

关于Python SyntaxError :'return' 外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13068043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com