Pass and return
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Dec 21 03:27:47 EST 2012
On Thu, 20 Dec 2012 21:23:58 -0800, iMath wrote:
> Pass and return
> Are these two functions the same ?
They are neither functions, nor are they the same.
Check if they are functions:
- can you pass them arguments?
- can you assign their result to a target?
No.
py> pass(23)
File "<stdin>", line 1
pass(23)
^
SyntaxError: invalid syntax
py> x = return
File "<stdin>", line 1
x = return
^
SyntaxError: invalid syntax
Are they the same? Try it with these two functions:
def test_pass():
for i in range(100):
pass
print i
def test_return():
for i in range(100):
return
print i
py> test_pass()
99
py> test_return()
py>
So what are they?
They are *statements*, not functions. You cannot pass them arguments, nor
do they assign a result to a target on the left hand side of = equals
sign.
"pass" is a do-nothing statement. It literally does nothing.
"return" exits a function and sets the return result. It is only legal
inside functions and generators, while "pass" is legal almost anywhere.
Normally you say "return some_value", but you can leave out the result
and Python will "return None".
If functions get all the way to the bottom without a return statement,
they will return None.
The example you give:
> def test():
> return
The body of the function immediately returns None. But functions return
None by default, so you could leave the "return" statement out. If you do
that, you will get a SyntaxError because there is nothing in the body:
py> def test():
...
...
File "<stdin>", line 3
^
IndentationError: expected an indented block
So if you put a "pass" statement in, just to satisfy the compiler, you
get the same result:
> def test():
> pass
Also a function which immediately exists and return None.
--
Steven
More information about the Python-list
mailing list