How to fix SyntaxError: 'return' outside function in Python

When you’re programming in Python, you might encounter the following error:

SyntaxError: 'return' outside function

This error occurs when you put a return statement outside of a function body. You probably forgot to indent the line where you put the return statement.

This tutorial will show an example that causes this error and how to fix it in practice.

How to reproduce this error

Suppose you have a function named sum() that sums the value of two numbers.

You defined the function as follows:

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

x = sum(7, 9)

When you run the code above, you get the following error:

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

The error occurs because the line return result is not indented properly, so Python considers it to be outside of the sum() function block.

How to fix this error

To resolve this error, you need to put the return statement inside the function body.

This is done by adding indentations before the return keyword as shown below:

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

x = sum(7, 9)
print(x)  # 16

The indentation for code inside the function body must be consistent, or you’ll get the no matching indentation level error.

Once you fixed the indentation, run the code again. Notice that this time you didn’t get the syntax error.

Now you’ve learned how to fix the return outside function syntax error. Nice work! 👍

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.