What is the purpose of the return statement?

后端 未结 13 2748
难免孤独
难免孤独 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:49

    return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.

    print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.

    The following code shows how to use return and print properly:

    def fact(x):
        if x < 2:
            return 1
        return x * fact(x - 1)
    
    print(fact(5))
    

    This explanation is true for all of the programming languages not just python.

提交回复
热议问题