Python function returns none after 3 rd use of None
cc
gets called twice here.
print cc(klds(asa()))
, equivalent to print cc(7)
is the first time it gets called. Trace it through:
if k != 7: # Nope, keep going...
print 2
rt(k+2)
We've hit the end of the function. There is no return statement, so it return None
, which is what you're seeing at the end.
To fix it, make sure you're returning your values. (i.e. return rt(k+2)
instead.)
There is a similar problem elsewhere in your code you'll also have to fix before it works like you want it to.
return, return None, and no return at all?
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.
Python Script returns unintended None after execution of a function
In python the default return value of a function is None
.
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not printed.
>>>
So, just use:
letter_grade(score) #remove the print
Another alternative is to replace all prints with return
:
def letter_grade(score):
if 90 <= score <= 100:
return "A"
elif 80 <= score <= 89:
return "B"
elif 70 <= score <= 79:
return "C"
elif 60 <= score <= 69:
return "D"
elif score < 60:
return "F"
else:
#This is returned if all other conditions aren't satisfied
return "Invalid Marks"
Now use print()
:
>>> print(letter_grade(91))
A
>>> print(letter_grade(45))
F
>>> print(letter_grade(75))
C
>>> print letter_grade(1000)
Invalid Marks
How to prevent Python function from returning None
Python will always return None
, if no return is specified at the point of exiting the function call. Your options are:
- return something else if the condition is not met.
- ignore the function if it returns
None
option 1 (return something else when the condition isn't met):
def html_check(td, text):
if td.text == text:
value = td.find_next('td').text
return value
return "no value found"
option 2 (ignores the function if None
is returned):
if html_check(td, 'section'):
# do things
Is there a way to return literally nothing in python?
There is no such thing as "returning nothing" in Python. Every function returns some value (unless it raises an exception). If no explicit return
statement is used, Python treats it as returning None
.
So, you need to think about what is most appropriate for your function. Either you should return None
(or some other sentinel value) and add appropriate logic to your calling code to detect this, or you should raise an exception (which the calling code can catch, if it wants to).
Related Topics
Weird Behavior: Lambda Inside List Comprehension
If Two Variables Point to the Same Object, Why Doesn't Reassigning One Variable Affect the Other
Where to Put Django Startup Code
Django JSONfield Inside Arrayfield
Matplotlib - Add Colorbar to a Sequence of Line Plots
Why Does @Foo.Setter in Python Not Work for Me
How to Upload a File to Google Cloud Storage on Python 3
Nltk Naivebayesclassifier Training for Sentiment Analysis
Matching Any Character Including Newlines in a Python Regex Subexpression, Not Globally
SchröDinger's Variable: the _Class_ Cell Magically Appears If You'Re Checking for Its Presence
Repeat Rows in Data Frame N Times
Integer Overflow in Numpy Arrays
Why Do I Get "Pickle - Eoferror: Ran Out of Input" Reading an Empty File
Tab Completion in Python's Raw_Input()
Why Doesn't Django's Model.Save() Call Full_Clean()
Best Way to Determine If a Sequence Is in Another Sequence