On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set 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

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

Answer from user2032433 on Stack Overflow
Top answer
1 of 5
787

On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.

Using return None

This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.

In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None

Using return

This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.

We've got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function.

def find_prisoner_with_knife(prisoners):
    for prisoner in prisoners:
        if "knife" in prisoner.items:
            prisoner.move_to_inquisition()
            return # no need to check rest of the prisoners nor raise an alert
    raise_alert()

Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught.

Using no return at all

This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java.

In the following example, we set 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

Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught.

2 of 5
57

Yes, they are all the same.

We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

import dis

def f1():
  print "Hello World"
  return None

def f2():
  print "Hello World"
  return

def f3():
  print "Hello World"

dis.dis(f1)
    4   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    5   5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f2)
    9   0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE

    10  5 LOAD_CONST    0 (None)
        8 RETURN_VALUE

dis.dis(f3)
    14  0 LOAD_CONST    1 ('Hello World')
        3 PRINT_ITEM
        4 PRINT_NEWLINE            
        5 LOAD_CONST    0 (None)
        8 RETURN_VALUE      
🌐
Reddit
reddit.com › r/learnpython › eli5 how does "none" work exactly?
r/learnpython on Reddit: ELI5 how does "None" work exactly?
October 6, 2023 -

I get the general idea that None is a type when there is no specific value to be return.

But I am just confused on how to explicitly have a value of "None" . I am still learning python so I want to understand in which case does a function returns the value of "None". Like, it would also be helpful is someone could share a short function that displays "None" , preferably with no "return".

I've search online and there was an example of print(print("hi")), I kind of get this, the interpreter displays the first print and the second one is "None" because there is no value.

Thanks in advance

🌐
Real Python
realpython.com › python-return-statement
The Python return Statement: Usage and Best Practices – Real Python
June 14, 2024 - If you don’t supply an explicit return statement with an explicit return value, then Python will supply an implicit return statement using None as a return value. In the above example, add_one() adds 1 to x and stores the value in result but it doesn’t return result. That’s why you get value = None instead of value = 6.
Top answer
1 of 2
9

This is a recursive function. When you reach the terminal case (string == ""), you return 1 or 2. That gets returned to the calling function -- the previous call of nfsmsim. But that call of of nfsmsim doesn't return anything! You need to get the value from the terminal call of nfsmsim and pass it on by returning it again.

In other words, you need a return statement in each of these two branches of your if statement:

elif (current, string[0]) in edges.keys():
    global loc
    string = string[1:]
    nfsmsim(string, loc[0], edges, accepting)
elif len(loc)>1:
    global loc
    nfsmsim(string, loc[1], edges, accepting)
2 of 2
2

Not using a return command when the function ends is the same as using return None.

As the function is recursive and you are using its result, you must return the value of every of its call also inside its body:

elif (current, string[0]) in edges.keys():
    global loc
    string = string[1:]
    return nfsmsim(string, loc[0], edges, accepting)
elif len(loc)>1:
    global loc
    return nfsmsim(string, loc[1], edges, accepting)

You should forget about using the global loc. Just pass it via the argument. It is a reference anyway:

edges = { (1, 'a') : [2, 3],
          (2, 'a') : [2],
          (3, 'b') : [4, 3],
          (4, 'c') : [5] }
accepting = [2, 5] 
loc = []
def nfsmsim(string, current, edges, accepting, loc): 

    if string != "":
        if ((current, string[0]) in edges.keys()):
            loc = edges[(current, string[0])]
            print "edge found:",loc

    if (string == ""):
        print "string is over",current,accepting
        print type(current), type(accepting)
        if current in accepting : 
            print "1"
            return True
        else: 
            print "2"
            return 2
    # fill in your code here 
    elif (current, string[0]) in edges.keys():
        string = string[1:]
        return nfsmsim(string, loc[0], edges, accepting, loc)
    elif len(loc)>1:
        return nfsmsim(string, loc[1], edges, accepting, loc)


# This problem includes some test cases to help you tell if you are on
# the right track. You may want to make your own additional tests as well.
print nfsmsim("abc", 1, edges, accepting, loc)

It prints the following on my console:

c:\tmp\___python\fixxxer\so10274792>python a.py
edge found: [2, 3]
edge found: [4, 3]
edge found: [5]
string is over 5 [2, 5]
<type 'int'> <type 'list'>
1
True
🌐
Reddit
reddit.com › r/python › return none or not to return none
r/Python on Reddit: return None or not to return None
June 8, 2013 -

Several weeks ago a was pursuing some of the posts here on python and stumbled on an article about bad programming habits. I cant find the article again for reference but right at the top was a heady warning to avoid returning a meaningful None. AT the time I thought, 'well thats just droll and I never do that anyway', but as it turns out I do it all the time. If the function finds the correct thing then return the correct thing otherwise just end the function and python will return None for you.

So do you guys do the same thing? Whats wrong with returning None in the first place? What strategies do you use to avoid returning None?

🌐
Quora
quora.com › What-does-it-mean-when-the-Python-function-returns-none
What does it mean when the Python function returns none? - Quora
Answer (1 of 6): There are no inherently implied semantics attached to None-returning functions. In other words, it means whatever you want it to mean. In Python, interpreted and dynamically typed as it is, functions don't have return types. There is no type checker to enforce that a function re...
🌐
Reddit
reddit.com › r/learnpython › why does this function return none instead of a value?
r/learnpython on Reddit: Why does this function return None instead of a value?
February 7, 2022 -
def baseConverter(number, base):
    final_base = ""
    division_base = base
    while division_base >= 10:
        division_base /= 10
    division_base = int(division_base)
    result = math.floor(number / division_base)
    remainder = number % division_base
    base = int(str(base) + str(remainder))
    if result == 0:
        base = str(base)
        print("Final base is " + base)
        print("This value should be returning: " + base[1:])
        final_base = base[1:]
        return final_base
    else:
        baseConverter(result, base)
