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
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
.