PythonMastery
reference 2 min read · lesson 71 of 80 in Errors

SyntaxError: 'return' outside function

1 · The lesson

read

What this error means

Python found a return line that is not inside a function. return means "leave this function and hand back this value", so it only makes sense inside a def. Python decides what is inside a function by indentation: the body of a function is every line indented under the def. A return that sits at the left edge, or one level too far left, is outside it. Python finds this before running anything.

When you see it

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

Why it happens

1. The indentation slipped. The return is meant to be the last line of the function, but it lines up with the def instead of the body:

python
def add(a, b):
    total = a + b
return total

This often happens after copying code, mixing editors, or deleting a line above it.

2. You used return to stop a script. At the top level of a file there is no function to leave. Code like this works in some other languages, but not in Python:

python
total = 0
for n in [1, 2, 3]:
    total += n
return total

3. The def line went missing. You copied the body of a function from a tutorial or an answer, but not the def line above it.

The same mistake with loops gives SyntaxError: 'break' outside loop or 'continue' not properly in loop: a break or continue that is not inside a for or while.

How to fix it

Indent the return to line up with the body of the function:

python
def add(a, b):
    total = a + b
    return total

print(add(2, 3))      # 5

In a script, print the result instead of returning it:

python
total = 0
for n in [1, 2, 3]:
    total += n
print(total)          # 6

To stop a script early, use sys.exit(). It ends the program at that point, from anywhere:

python
import sys

name = ""
if not name:
    print("No name given, stopping.")
    sys.exit(1)       # the number is the exit code; 0 means success
print("Hello", name)  # never reached

If the code really should be a function, wrap it in one, then call it:

python
def total_of(numbers):
    total = 0
    for n in numbers:
        total += n
    return total

print(total_of([1, 2, 3]))   # 6

To see the structure clearly, turn on "render whitespace" in your editor (VS Code: View, Appearance, Render Whitespace). Every line of the function body should start at the same indentation.

When you'd see this in real code

  • A function cut from one file and pasted into another, where the editor lost the indentation of the last line.
  • Code from a notebook cell moved into a function, with the final return left at the old level.
  • A script that started as return result inside a function, after the def was removed to run the code directly.
  • An if block at the top level of a script with return inside it, meant as "stop here".

See Also

Found this useful? Share it with a friend who’s learning Python.