Please enable JavaScript to use CodeHS

Python Tutorial

Booleans and Logical Operators in Python

Every decision a program makes comes down to True or False. Learn how booleans work, then wire conditions together with and, or, and not - just like switches on a circuit board.

python ~20 min Beginner friendly
The Big Idea

What is a boolean?

Programs are constantly making decisions: should this line of code run, or should we skip it? To decide, we use boolean expressions - conditions that evaluate to True or False.

Think of the statement "it is currently raining." Right now, that statement is either true or false - there's no in-between. Checking it tells you whether to grab an umbrella. Python stores exactly this kind of yes-or-no answer in a special type of variable called a boolean (or bool for short).

A boolean can hold the value True or the value False, and nothing else. Compare that to an integer variable, which can hold any whole number, or a string, which can hold any text. A boolean is like a light switch: it's on, or it's off.

main.py
is_raining = True

print("I need to grab my umbrella: " + str(is_raining))
Console
I need to grab my umbrella: True

Try imagining the value of is_raining flipped to False - the program would print I need to grab my umbrella: False instead. Remember, a boolean can only ever be one of two values!

Capitalization counts! In Python you must write True and False with a capital first letter and no quotes. Lowercase true is an error, and "True" in quotes is just a string of text, not a boolean.


Where Booleans Come From

Comparisons make booleans

You won't always type True or False by hand. Most of the time, a boolean is the answer to a question your program asks with a comparison operator. Every comparison produces a boolean:

OperatorQuestion it asksExampleResult
==Are these two values equal?7 == 7True
!=Are these two values different?3 != 3False
>Is the left side greater?10 > 4True
<Is the left side smaller?10 < 4False
>=Greater than or equal to?5 >= 5True
<=Less than or equal to?6 <= 5False

That means you can store the result of a comparison in a boolean variable, just like storing a number in an int:

main.py
temperature = 38

is_cold = temperature < 50   # the comparison produces a boolean

print("It is cold outside: " + str(is_cold))
Console
It is cold outside: True

The Power Tools

The logical operators: and, or, and not

One condition is often not enough. Extending our weather example: if it's raining we grab an umbrella... but what about these situations?

  • What if it is raining AND it is also cold? Both conditions are True, so we'll need a raincoat as well.
  • What if it is cold AND NOT raining? One condition is True and one is not - so we grab a sweatshirt instead.
  • What if it is sunny? We might still want the umbrella for shade! So if we have rain OR sun, we need the umbrella.

Everyday life works the same way. "You get dessert if you finish dinner and clean your room" means both things have to happen - eating dinner alone won't cut it. But "you can watch a movie if it's Friday or Saturday" only needs one of the two to be true.

Python gives us three logical operators to build these combined conditions, and they're just lowercase words:

and

Evaluates to True only if both values are True. False otherwise.

or

Evaluates to True if at least one value is True. False only when both are False.

not

Flips the value: not True is False, and not False is True. It takes the opposite.

Using them with our weather situations:

  • Raining and cold? → Raincoat
  • Cold and not raining? → Sweatshirt
  • Raining or sunny? → Umbrella

Here's the whole thing as a program. Imagine changing the three booleans at the top and predicting how the output changes:

main.py
is_raining = True
is_cold = True
is_sunny = False

raincoat = is_raining and is_cold
sweatshirt = not is_raining and is_cold
umbrella = is_raining or is_sunny

print("I need to grab my umbrella: " + str(umbrella))
print("I need to grab my raincoat: " + str(raincoat))
print("I need to grab my sweatshirt: " + str(sweatshirt))
Console
I need to grab my umbrella: True
I need to grab my raincoat: True
I need to grab my sweatshirt: False
Interactive

The logic lab

Time to see the operators in action. Below are two boolean variables wired up as switches: finished_dinner and cleaned_room. Flip them on (True) and off (False) and watch what and, or, and not produce. The dessert bulb only lights when the and row is True - both chores done!

Logic Lab

click the switches to flip True / False
finished_dinner and cleaned_room → False no dessert yet
finished_dinner or cleaned_room → True
not finished_dinner → False

a and b

abresult
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

a or b

abresult
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

not a

aresult
TrueFalse
FalseTrue

Notice: as you flip the switches, one row in each truth table lights up - that's the row your current values match. The tables are the complete rulebook: every combination of True and False, and what each operator does with it.

