Syntaxerror: Return Outside Function

In this blog post we will try to teach our users how they can solve the syntaxerror: return outside function in a python programming language. One can encounter this error many a time while coding in that particular language. It is a type of syntax error in python. This syntax issue is nothing more than a straightforward indentation error. Typically, this error happens when the return function’s indent does not coincide with or align with the declared function’s indent.

 

 

Solution of SyntaxError: Return Outside Function

First, let’s see a case in which this error can arise.

 

def sub(a, b):
    print(a, b)
return a-b
print(sub(5,4))

 

The output of this code is an error that seems like:

 

 

The major reason for this error is that the return statement does not have the same indentation as other statements inside the function. The python will treat this as a line outside the function. The solution for the same is:

 

 

def sub(a, b):
    print(a, b)
    return a-b
print(sub(5,4))

 

 

In this case, as the indentation of the return statement is similar to other statements inside the function it will produce the output which is as follows:

 

 

We now know how crucial proper indentation is to programming. Indentation and whitespace are essential since Python does not employ curly braces as C does. As a result, when the return statement is typed inside the function, the outcome differs from when it is mentioned outside. To prevent any syntax mistakes, it is best to check your indentation correctly before using a method.

 

 

 

Also Read: Python Botocore

 

Share this post

Leave a Reply

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