Lesson 24 +10 XP

Booleans

Booleans

Booleans represent one of two values: True or False. They drive decisions in if statements.

Compare values

A comparison produces a boolean:

print(10 > 9)    # True
print(10 == 9)   # False
print(10 < 9)    # False

Booleans in if statements

a = 200
b = 33
if b > a:
    print("b is greater than a")
else:
    print("b is not greater than a")

Evaluate values and variables

The bool() function asks Python: is this value True or False?

print(bool("Hello"))  # True
print(bool(15))       # True

Almost everything is True

Only a few values are False:

  • False
  • None
  • 0 and 0.0
  • empty strings ""
  • empty collections: [], (), {}, set()
  • the empty range range(0)

Everything else is True.

Check it

print(bool([]))    # False
print(bool(""))    # False
print(bool(0))     # False
print(bool("abc")) # True

Functions can return booleans

def is_adult(age):
    return age >= 18

print(is_adult(20))  # True

isinstance

isinstance() checks a value's type and returns a boolean:

x = 200
print(isinstance(x, int))  # True

TL;DR

  • Booleans are True or False, produced by comparisons.
  • bool(value) tests truthiness.
  • Only False, None, 0, and empty collections are falsy.
  • isinstance(x, type) checks types.