Function returns None without return statement

后端 未结 7 1823
北荒
北荒 2020-11-21 06:19

I just learned (am learning) how function parameters work in Python, and I started experimenting with it for no apparent reason, when this:

def jiskya(x, y):
         


        
相关标签:
7条回答
  • 2020-11-21 06:56

    Ok, to start off when you do this:

    print(jiskya(2, 3))
    

    You getting something pretty much equivalent to this:

    print(print(2))
    

    So, what is going on? The print(2) is printing out 2, and returns None which is printed by the outer call. Straightforward enough.

    Now look at this:

    def hello():
        return 2
    

    If you do:

    print(hello())
    

    You get 2 because if you print out a function you get whatever the return value is. (The return value is denoted by the return someVariable.

    Now even though print doesn't have parenthesis like most functions, it is a function just a little special in that respect. What does print return? Nothing. So when you print print someVariable, you will get None as the second part because the return value of print is None.

    So as others have stated:

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

    Should be re-written:

    def jiskya(x, y):
        if x > y:
            return y
        else:
            return x
    
    0 讨论(0)
提交回复
热议问题