Booleans

Built-in Python data type: True and False

We will cover this section in more detail, likely after the quiz. The lecture notebook and outputs are kept here for your reference, but we will cover it later.

Naturally, we will want to compare values in our code.

# is age at least age_limit?
age_limit = 21
age = 17
# is password_guess equal to true_password?
# note: do not do this---weak security!
true_password = 'qwerty1093x!'
password_guess = 'QWERTY1093x!'

Enter the Boolean data type, or bool, which only has two values: True and False.

Read Inferential Thinking

Read Ch 4.3, which discusses Boolean values and comparison operators.

Comparison Operators

Boolean values most often arise from comparison operators.

3 > 1 + 1
True
3 < -1 * 2
False
1 < 1 + 1 < 3
True
s = "Data " + "6"
s == "Data 6"
True

Note in the last example, the = sign is an assignment operator whereas the == sign is an comparison operator that checks for equality.

For a full list of comparison operators, see the above Inferential Thinking textbook chapter.

Truthy Values

In Python we can cast any value to bool.

Falsy value: Values that evaluate to False when converted to bool:

  • False
  • '' (the empty string)
  • 0
  • 0.0
  • None

Generally things that are empty (empty lists, sets, dictionaries, etc).

Truthy value: Everything else. Evaluates to True when converted to bool.

Think philosophically: if a value is something, then it exists and therefore it is True. If it is nothing, then it is False.

Booleans in Data Science

In data science, boolean values can be used represent a binary variable:

  • yes/no
  • on/off
  • high/low
  • etc.

The datascience package automatically casts booleans into integers: * True is equivalent to 1. * False is equivalent to 0.

Exercises

Here are some WWPD (What Would Python Do?) exercises for you to read through and understand. For each value in each expression, think carefully about its data type.

17 == '17'
False
'zebra' != True
True
True == 1.0
True
banana = 10
'apple' >= banana
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 2
      1 banana = 10
----> 2 'apple' >= banana

TypeError: '>=' not supported between instances of 'str' and 'int'
'alpha' >= 5 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[11], line 1
----> 1 'alpha' >= 5 

TypeError: '>=' not supported between instances of 'str' and 'int'
5 > True
True