I have been learning python about a week now, below is the question:
Code
def Foo(): pass def Bar(): return None
Usage
a = Foo() print(a) # None b = Bar() print(b) # None
Question: 1. Why do we need pass when we already have return None? Is there some scenario that return None can not handle but pass can?
Return exits the current function or method. Pass is a null operation and allows execution to continue at the next statement.
If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.
As other have answered, the result is exactly the same, None is returned in all cases. The difference is stylistic, but please note that PEP8 requires the use to be consistent: Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should.
In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
pass
is an "empty" command, but return
stops the function / method.
Examples:
def func(): do_something() #executed pass do_something_else() #also executed
but:
def func2(): do_something() #executed return None do_something_else() #NOT executed
In the second case, return None
is: "stop the function and return None". But pass
is just like "go to the next line"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With