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.
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.
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
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
Videos
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)
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
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?
Might not be exactly on topic but I wish more people would code their functions to NOT return None and instead return expected type.
BeautifulSoup is the biggest perpetrator of this. Whenever you parse the tree/soup you'll either get a list of results or a single result, now if no results are found instead of getting an empty list you get None returned, which in turn requires you to make checks on every single lookup which really messes up your code up and makes everything look ridiculous.
switched to lxml/xpath and never looked back.
Per PEP-20, explicit is better than implicit, so when I'm writing code where None is a valid answer, I explicitly return a None. If it's an error to get to the end, raise an error.
If it's a hack/preliminary code, I don't care. For production level code, I have one return and it's the last line of the function/method. For a short function, I don't really care, but definitely for a long function.
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)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