Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python return statement error " 'return' outside function"

Tags:

python

When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:     return False 

I get the following error

SyntaxError: 'return' outside function 

I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

like image 981
Jeff Avatar asked Oct 20 '11 20:10

Jeff


People also ask

Can you use return outside a function Python?

return has no meaning outside of a function, and so python raises an error. Show activity on this post. You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

Why is my return outside the function?

This syntax error is nothing but a simple indentation error, generally, this error occurs when the indent or return function does not match or align to the indent of the defined function. As you can see that line no.

How do you call an outside function in Python?

Say your function bar is in a file called foo.py on your Python path. Then you can do this: from foo import bar if bar(): print "bar() is True!"

How do you return a value from another function in Python?

Simply call a function to pass the output into the second function as a parameter will use the return value in another function python.


2 Answers

The return statement only makes sense inside functions:

def foo():     while True:         return False 
like image 63
Raymond Hettinger Avatar answered Sep 21 '22 03:09

Raymond Hettinger


Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

like image 34
buzzard51 Avatar answered Sep 21 '22 03:09

buzzard51