"None" in Python: A Variable without a Value

In Python, you can create a variable and initialize (set the initial value of) the variable to None:

logged_in_user = None

This is the equivalent of null or nil in other languages (e.g. Java, C#).

How to Check if a Variable's Value is None

There are two ways to check if a value is None. One way is to create an if statement with the condition is None:

if logged_in_user is None:
    print('A user is not logged in.')
else:
    print('A user is logged in.')

You can also change the if statement as follows:

if logged_in_user:
    print('A user is logged in.')
else:
    print('A user is not logged in.')

Note that we're changing the order of what we're comparing. This condition:

if logged_in_user:
    print('A user is logged in.')

is evaluated (performed) first, and is equivalent to this:

if logged_in_user is not None:
    print('A user is logged in.')

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.