To start this guide, download this zip file.
None
Consider this function called best_animal()
:
def best_animal() -> str:
response = input('What do you think is the best animal? ')
return response
if __name__ == '__main__':
animal = best_animal()
If a person enters ‘giraffe’ at the prompt, then response → 'giraffe'
, and
after the function returns animal → 'giraffe'
.
However, what happens if you leave off the return
statement?
def best_animal():
response = input('What do you think is the best animal? ')
if __name__ == '__main__':
animal = best_animal()
In this case, the best_animal()
function returns None
! So then
animal → None
.
Using None
Having a value that represents None
, or nothing, can be really useful. For
example, look at this revised best_animal()
function:
def best_animal() -> str | None:
response = input('What do you think is the best animal? ')
if response == '':
return None
return response
if __name__ == '__main__':
animal = best_animal()
if animal is None:
print("You don't have a favorite animal? 😔")
else:
print(f"Your favorite animal is a {animal}? Cool!")
You can find this code in best_animals.py
in the zip file above. Walk through
this program with the debugger to see what happens in these cases:
-
If you enter ‘giraffe’, then:
- The variable
response → 'giraffe'
. - Since this is not equal to an empty string, then
best_animal()
returns ‘giraffe’. - This sets the variable
animal → 'giraffe'
. - Since
animal
is notNone
, the program prints “Your favorite animal is a giraffe? Cool!”
- The variable
-
If you enter nothing, by just pressing the
Enter
key, then:- The variable
response → ''
. - Since
response
is equal to the empty string, thenbest_animal()
returnsNone
. - This sets the variable
animal → None
. - Since
animal
isNone
, the program prints “You don’t have a favorite animal? 😔”
- The variable
You can check if a variable is None
using is None
:
if animal is None:
# do something
Likewise, you can check if a variable is not None using
is not None`:
if animal is not None:
# do something