Sitelet https://java2blog.com/syntaxerror-return-outside-function/

SyntaxError: ‘Return’ Outside Function

In this post, we will see about SyntaxError: 'Return' Outside Function in Python.

This error will generally occur when you do not put the return statement indentation properly with function definition.

💡 Did you know?

Unlike C,C++ or java, Python uses whitespace for indentation. All statements which are at same distance on right belong to same block.

There can be two main reasons for this issue.
[toc]

Wrong indentation

Let’s see this with the help of example.
Here is simple function to get multiplication of two numbers.

def multiplicationOfNumber(x,y):
    z=x*y
return z

print(multiplicationOfNumber(10,20))

When you execute above program, you will get below error.

  File "", line 3
    return z
            ^
SyntaxError: 'return' outside function

We are getting this error because return z is inline with def multiplicationOfNumber(x,y): but it should be in same block with z=x*y.

Let’s move return z to z=x*y block, you won’t see the error any more.
Below slider will help you understand it better.
[smartslider3 slider=4]

def multiplicationOfNumber(x,y):
    z=x*y
    return z

print(multiplicationOfNumber(10,20))

When you execute above program, you will get below error.

200

Return statement without defining function

Another reason for this error can be if you did not define a function and still using return statement.

x=10
y=20
z=x*y
return z

When you execute above program, you will get below error.

  File "", line 3
    return z
            ^
SyntaxError: 'return' outside function

You can solve this error by putting statements in function as multiplicationOfNumber and correctly indenting return statement.

That’s all about SyntaxError: ‘Return’ Outside Function in Python

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.