Python's None: Null in Python (Overview)
None is a powerful tool in the Python toolbox. Like True and False, None is an immutable keyword. As the null in Python, you use it to mark missing values and results, and even default parameters where it’s a much better choice than mutable types.
Now you can:
- Test for
Nonewithisandis Not - Choose when
Noneis a valid value in your code - Use
Noneand its alternatives as default parameters - Decipher
NoneandNoneTypein your tracebacks - Use
NoneandOptionalin type hints
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
Comments & Discussion
Sam W on Aug. 2, 2020
This was all very helpful. So thank you.
But it has confused me about something I had thought I understood.
I use if var: a lot to test if data exists. And I’m usually basing that on a returned function.
e.g.
def main(input):
test = test_func(input)
if test:
do_something()
else:
do_something_else()
def test_func(input):
if input == something:
return something
Is it wrong of me, then, to use this Truthy/Falsey if test: approach? My test_func is returning None if the condition is not met, and so I want my main func to do_something_else().
To ensure this, would I be better writing if test is not None: instead?
Bartosz Zaczyński RP Team on Aug. 3, 2020
Using explicit comparison is more Pythonic because it clearly states your intent. That’s one of the core philosophies you’ll find in the Zen of Python.
More importantly, however, relying on implicit truthy/falsy values is risky because it may not work as expected, depending on what your functions return. For example, if zero (0) should be considered a success, which often is in Unix programs, then your condition won’t work, because zero evaluates to false in a Boolean context.
As a rule of thumb, use explicit comparison whenever possible.
Bartosz Zaczyński RP Team on Aug. 3, 2020
By the way, it’s also worth noting to avoid double negation in expressions like this:
if test is not None:
success()
else:
failure()
You can swap the order to make it a little easier on the eyes:
if test is None:
failure()
else:
success()
Become a Member to join the conversation.

Agil C on July 30, 2020
Thanks for the video..!