Python Script Returns Unintended "None" After Execution of a Function

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

Why is None printed after my function's output?

It's the return value of the function, which you print out. If there is no return statement (or just a return without an argument), an implicit return None is added to the end of a function.

You probably want to return the values in the function instead of printing them:

def jiskya(x, y):
if x > y:
return y
else:
return x

print(jiskya(2, 3))

Why is None printed after every line?

You're printing the return value of make_sound here: print userchoice.make_sound(). Since make_sound doesn't explicitly specify return value None is returned by default and that's what you see in the output.

You can fix the problem by either not printing the return value or changing make_sound to return the sound instead of printing it.

Why is None printed after every line?

You're printing the return value of make_sound here: print userchoice.make_sound(). Since make_sound doesn't explicitly specify return value None is returned by default and that's what you see in the output.

You can fix the problem by either not printing the return value or changing make_sound to return the sound instead of printing it.

function return none instead of return number

You're performing a chained equality comparison which is not doing what you think it does. The bitwise & is performed first as it has a higher priority than ==.

Replace:

x == 1 & y == 0
# 1 == 1 & 0 == 0
# 1 == 0 == 0 False!

With:

x == 1 and y == 0

See: Operator precedence

Return items from list in function. Python

You are printing the return code from func which is none. Just call func(my_list) without the print.



Related Topics



Leave a reply



Submit