What is the purpose of the return statement?

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

    Just to add to @Nathan Hughes's excellent answer:

    The return statement can be used as a kind of control flow. By putting one (or more) return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

    Here's an example:

    >>> def make_3_characters_long(some_string):
    ...     if len(some_string) == 3:
    ...         return False
    ...     if str(some_string) != some_string:
    ...         return "Not a string!"
    ...     if len(some_string) < 3:
    ...         return ''.join(some_string,'x')[:,3]
    ...     return some_string[:,3]
    ... 
    >>> threechars = make_3_characters_long('xyz')    
    >>> if threechars:
    ...     print threechars
    ... else:
    ...     print "threechars is already 3 characters long!"
    ... 
    threechars is already 3 characters long!
    

    See the Code Style section of the Python Guide for more advice on this way of using return.

提交回复
热议问题