My very simple python function is returning \'None\' at the end of it and I\'m not sure quite why. I\'ve looked at some other posts and still can\'t figure it out. Any help
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
printmult(30)
The issue was that you were printing the return value of a function that returns nothing, which would print None
I came from Ruby as well and it seems strange at first.
If you print
something that has a print
statement in it, the last thing it returns is None
.
If you just returned the values and then invoked a print
on the function it would not output None
.
Hope this helps :)
The other answers have done a good job of pointing out where the error is, i.e. you need to understand that printing and returning are not the same. If you want your function to return a value that you can then print or store in a variable, you want something like this:
def returnmult(n):
i = 1
result_string = ''
while i <= 10:
result_string += str(n * i) + ' '
i += 1
return result_string
print(returnmult(30))
You are not returning anything in the function printmult
, therefore when you print the result of printmult(30)
it will be None
(this is the default value returned when a function doesn't return anything explictly).
Since your method have a print
statement inside and it's not supposed to return something (usually when a method names is something like printSomething()
, it doesn't return anything), you should call it as:
printmult(30)
not
print(printmult(30))
Because in Python, every function returns a value, and None
is what is returned if you don't explicitly specify something else.
What exactly did you expect print(printmult(30))
to do? You've asked it to evaluate printmult(30)
, and then print
whatever results from that. Something has to result from it, right? Or were you maybe expecting some kind of exception to be raised?
Please be sure you understand that printing and returning are not the same thing.