1

New to python and hope this is not trivial. I searched through google, and did not find a related answer.

This is a loosely related answer. I understand all of it, while it does not answer my question. Why would you use the return statement in Python?

Thank you very much for your time and attention.

Community
  • 1
  • 1
stone
  • 31
  • 2
  • 5
  • Also [documentation](https://docs.python.org/2/reference/simple_stmts.html#the-return-statement) states that "return may only occur syntactically nested in a function definition, not within a nested class definition." – metatoaster Sep 19 '16 at 12:18
  • Is there any context that led you to ask this question? –  Sep 19 '16 at 12:18
  • 6
    What would you expect it to do outside of a function? – jwodder Sep 19 '16 at 12:20
  • What exactly do you want to do? Maybe we can offer you the right keyword you're looking for. – Mukherjee Sep 19 '16 at 12:21
  • 1
    @PM2Ring Whoops, http://stackoverflow.com/questions/7842120/python-return-statement-error-return-outside-function would have been a better one. – metatoaster Sep 19 '16 at 12:38
  • @metatoaster It's still not perfect, but it's got an accepted answer by a Python core dev, so I guess it's close enough. :) – PM 2Ring Sep 19 '16 at 12:49

3 Answers3

3

Yes, it can only be used inside a function—this is defined in the language reference:

return may only occur syntactically nested in a function definition, not within a nested class definition.

kfb
  • 6,252
  • 6
  • 40
  • 51
2

Did you already see the docs?

return may only occur syntactically nested in a function definition, not within a nested class definition.

[Emphasis mine]

Also, considering the purpose of the return statement, it would not even make sense if it was usable outside of a function.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

You will get a SyntaxError if you try.

When in doubt, use the interactive interpreter by invoking python without any arguments:

$ python
Python 2.7.12+ (default, Sep  1 2016, 20:27:38) 
[GCC 6.2.0 20160822] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> return 4
  File "<stdin>", line 1
SyntaxError: 'return' outside function
>>>

It will help a lot for debugging and trying things out.

icarito
  • 328
  • 2
  • 11