Boolean and None types; Logical expressions#

Boolean and None types#

So far we have seen the str, int, and float types in python. There are two more “simple” types, namely the bool type and the None type.

The boolean (bool) type consists of two symbols: True and False:

True
True
False
False

While the None type consists of a single special symbol None, which is sometimes used in data science to represent missing values (note that Jupyter notebook do not display None’s):

None

Simple logical expression#

The most common way to produce a bool type is via logical (or boolean) expressions. For example, let’s say you want to check whether a variable named x is equal to zero, you do:

# assign the value of x to 2
x = 2

# CHECK if x is EQUAL TO zero
x == 0
False

(Note that we have two equal sign juxtapose with each other to represent the concept of “equal to”)

For numerical values, we have the following comparison operators:

  • == for equality

  • != for _in_equality

  • > for bigger than

  • < for less than

  • >= for bigger than or equal to

  • <= for less than or equal to

For example:

# assign the values of x, y, and z
x = 2
y = 2
z = 3
x > y
False
x >= y
True
x != z
True

For strings, we can do == and != comparisons just like numerical values. In addition, a useful comparison operator is in, where x in y checks whether the string y contains x as a substring.

# define two string variables
word = "apple"
sentence = "this is an apple"
# the two strings are not equal
word == sentence
False
# But the sentence contains the word
word in sentence
True
# The negation of `in` is `not in`
word not in sentence
False

Compound logical statements#

We can join more than one boolean expressions together using the logical operators and and or, and we can negate a logical statement using not. For example, suppose we want to check if \(1 < x < 3\):

# define a value for x
x = 2
# check the pair of inequality using `and`
1 < x and x < 3
True

Note that or means “non-exclusive or” here. Example:

1 < x or x < 3
True
x >= 5 or x <= 2
True

For an example of not, consider De Morgan’s Laws:

# assign the values of x, y, and z
x = 2
y = 2
z = 3
# "or" of two negations
x != y or x != z
True
# negation of "and". Should be equivalent to above
not (x == y and x == z)
True

Checking if a value is None#

There is a special rule for checking if a value is None. Instead of x == None, you should use x is None:

x = 5
x is None
False

The negation of is is is not:

x is not None
True