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.
Table of Contents [hide]
Wrong indentation
Let’s see this with the help of example.
Here is simple function to get multiplication of two numbers.
1 2 3 4 5 6 7 |
def multiplicationOfNumber(x,y): z=x*y return z print(multiplicationOfNumber(10,20)) |
When you execute above program, you will get below error.
1 2 3 4 5 6 |
File "<ipython-input-1-8da1e430822d>", 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]
1 2 3 4 5 6 7 |
def multiplicationOfNumber(x,y): z=x*y return z print(multiplicationOfNumber(10,20)) |
When you execute above program, you will get below error.
Return statement without defining function
Another reason for this error can be if you did not define a function
and still using return
statement.
1 2 3 4 5 6 |
x=10 y=20 z=x*y return z |
When you execute above program, you will get below error.
1 2 3 4 5 6 |
File "<ipython-input-1-8da1e430822d>", 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