Returning values from functions

suggest change

Functions can return a value that you can use directly:

def give_me_five():
    return 5

print(give_me_five())  # Print the returned value
# Out: 5

or save the value for later use:

num = give_me_five()
print(num)             # Print the saved returned value
# Out: 5

or use the value for any operations:

print(give_me_five() + 10)
# Out: 15

If return is encountered in the function the function will be exited immediately and subsequent operations will not be evaluated:

def give_me_another_five():
    return 5
    print('This statement will not be printed. Ever.')

print(give_me_another_five())
# Out: 5

You can also return multiple values (in the form of a tuple):

def give_me_two_fives():
    return 5, 5  # Returns two 5

first, second = give_me_two_fives()
print(first)
# Out: 5
print(second)
# Out: 5

A function with no return statement implicitly returns None. Similarly a function with a return statement, but no return value or variable returns None.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Functions:
* Returning values from functions

Table Of Contents
2 Filter
3 List
4 Functions
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve