6.4 Return values
A Python function can return nothing, one thing, or many things. That covers all possibilities!
In truth, a Python function always returns one object. Let me explain. Our simple do-nothing function from the beginning of this chapter appears to produce nothing.
def f():
pass
But if we check the type of the result, we see that it is NoneType
.
type(f())
NoneType
f() is None
True
The returned object is None
, which we
discussed in section 3.9.5. We get the same result
if we use a bare return
in f.
def f():
return
f() is None
True
Use return
to have the function pass a value back to whatever
called the function.
def g(x, y):
return x + y
g(10, 23)
33
If you forget the return
, you will get
None
.
def bad_g(x, y):
x + y
bad_g(10, 23) is None
True
It’s a common mistake for coders to...