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 is appreciated.
Here is my code:
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
print(printmult(30))
You are not returning anything in the function
printmult
, therefore when you print the result ofprintmult(30)
it will beNone
(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 likeprintSomething()
, it doesn't return anything), you should call it as:not
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 evaluateprintmult(30)
, and thenprint
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.
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:
I came from Ruby as well and it seems strange at first.
If you
print
something that has aprint
statement in it, the last thing it returns isNone
.If you just returned the values and then invoked a
print
on the function it would not outputNone
.Hope this helps :)