Return outside function Python: How to Resolve This Error
In Python, don’t use the return statement to get out of the loop. If you do that, then you will face the SyntaxError. Instead, use the break or quit() statement to break the loop or terminate the program.
Return outside function Python
When you are working in a loop, you mistakenly use the return statement to break the loop instead of using the break or quit() function. If you are using return, you will get the SyntaxError: return outside function in Python. This syntax error suggests that you are not using the return statement within the function because you are using it in the loop, and that loop is not enclosed by a function.
For example, see the below code.
while True: return False
The above while loop should not have a return statement because it does not break the loop.
It does not make any sense to stop a while loop by using the return statement.
If you run the above code, then you will get the following output.
return False ^ SyntaxError: 'return' outside function
We get the SyntaxError: ‘return‘ outside function.
To resolve the return outside function SyntaxError in Python, create a function and write the loop inside that function, and then use the return function. This is the correct way to use the return.
def func(): while True: return False print(func())
And we resolved the error and get the expected output.
Using break keyword
To break the loop in Python, use the break keyword. The break statement ends the loop. If the break statement is inside the nested loop (loop inside another loop), the break will terminate the innermost loop.
Let’s take a for loop and range() function to iterate in-range elements and break the loop if certain conditions are met.
for i in range(1, 10): if(i == 2): break print(i*5)
In the first iteration, the conditions are not met, so it prints 5, and in the second iteration, when i = 2, it breaks the loop because i = 2 condition satisfied. It executes the break keyword, which ultimately stops the execution.
Using quit() function in Python
To exit the Python program, use the quit() function. As soon as the system finds the quit() function, it terminates the program’s execution immediately.
for i in range(1, 10): if(i == 2): quit() print(i*5)
You can see that it immediately quits the program when i = 2.
It raises the SystemExit exception behind the scenes. If you print it, it will give a message.
That is it for “return outside function” SyntaxError in Python Tutorial.