Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"pass" same as "return None" in Python?

Tags:

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?

like image 995
singsuyash Avatar asked Apr 14 '16 11:04

singsuyash


People also ask

Is pass the same as return in Python?

Return exits the current function or method. Pass is a null operation and allows execution to continue at the next statement.

What does return None mean in Python?

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.

Is return the same as return None?

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.

What is a pass in Python?

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.


1 Answers

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"

like image 98
Vincent Avatar answered Nov 10 '22 01:11

Vincent