What is the purpose of the return statement?

后端 未结 13 2522
难免孤独
难免孤独 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 07:14

    Here is my understanding. (hope it will help someone and it's correct).

    def count_number_of(x):
        count = 0
        for item in x:
            if item == "what_you_look_for":
            count = count + 1
        return count
    

    So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0. If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change. I hope I got it right. Oh, and return is always inside a function.

提交回复
热议问题