简体   繁体   中英

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 . Unlike other languages, whitepace makes a big difference in Python, so consistency is important.

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. When using -tt these warnings become errors. 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).

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. What i learned is return statement should be some thing like this.

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

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. However, you will get an python error - SyntaxError :'return' outside function if the return is indented as below.

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

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.

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.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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