Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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 None with is and is Not
  • Choose when None is a valid value in your code
  • Use None and its alternatives as default parameters
  • Decipher None and NoneType in your tracebacks
  • Use None and Optional in type hints

Download

Sample Code (.zip)

1015 bytes

Download

Course Slides (.pdf)

2.5 MB

Comments & Discussion

Agil C on July 30, 2020

Thanks for the video..!

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.