What Did We Learn This Week? Boolean Edition
- A boolean is a type of variable in Python that stores either a yes or no (True or False)
- We would use a boolean to tell the computer different logical statements
- A boolean is set by the keywords (True) and (False)
- A Boolean is a variable that can hold either a True value or a False value
In the example here, booleans sky_blue and tree_red have been defined to tell the computer that the sky is blue, and that a tree is not red. Once the booleans are defined, the computer remembers that sky_blue is true, and that tree_red is false.
- Unlike ints and strings, it can be hard to understand when a boolean should be used. When would your computer program need to know if the sky is blue? That trees are green, not red?
- In daily life, you use booleans all the time without realizing it. The game of twenty questions is all about booleans, and even your light switch is a boolean. It is either True, and the light is on, or it is False, and the light is off.
- In computer programming, booleans are often used in comparisons to see if two numbers (or strings) are the same. They also have some other uses that we will cover next week.
- Note that in the ≤ and the ≥ expressions, the = always comes after the >/<.
- Comparisons are used to compare to values. They can check if they are the same or different, or for numbers they can see if one is greater than the other. You can even use comparisons to see if two booleans have the same value!
- With booleans, there are several special types of comparisons called logical statements. Instead of just comparing if both booleans are the same, for instance, you can ask the computer if both booleans are True, or if at least one of them are True.
- AND Statements compare two booleans, and return True if both are True.
- OR Statements compare two booleans, and if at least one is True, return True
- NOT can be added in front of any boolean, and reverses the value of the boolean. They can be used in conjunction with any logical statement as well.
Booleans are one of the most difficult concepts that you have learned so far. We recommend taking a while to play around with logical statements and comparisons in a Repl.it session so you get the feel for them. It might seem like a lot of new concepts at first, but the more you practice the more you will understand the logic of booleans.