Python for AIPython for AI
Data Types

Booleans

True and False values for decisions

Today, we're going to dive into booleans, a fundamental data type in Python that helps your programs make decisions.

What are booleans?

Booleans are a data type that can only have two values: True or False. They are named after George Boole, a mathematician who created boolean algebra. Think of them as yes or no answers in your code.

These simple values are super important. They are the building blocks for logic and control flow, which means making your program do different things based on conditions.

Creating booleans

You can directly assign True or False to a variable. Remember to capitalize the first letter; true or false (lowercase) are not recognized in Python.

python
is_sunny = True
has_umbrella = False

print(is_sunny)
print(has_umbrella)
Boolean values True and False are distinct. They are not the same as the strings "True" or "False".

Comparison operators

Most often, booleans are the result of comparisons. You compare two values, and Python tells you if the comparison is True or False. These are called comparison operators.

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to
python
x = 10
y = 5

print(x == y)  # Is 10 equal to 5? (False)
print(x > y)   # Is 10 greater than 5? (True)
print(x != y)  # Is 10 not equal to 5? (True)

age = 18
can_vote = (age >= 18)
print(can_vote) # Is age greater than or equal to 18? (True)

Common mistakes

  • Forgetting to capitalize True and False. Python is case-sensitive!
  • Using a single equals sign (=) for comparison instead of a double equals (==). The single equals is for assignment; the double equals is for checking equality.
python
# Common Mistake 1: Incorrect capitalization
# my_boolean = true # This would cause an error!

# Common Mistake 2: Single equals instead of double
# if x = 5: # This would try to assign, not compare!
#    print("x is 5")

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
What does `True and False` evaluate to?
Quiz
Not started
What does `not (5 > 3)` evaluate to?

What's next?

Booleans are crucial for controlling the flow of your program. Next, you'll learn about conditional statements like if and else. These statements use boolean values to decide which code blocks to run.

Understanding booleans well sets you up for writing programs that can truly make smart decisions!