Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

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?

1 Answer

0 votes
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

Related questions

0 votes
2 answers
asked Sep 12, 2019 in Python by Sammy (47.6k points)
+2 votes
3 answers
0 votes
1 answer
0 votes
1 answer
+3 votes
2 answers
asked May 28, 2019 in Python by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...