Booleans

Booleans (or bools) represent one of two values: True or False. You can use Python’s comparison operators to compare two numbers:

  • > Greater than
  • < Less than
  • >= Greater than or equal to
  • <= Less than or equal to
  • == Equal to
  • != Not equal to

Example using “greater than” operator:

print(43 > 21)

Output:

True

Example using “equals to” operator:

print(43 == 21)

Output:

False

In the order of operations, arithmetic operators are evaluated before comparison operators:

print(78 <= 3 * 26)

Output:

True

Booleans can be combined or negated using logical operators:

  • and
  • or
  • not
(0 == 1) or (53 > 20)

Output:

True
(67 > 3) and (34 != 34)

Output:

False

Boolean values can be assigned to variables just like numbers and strings:

b = (54 < 22)
c = not b
print(c)

Output:

True

Exercises

  1. Write a single line of code to determine if 241 times 4.5 is greater than or equal to 3281 divided by 3.

    Hint: use a comparison operator.

  2. The variable red_led is being used as a bool to control the red light on a circuit board. If it’s set to True then then light will be on. If it’s set to False then the light will be off. Write a single line of code to flip the state of the light (i.e., if it’s on, turn it off; if it’s off, turn it on).

    Hint: use a logical operator, not an if/else block.

Thanks! We hope you found what you are looking for. Please feel free to contribute via Github.