🌐
Real Python
realpython.com › lessons › returning-none-explicitly
Returning None Explicitly (Video) – Real Python
You actually have to print the result of a function call to see that it does indeed return None. 01:11 Next, we’ll look at having just a bare return statement, 01:17 so we’ll have return but no return value. If we print the result of its function call, we get None.
Published   August 10, 2021
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-none-printed
Why does my function print None in Python [Solved] | bobbyhadz
Functions often print None when we pass the result of calling a function that doesn't return anything to the print() function. All functions that don't explicitly return a value, return None in Python.
🌐
Quora
quora.com › In-Python-what-does-return-None-mean-if-inside-a-function-we-use-return-without-any-value
In Python, what does return None mean if inside a function we use return without any value? - Quora
Answer (1 of 4): You’re correct; just a simple [code ]return[/code] statement without a value will return [code ]None[/code] implicitly. The reason why this happens is because Python has no concept of void. In C, if you wanted to not return ...
🌐
Better Programming
betterprogramming.pub › please-stop-returning-none-from-python-functions-ff98e492b4b0
Stop Returning None From Python Functions | by Imran Ali | Better ...
August 10, 2023 - The function returns None when the denominator is 0. This makes sense as the result is undefined so sending None sounds natural. However, the user of the function can incorrectly use it as shown below.
🌐
Julianhysi
julianhysi.com › post › 4
Julian's Blog - Bare return vs return None vs no return
Every function in Python which does not hit a return statement, will implicitly return None. This leaves the Python developer with a few options: - don't do anything (the function will implicitly return None) ... Now, all of these options will return None, so there's no difference in behavior.
🌐
Team Treehouse
teamtreehouse.com › community › python-function-returns-a-none-value-for-no-reason
python function returns a none value for no reason (Example) | Treehouse Community
January 30, 2016 - this function return None if i run it more then once can anybody tell me why ? ... I haven't explicitly tested, but it's likely because this is intended to be a recursive function, but you don't return the call when it's called from within itself. Instead, when called from inside itself, the innermost return value is discarded, and None is passed up and returned by the original invocation.
🌐
Python.org
discuss.python.org › python help
Why does the my code return none!? I’m a noob so I don’t know whether the question is overtly stupid or what😃 - Python Help - Discussions on Python.org
July 25, 2021 - This returns none. Ideal behind program is to convert Celsius to Fahrenheit using Fahrenheit = (9/5) * celsius + 32 But when I write return (9/5) * c + 32 it gives the desired result Just curious on the difference between print ((9/5) * c + 32) and return
🌐
Codecademy
codecademy.com › forum_questions › 54f64ad795e3788c240004cc
17/19 code looks OK but return returns "None". | Codecademy
In the code that you posted here, the body of the function has not been indented, but it needs to be. However, even if the code that you submitted to the Python interpreter is indented correctly, you will not see the value returned by your shut_down function, as it is currently written, because you do not have any print statements anywhere in your code. So, if you see None printed, it is not an indication that your function returned None.
🌐
AskPython
askpython.com › home › python return statement
Python return Statement - AskPython
May 11, 2023 - In Python, every function returns something. If there are no return statements, then it returns None. If the return statement contains an expression, it’s evaluated first and then the value is returned.
🌐
Reddit
reddit.com › r/learnpython › why does this recursive solution return 'none' instead of the array value?
r/learnpython on Reddit: Why does this recursive solution return 'none' instead of the array value?
December 9, 2019 -

I was practicing a leetcode problem and can't for the life of me figure out why this recursive solution returns none instead of the value of the array. When I print the array directly before the return, it gives me a populated array, but when I run the full runningSum function it gives me nothing. What am I missing? Picture of the problem in question

class Solution(object):
    def runningSum(self, nums):
        arr = []
    
        def summ(nums):
            if nums == []:
                print(arr)
                return arr
        
            total = 0

            for i in reversed(nums):
                total += i
            
            arr.append(total)
            summ(nums[:-1])
        
        return summ(nums)

edit: I know that even if this worked I'd still need to reverse the array. I'm just more bothered that I can't get the function to return the array

🌐
Codecademy
codecademy.com › forum_questions › 558d38019113cbc609000498
Function keeps returning None | Codecademy
In that case, you have range(2,2). This gives you an empty list [ ] because the second argument has to be greater than the first one when calling range(). The for-loop can’t iterate over an empty list because it has no elements. Thus it is skipped. Your code then doesn’t return anything, which basically is the same as None:
🌐
Python.org
discuss.python.org › python help
Why does one version of my function return None, while the other works fine? - Python Help - Discussions on Python.org
October 26, 2023 - Inspired by the pipeline operator (|>) in other languages, I tried to implement a function to imitate it. When I use reduce to implement it, it results in None somewhere along the way, but another one using loops works just fine. from functools import partial, reduce from pprint import pprint def pipeline(data, *funcs): res = data for func in funcs: res = func(res) return res def pipeline_v2(data, *funcs): reduce(lambda arg, func: func(arg), funcs, data) def main() ->...