Return, Return None, and No Return in Python: What's the Difference?
Consider the following functions:
def my_func1(): print("Hello World") return None def my_func2(): print("Hello World") return def my_func3(): print("Hello World")
While they may appear to all return None, there are subtle differences in their behavior.
Behavior Differences
When these functions are executed:
Usage Considerations
Return None
Return
No Return
Examples
Getting a Mother's Name (Return None):
def get_mother(person): if is_human(person): return person.mother else: return None
Finding a Prisoner with a Knife (Return):
def find_prisoner_with_knife(prisoners): for prisoner in prisoners: if "knife" in prisoner.items: prisoner.move_to_inquisition() return # No need to check the other prisoners. raise_alert()
Setting a Mother's Name (No Return):
def set_mother(person, mother): if is_human(person): person.mother = mother
The above is the detailed content of Python `return`, `return None`, and No `return`: What are the Key Differences?. For more information, please follow other related articles on the PHP Chinese website!