Expression tester

Logical operators really shine when they combine comparisons. Pick values for x and y, choose an expression, and watch Python evaluate each piece first, then combine the booleans:

Expression tester


Level Up

Combining conditions with parentheses

Boolean expressions can chain together as many conditions as your program needs. When they do, parentheses work just like in math: evaluate what's inside the parentheses first, then combine the results.

Take a and (b or c). Python first works out b or c, gets a single True or False, and then ands it with a. Reading complex expressions is a skill worth practicing - here's one worked out step by step:

main.py
a = True
b = False
c = True

# Step 1: (b or c)  ->  (False or True)  ->  True
# Step 2: a and True  ->  True and True  ->  True
result = a and (b or c)

print("a and (b or c) is: " + str(result))
Console
a and (b or c) is: True

Good to know: even without parentheses, Python has an order of operations for logic: not first, then and, then or. But adding parentheses makes your intent clear to anyone reading your code - use them!


Watch Out

Common mistakes

1. Using = when you mean ==

A single = assigns a value to a variable. A double == compares two values and produces a boolean. Writing score = 100 when you meant to check the score changes your variable instead of asking a question. If you want the boolean answer, always use score == 100.

2. Forgetting the capital letter

Python only recognizes True and False - capital T, capital F. Lowercase versions crash your program:

main.py
is_sunny = true   # lowercase t... uh oh
Console
Traceback (most recent call last):
  File "main.py", line 1, in <module>
NameError: name 'true' is not defined

3. Putting quotes around booleans

"True" with quotes is a string - just five characters of text. It is not the boolean True, and it won't behave like one in logic. Booleans never wear quotes.


Your Turn

Practice

Setting up and evaluating boolean expressions can range from very simple to rather complex. Let's do some practice so you can perfect your skills!

1

True or False?

The program below starts with four initialized booleans. Before pressing Run, read each expression and predict whether it evaluates to True or False. Hint: just like order of operations in math, evaluate what's inside the parentheses first. Then run it and see how you did!

main.py
a = True
b = False
c = True
d = False

first = a and (b or d)
second = (b or d) or c
third = (a or d) and (b or c)
fourth = not b and d
fifth = (d or not a) or not a

print("First expression: " + str(first))
print("Second expression: " + str(second))
print("Third expression: " + str(third))
print("Fourth expression: " + str(fourth))
print("Fifth expression: " + str(fifth))
Console
First expression: False
Second expression: True
Third expression: True
Fourth expression: False
Fifth expression: False
  • a and (b or d): the parentheses give False or False = False, and True and False = False.
  • (b or d) or c: False or True = True (or only needs one True, and c delivers).
  • (a or d) and (b or c): True and True = True.
  • not b and d: not False is True, but True and False = False.
  • (d or not a) or not a: not a is False, so it's (False or False) or False = False.
2

Write the Boolean Expressions

How'd you do?? Now go the other direction: turn each everyday statement into a boolean expression. You can create whatever boolean variables you need - this is a pencil-and-paper exercise, not a runnable program. The first one is done for you:

  • You drive to the ice cream shop if you have enough money, there is enough gas in the car, and you are over 16.
    ice_cream = enough_money and enough_gas and over_16
  • A duck flies south for the winter if the temperature is not warm and it has energy to do so.
  • To make pasta, you need to have white or wheat flour and fresh eggs.
  • You will go build a snowman if there is enough snow outside, the temperature is above 20F or you have a hat, and your friend will join you.
solutions.py
# 2) "not warm" flips the condition with not
flies_south = not is_warm and has_energy

# 3) either flour works, but the eggs are required
make_pasta = (white_flour or wheat_flour) and fresh_eggs

# 4) snow AND (warm enough OR a hat) AND a friend
build_snowman = enough_snow and (above_20 or have_hat) and friend_joins

Your variable names can be different - what matters is the logic. Notice how #3 and #4 need parentheses so the or gets evaluated before the and.


Check Yourself

Quick quiz

1. Which of these is a valid boolean value in Python?

2. What does (True and False) or True evaluate to?

3. You want to check whether points equals 100. Which line does that?

Keep learning Python

Booleans are the fuel that powers every decision in your programs. Next, put them to work: use them to choose between paths with conditionals, or to keep a loop running while a condition stays True.