3 views
in Python

Consider three functions:

def my_func1():

print "Hello World"

return None

def my_func2():

print "Hello World"

return

def my_func3():

print "Hello World"

They all appear to return None. Are there any differences between how the returned value of these functions behaves? Are there any reasons to prefer one versus the other?

by (106k points)

When we see the actual behaviour of all the three return statements then there is no difference. All these return None. However, it depends on the situation at which time and at which place they will be used.

Below are some instructions which will clear your doubt about how the different methods should be used:-

Where to use return None:-

The return statement meant to return a value for later use, and in that case, it returns None.  Below is the example for return None.

def get_mother(person):

if is_human(person):

return person.mother

else:

return None

## Where to using return:-

The return statement is used for the same reason as a break is used in loops. It is used to exit the whole function. Below is an example regarding the return statement.

In the below -mentioned example let we have got 15 blocks and we know one of them contains a knife. So to know which one of them contains a knife we will loop through each blocks one by one to check if they have a knife. If we hit the correct blocks with a knife, we can just exit the function cause we know there is only one knife and no reason the check rest of the blocks. So to exit after getting a knife we will use return.

def find_prisoner_with_knife(blocks):

for blocks in blocks:

if "knife" in blocks.items:

block.move_to_inquisition()

return

## Where we will not use return at all:-

While if you do not use the return then it will return None as well.

Below is an example where we have set a person's mother's name, and then the function exits after completing successfully.

def set_mother(person, mother):

if is_human(person):

person.mother = mother