BeginnerLesson firstCategory 12 of 20

Boolean Logic

Work with True/False values and logical operators. Read the lesson first, then move through the exercises in order.

4 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Compound Conditions

Study Material

Read the full lesson

The language of True and False

At its absolute core, a computer only understands two concepts: On and Off, 1 and 0, True and False.

In Python, this is represented by the Boolean data type, which has only two possible values: True and False. (Note the capital letters!).

Comparison Operators

You usually generate Booleans by comparing things.

  • == means "is equal to"
  • != means "is not equal to"
  • > means "is greater than"
  • < means "is less than"
  • >= means "is greater than or equal to"
  • <= means "is less than or equal to"
python
print(5 > 3) # Output: True print(10 == 2) # Output: False print("cat" == "dog") # Output: False

💡 Warning: Be careful not to mix up = (assignment) with == (comparison). One = puts a value into a variable. Two == asks a question: "Are these equal?"

Logical Operators

Sometimes you need to combine multiple questions. Python uses plain English words for this: and, or, and not.

The and operator

Both sides must be True.

python
is_weekend = True is_sunny = True print(is_weekend and is_sunny) # Output: True

The or operator

Only one side needs to be True.

python
has_cash = False has_credit_card = True print(has_cash or has_credit_card) # Output: True

The not operator

Flips the Boolean to its opposite.

python
is_raining = True print(not is_raining) # Output: False

What this lesson should give you

After this lesson, you should understand how to:

  • identify the two boolean values True and False
  • use comparison operators (>, <, ==, !=)
  • combine conditions using and and or
  • flip logic using not

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.