1. Booleans - the logical data type
Booleans are helpful both as a data type and a context for evaluation.
2. Booleans as a data type
As a data type, booleans only have two values, true and false, and those two values work like an on-off switch and are complete opposites of each other. Be careful if you come from other languages or switch between multiple languages because these values are capitalized in Python. They are often used for conditionals, as shown in this example where I'm setting a value equal to true, then checking if it is truthful by using an if statement, and finally printing a line about going to get more.
3. Truthy and Falsey
In addition to boolean values True and False, all values can be truthy or falsey when you view them in a boolean evaluation context such as an if statement. Truthy values are ones that will return true in an boolean evaluation falsey values will evaluate to false. For example, if we have the variable apples set to two, and we use it in an if statement it will act as it if were true. That makes the integer two a truthy value. If apples is 0 it will evaluate to False and thus is falsey.
4. Truthy and Falsey
Let's explore some truthy and falsey values. Any non-zero numeric type is truthy, and zero is falsey. Any non-empty string is truthy, while empty ones are falsey. That same logic applies to lists and dictionaries as well. Also, None is falsey. In general, something is truthy if it's not empty of value.
5. Operators - a boolean evaluation context
We'll often use a python operator as a boolean evaluation context. For example, the cookie_qty == 3, which when evaluated, returns a boolean data type of True or False depending on the value of cookie_qty. In addition to the equality comparison you see here, Python provides operators for not equal to, less than, less than or equal to, greater than, and greater than or equal to.
6. Floats are approximately an issue
Remember when I was talking about floats, and I said they were suitable for approximations? Equality comparisons are an area where using floats can throw you off, as floating points are stored internally in a less precise way than we expect. For example, if we add 0-point-1 and 1-point-1, that should give us 1-point-2. Well, when we evaluate it, that turns out to be false. If we print the value, we see that it's stored slightly off what we expected. There are ways to handle this with rounding and absolute values, but we'll leave those to math class.
7. Let's practice!
Time for you to go be the investigator and determine what is true and what is not.