Last updated: Apr 8, 2024
Reading timeยท3 min
Functions often print None
when we pass the result of calling a function
that doesn't return anything to the print()
function.
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.
The example
function doesn't return anything, so it ends up implicitly
returning None
, so 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
bobbyhadz.com
and abc
, instead of None
.
None
.If you don't want to return anything from the function, remove the print()
call when calling the example()
function.
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 None
.
None
values in PythonThe most common sources of None
values are:
None
implicitly).None
.sort()
) that mutate the original object in place and return None
.Some built-in functions, such as sort()
, append()
, extend()
return None
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 None
.
The list.sort()
method sorts a list in place and returns None
.
Make sure to not store the result of calling methods that return None
in
variables.
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
return None
.
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
The if
statement in the get_list
function is only run if the passed in
argument has a length greater than 3
.
None
.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
case.
def get_list(a): if len(a) > 3: return a return [] # ๐๏ธ Return an empty list if the condition is not met # ๐๏ธ [] my_list = get_list(['a', 'b']) print(my_list) # ๐๏ธ []
Now the function is guaranteed to return a value regardless of whether the condition is met.
You can learn more about the related topics by checking out the following tutorials: