Functions often print
None when we pass the result of calling a function
that doesn't return anything to the
All functions that don't explicitly return a value, return
None in Python.
def example(): print('bobbyhadz.com') print(example()) # 👇️ Output # bobbyhadz.com # None
Notice that we called the print() function twice.
When we call the
example() function, the
print() function gets called with
hello world, and then we print the result of calling the
example function doesn't return anything, so it ends up implicitly
None gets printed.
If we were to return a value from the function, the value would get printed.
def example(): print('bobbyhadz.com') return 'abc' print(example()) # 👇️ Output # bobbyhadz.com # abc
We used the return statement to return a value from the function.
Now when the
example() function is called, we print the strings
abc, instead of
If you don't want to return anything from the function, remove the
call when calling the
def example(): print('hello world') example() # 👇️ Output # hello world
There is no point in printing the result of calling a function that doesn't
return anything because we're always going to print
Nonevalues in Python
The most common sources of
None values are:
sort()) that mutate the original object in place and return
Some built-in functions, such as
because they mutate the object in place.
a_list = ['z', 'a', 'b', 'c'] print(a_list.sort()) # 👉️ None print(a_list) # 👉️ ['a', 'b', 'c', 'z']
Notice that the call to the
list.sort() method printed
list.sort() method sorts a list in place and returns
Make sure to not store the result of calling methods that return
a_list = ['z', 'a', 'b', 'c'] # ⛔️ don't do this result = a_list.sort() print(result) # 👉️ None print(a_list) # 👉️ ['a', 'b', 'c', 'z']
There is a convention in Python for methods that mutate an object in place to
Another common source of
None values is having a function that returns a value
only if a condition is met.
def get_list(a): if len(a) > 3: return a # 👇️ None my_list = get_list(['a', 'b']) print(my_list) # 👉️ None
if statement in the
get_list function is only run if the passed in
argument has a length greater than
To get around this, we could return a default value if the condition is not met,
e.g. an empty string, an empty list,
0, or any other value that suits your use
def get_list(a): if len(a) > 3: return a return  # 👈️ return an empty list if condition not met # 👇️  my_list = get_list(['a', 'b']) print(my_list) # 👉️ 
Now the function is guaranteed to return a value regardless if the condition is met.
You can learn more about the related topics by checking out the following tutorials: