Python Function Returning None

2019-01-02 18:38发布

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))

4条回答
后来的你喜欢了谁
2楼-- · 2019-01-02 19:33

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))
查看更多
笑指拈花
3楼-- · 2019-01-02 19:33

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.

查看更多
笑指拈花
4楼-- · 2019-01-02 19:35

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))
查看更多
临风纵饮
5楼-- · 2019-01-02 19:37

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 :)

查看更多
登录 后发表回答