Booleans
Let's focus on a new data type: the boolean.
A boolean is a data type with only two possible values: True or False.
Syntax
The boolean values True or False in Python are written with a capital letter as the first letter and you don't need to put quotes around them.
In python, we use the below comparison operators.
When you use a comparison operator, Python will return a boolean, the result of the comparison is either True or False.
Example
One = vs Two ==
The = sign is used when you assign a value to a variable.
The == sign is used when you want to compare two values.
AND, OR, NOT
-
Use the AND keyword when you want to test if two conditions are true.
-
Use the OR keyword when you want to test if at least one of the two conditions is true.
-
Use the NOT keyword when you want to test if the opposite of your condition is true
Example
>>> a = 3
>>> b = 6
>>> a < b and a > 0
True
>>> a > b and a > 0
False
>>> a > b and a < 0
False
>>> a < b and a < 0
False
>>>
When using the AND keyword, it will return True only if both conditions are True.
Exercise
Try to guess each time if the condition will be True or False. You can check your answers in the Answer tab.
- 1 == 1
- "hello" == "bye"
- 2 != 8
- 3 > 8 and 2 > 3
- 2 < 5 or 5 > 10
- "hello" != "world" and 3 >= 2
- not 3 > 5
- not (2 == 2 and 3 != 4)
- 2 >= 2 or (5 < 4 and 3 > 1)
- True
- False
- True
- False
- True
- True
- True
- False
- True