In my Python development journey, I’ve seen this error trip up both interns and senior engineers alike.
It usually happens when you’re in a flow, refactoring a large block of code, and a single return statement ends up in the wrong place.
The “SyntaxError: ‘return’ outside function” is Python’s way of telling you that it found a return statement sitting out in the open where it doesn’t belong.
In this tutorial, I’ll share my firsthand experience on why this happens and show you the exact methods I use to fix it quickly.
What Causes the ‘return’ outside function Error?
In Python, the return keyword has a very specific job: it exits a function and sends a value back to the caller.
If you try to use return in the main body of your script, outside of any def block, Python gets confused because there is no “caller” to return to.
I’ve found that this almost always boils down to one of three things: improper indentation, using return when you meant break, or simply forgetting to wrap your logic in a function.
Method 1: Fix Indentation Issues
This is by far the most common reason I see this error during code reviews.
Python relies on whitespace to understand the structure of your code, so if your return isn’t indented far enough, it’s no longer part of the function.
The Problematic Code
Imagine I’m writing a script to calculate the sales tax for a retail client in New York. If I misalign the return, the script crashes immediately.
# A simple sales tax calculator for New York (8.875%)
def calculate_ny_sales_tax(price):
tax_rate = 0.08875
total_tax = price * tax_rate
# Oops! This return is not indented under the function
return total_tax
# Trying to call the function
iphone_price = 999
print(calculate_ny_sales_tax(iphone_price))I executed the above example code and added the screenshot below.

To fix this, I ensure the return statement is indented to the same level as the logic inside the function.
# Corrected: The return is now inside the function scope
def calculate_ny_sales_tax(price):
tax_rate = 0.08875
total_tax = price * tax_rate
return total_tax
# Now we can successfully calculate the tax
macbook_price = 1299
print(f"Total Tax: ${calculate_ny_sales_tax(macbook_price):.2f}")In my experience, using a code editor that shows “indentation guides” or vertical lines helps me spot these misalignments before I even run the code.
Method 2: Replace ‘return’ with ‘break’ in Loops
I often see developers try to use return to stop a loop that is running in the main script (not inside a function).
While return stops a function; it cannot be used to stop a standalone for or while loop.
The Problematic Code
Let’s say I’m scanning a list of flight prices to find the first one that fits a budget of $500 for a trip to Chicago.
flight_prices = [650, 720, 480, 550, 390]
for price in flight_prices:
if price <= 500:
print(f"Found an affordable flight: ${price}")
# This causes a SyntaxError because we are not in a function
return price When I’m working outside of a function and need to stop a loop, I use the break keyword instead.
flight_prices = [650, 720, 480, 550, 390]
affordable_flight = None
for price in flight_prices:
if price <= 500:
affordable_flight = price
print(f"Found an affordable flight: ${price}")
# Use break to exit the loop, not the script
break
print(f"Final Selection: ${affordable_flight}")I executed the above example code and added the screenshot below.

If you actually need to stop the entire script, you can use sys.exit(), but for most loop-breaking needs, break is the professional choice.
Method 3: Use ‘print’ Instead of ‘return’
If you aren’t trying to pass a value to another part of your program and just want to see the result in your terminal, you likely don’t need a return at all.
I’ve seen many beginners use return as if it were a “show me the answer” command.
The Problematic Code
Suppose I want to check the eligibility of a voter in Texas.
age = 20
citizen = True
if age >= 18 and citizen:
# This will throw the error because it's in the global scope
return "Eligible to vote"In this scenario, I replace return with print(). This displays the result without needing a function wrapper.
age = 20
citizen = True
if age >= 18 and citizen:
# Print works perfectly for scripts and top-level logic
print("Eligible to vote in the upcoming election.")I executed the above example code and added the screenshot below.

I usually prefer this approach for quick automation scripts where I don’t need the complexity of multiple function calls.
Method 4: Wrap Logic in a Main Function
In professional Python development, we often wrap our entire script logic inside a main() function.
This is a best practice I follow in every production-level project because it prevents global variable clutter and allows the use of return.
The Example
Here is how I would structure a script to calculate a tip for a dinner in Miami, ensuring the return is perfectly valid.
def calculate_tip(bill_amount, tip_percentage):
# Standard service tip calculation
return bill_amount * (tip_percentage / 100)
def main():
dinner_bill = 150.00
tip_rate = 20
# Now this return is valid because it's inside the main() function
tip_amount = calculate_tip(dinner_bill, tip_rate)
print(f"Your dinner bill in Miami: ${dinner_bill}")
print(f"Suggested Tip ({tip_rate}%): ${tip_amount:.2f}")
if __name__ == "__main__":
main()By using this structure, you never have to worry about the “outside function” error because all your logic lives inside a defined scope.
Handling Python syntax errors is part of the daily life of a developer. Once you understand that return is strictly for functions, you can fix this error in seconds.
I hope this tutorial helped you get your code back on track.
You may also like to read:
- NumPy Array to List in Python
- np.savetxt() Function in Python
- np.genfromtxt() Function in Python
- NumPy Reset Index of an Array in Python

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.