简体   繁体   English

Python语法错误:'返回'外部函数

[英]Python SyntaxError :'return' outside function

Compiler showed:编译器显示:

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

Where was I wrong?我哪里错了?

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

What about this?那这个呢?

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

I would check my indentation, it looks off.我会检查我的缩进,它看起来不对。 Are you possibly mixing tabs and spaces?您是否可能混合使用制表符和空格? The PEP8 (Python Style Guide) recommends using 4 spaces only . PEP8(Python 风格指南)建议使用4 个空格 Unlike other languages, whitepace makes a big difference in Python, so consistency is important.与其他语言不同,空格在 Python 中有很大的不同,因此一致性很重要。

The above also makes the following recommendation:以上也提出以下建议:

When invoking the Python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces.使用 -t 选项调用 Python 命令行解释器时,它会发出有关非法混合制表符和空格的代码的警告。 When using -tt these warnings become errors.使用 -tt 时,这些警告会变成错误。 These options are highly recommended!强烈推荐这些选项!

In particular, your 2nd else seems to be off (probably should be indented), and this method def __div__(self, other): too (which I would think ought to be at the same level as your other def s - ie, moved "out" rather than indented).特别是,您的第二个else似乎已关闭(可能应该缩进),并且此方法def __div__(self, other):也是(我认为应该与您的其他def处于同一级别 - 即,移动“出”而不是缩进)。

Problems mixing tabs/blanks are easy to have since both characters are "invisible".由于两个字符都是“不可见的”,因此很容易出现混合制表符/空白的问题。

确保您的__div__是在同一级别的声明__str__ (现在,它的内部声明__str_ )。

By my copy and paste, everything from this line:通过我的复制和粘贴,这一行的所有内容:

else:
if self.imagPart >=0:
        return '%f+%fi'%(self.realPart, self.imagPart)
elif self.imagPart <0: # Everything under here..

To this line:到这一行:

    resultI = float(float(r2*i1-r1*i2)/float(r2*r2+i2*i2))
result = Complex(resultR, resultI)
return result # Needs to be unindented.

has wrong indenting.缩进错误。

Well i am new to python world.好吧,我是 python 世界的新手。 What i learned is return statement should be some thing like this.我学到的是 return 语句应该是这样的。

Example one :-示例一:-

def split_train_test(data, test_ratio):
    shuffled_indices = np.random.permutation(len(data))
    test_set_size = int(len(data) * test_ratio)
    test_indices = shuffled_indices[:test_set_size]
    train_indices = shuffled_indices[test_set_size:]
    return data.iloc[train_indices],data.iloc[test_indices]

Example two :-例子二:-

def load_housing_data(housing_path=HOUSING_PATH):
    csv_path = os.path.join(housing_path, "housing.csv")
    return pd.read_csv(csv_path)

I answered here:- https://stackoverflow.com/a/47377418/2298357我在这里回答:- https://stackoverflow.com/a/47377418/2298357

def functiont(x,y z,k):
    """some function
    """
    if xxxx:
        return True
    else
        return False

As per the code above you can see the return statement is indented inside the function def and hence there will be no error in this case.根据上面的代码,您可以看到return语句在函数 def 内缩进,因此在这种情况下不会出现错误。 However, you will get an python error - SyntaxError :'return' outside function if the return is indented as below.但是,如果 return 缩进如下,您将收到 python 错误 - SyntaxError :'return' 外部函数

def functiont(x,y z,k):
    """some function
    """
if xxxx:
    return True
else
    return False

Use a good editor使用好的编辑器

Install one of the below editors that can format your files properly安装以下可以正确格式化文件的编辑器之一

Format document格式化文件

For example: In Visual Studio code, Open the file > Right click > Format document例如:在 Visual Studio 代码中,打开文件 > 右键单击​​ > 格式化文档

Finding & Fixing the issue发现并解决问题

Once the code is formatted by editor, you will see something like below一旦代码被编辑器格式化,您将看到如下所示的内容

Bad code错误代码

def func1():
    print ("I am in func1")
    return ""               # <----------- this is ok, its inside function func1

def func2():
    print ("I am in func2")
return ""                   # <-----CASE 1------ SyntaxError: 'return' outside function 'func2'

print ("I am outside of all functions")
return ""                   # <-----CASE 2------ SyntaxError: 'return' outside of all functions

NOTE - In both CASE 1 & CASE 2, ERROR occurred because 'return' is not inside any function, it's outside of all functions.注意 - 在案例 1 和案例 2 中,发生错误是因为“返回”不在任何函数内,它在所有函数之外。

Good code好代码

def func1():
    print ("I am in func1")
    return ""           # <----------- this is ok, its inside function func1

def func2():
    print ("I am in func2")
    return ""           # <-----CASE 1-- Fixed, added SPACE or TAB, now 'return' is inside function

print ("I am outside of all functions")
                        # <-----CASE 2-- Fixed, 'return' is removed, no return is required here

This is very common issue you might face when you write code in python after a gap.这是一个非常常见的问题,当您在出现间隙后用 python 编写代码时可能会遇到。

Hope that helps.希望有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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