Function returns None without return statement

后端 未结 7 1842
北荒
北荒 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:38

    Where did the 'None' come from?

    The function.

    And what is it?

    It's what the function returned.

    In Python, every function returns something. It could "be multiple things" using a tuple, or it could "be nothing" using None, but it must return something. This is how we deal with the fact that there is no way to specify a return type (which would make no sense since you don't specify types for anything else). When interpreted as a string for printing, None is replaced with the string "None".

    None is a special object that is supposed to represent the absence of any real thing. Its type is NoneType (it is an instance of that class). Whenever you don't explicitly return anything, you implicitly return None.

    You wrote the function to print one of the two values x or y, but not to return anything. So None was returned. Then you asked Python to print the result of calling the function. So it called the function (printing one of the values), then printed the return value, which was None, as the text "None".

提交回复
热议问题