Skip to content

How to Fix "SyntaxError: 'return' outside function" in Python

How to resolve the Python SyntaxError when a return statement appears outside a function due to incorrect indentation and ensure proper code structure.

When writing Python code, you might encounter the SyntaxError: 'return' outside function. This error is a direct consequence of Python's strict reliance on indentation to define code blocks. It occurs when a return statement is found at an indentation level where it is not inside the body of any function.

Since the return statement's sole purpose is to exit a function and optionally pass back a value, it is syntactically invalid anywhere else. This guide will explain Python's indentation rules, show you how to fix this common error, and highlight the importance of consistency.

Understanding the Error: The Role of return and Indentation

In Python, unlike many other languages that use curly braces {} to define the body of a function, indentation is used to group statements together. All lines of code that are part of a function's body must be indented to the same level underneath the def statement.

The return statement is used to:

  1. Immediately exit the currently executing function.
  2. Optionally "return" a value to the caller.

If a return statement is not indented or is indented at the same level as the def keyword, Python considers it to be in the main, global scope (not inside any function) and therefore raises a SyntaxError.

Reproducing the SyntaxError

The error is most commonly caused by forgetting to indent the return statement.

Example of code causing the error:

def add_numbers(a, b):
    result = a + b
return result

try:
    x = add_numbers(7, 9)
    print(x)
except SyntaxError as e:
    print(f"This block won't be reached because SyntaxError halts parsing.")

Output (when the file is parsed):

  File "main.py", line 5
    return result
    ^
SyntaxError: 'return' outside function

Solution: Correcting the Indentation

To fix this error, you must indent the return statement so that it is properly aligned with the other lines inside the function's body.

Solution:

def add_numbers(a, b):
    result = a + b
    return result

x = add_numbers(7, 9)
print(x)

Output:

16

A Note on Consistent Indentation

Python requires all lines within the same code block to have the exact same level of indentation. Mixing indentation styles (e.g., using 4 spaces for one line and 2 spaces for another) will result in an IndentationError.

Conclusion

The SyntaxError: 'return' outside function is one of the most straightforward errors in Python and is almost always caused by incorrect indentation.

To fix it:

  • Ensure your return statement is indented so that it is part of a function's body.
  • Make sure that all lines within the same function body have a consistent level of indentation.

By paying careful attention to Python's whitespace rules, you can easily avoid this common syntax error.

Navigation