What is the purpose of the return statement?

后端 未结 13 2516
难免孤独
难免孤独 2020-11-21 06:28

What is the simple basic explanation of what the return statement is, how to use it in Python?

And what is the difference between it and the print state

13条回答
  •  攒了一身酷
    2020-11-21 06:55

    In python, we start defining a function with "def" and generally, but not necessarily, end the function with "return".

    A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2

    Now, the code of this function will be:

    def A_function (x):
        return x + 2
    

    After defining the function, you can use that for any variable and get result. Such as:

    print A_function (2)
    >>> 4
    

    We could just write the code slightly differently, such as:

    def A_function (x):
        y = x + 2
        return y
    print A_function (2)
    

    That would also give "4".

    Now, we can even use this code:

    def A_function (x):
        x = x + 2
        return x
    print A_function (2)
    

    That would also give 4. See, that the "x" beside return actually means (x+2), not x of "A_function(x)".

    I guess from this simple example, you would understand the meaning of return command.

提交回复
热议问题