Online Tutorials & Training Materials | STechies.com
Register Login

SyntaxError: 'Return' Outside Function in Python

02 Sep 2019 1:13 pm || 0

Syntaxerror: 'return' outside function

This syntax error is nothing but a simple indentation error, generally this error occurs when the indent or return function does not match or align to the indent of defined function.

Example:

# Python 3 Code

def myfunction(a, b):
  # Print the value of a+b
  add = a + b
return(add)

# Print values in list
print('Addition: ', myfunction(10, 34));

Output:

File "t.py", line 7
    return(add)
    ^
SyntaxError: 'return' outside function

As you can see that line no. 7 is not indented or align with myfunction(), due to this python compiler compile the code till line no.6 and throws the error ‘return statement is outside the function.

Syntaxerror: 'return' outside function

Correct Example:

# Python 3 Code

def myfunction(a, b):
  # Print the value of a+b
  add = a + b

  return(add)

# Print values in list
print('Addition: ', myfunction(10, 34));

Output:

Addition:  44

Conclusion

We have understood that indentation is extremely important in programming. As Python does not use curly braces like C, indentation and whitespaces are crucial. So, when you type in the return statement within the function the result is different than when the return statement is mentioned outside. It is best to check your indentation properly before executing a function to avoid any syntax errors.