Skip to content

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.

comparison operators

When you use a comparison operator, Python will return a boolean, the result of the comparison is either True or False.

Example

📋 Interpreter
>>> 5 == 5
True
>>> 5 == 6
False
>>> a = 0
>>> a > 8
False
>>> a != 3
True
>>> a < 15
True
>>>

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

📋 Interpreter
>>> 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.

📋 Interpreter
>>> a = 3
>>> b = 6
>>> a < b or a > 0
True
>>> a > b or a > 0
True
>>> a > b or a < 0
False   
>>> a < b or a < 0
True
>>> 

When using the OR keyword, it will return True if one or both conditions are True.

📋 Interpreter
>>> a = 3
>>> b = 6
>>> not a < b
False
>>> not b < a
True
>>> 

When using the NOT keyword, it will return True if the condition is False and False if the condition is 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 == 1
  2. "hello" == "bye"
  3. 2 != 8
  4. 3 > 8 and 2 > 3
  5. 2 < 5 or 5 > 10
  6. "hello" != "world" and 3 >= 2
  7. not 3 > 5
  8. not (2 == 2 and 3 != 4)
  9. 2 >= 2 or (5 < 4 and 3 > 1)
  1. True
  2. False
  3. True
  4. False
  5. True
  6. True
  7. True
  8. False
  9. True