Booleans and conditionals
- Module
- M1.4
- Lesson
- 1 of 1
- Reading time
- 4 min
In this lesson
- Compare values with
==,!=,<,<=,>,>=, and test membership within. - Branch a program's logic with
if,elifandelse. - Combine conditions with
and,orandnot, and chain comparisons like0 <= x <= 10. - Write a short either/or value in one line with a conditional expression.
Earlier modules stored values and computed with them, but every line ran no matter what. Many CCC problems need a program to do one thing or another, depending on the input: print a different word, add a bonus, or skip a step. This lesson covers comparing values, branching on the result, and combining more than one condition.
Comparing values
A comparison operatorAn operator that compares two values and gives back a boolean, such as ==, <, or in.In the glossary compares two values and returns a boolean, True or False. Python has six of them: == for equal, != for not equal, < and <= for less than (or equal), and > and >= for greater than (or equal).
a = 7b = 10print(a == b)print(a != b)print(a < b)print(a >= b)Output
False
True
True
Falsea holds 7 and b holds 10. a == b is False, since the two numbers differ, and a != b is True for the same reason. a < b is True, and a >= b is False, since 7 is neither greater than nor equal to 10.
A common mistake is writing = where a comparison is meant. A single = is assignment, storing a value under a name. A double == is comparison, checking whether two values are equal, and does not change either one.
in is also a comparison operator. It checks whether a value shows up inside a piece of text (or another sequence you meet in a later module), and returns a boolean the same way == does.
letter = "a"vowels = "aeiou"print(letter in vowels)print("z" in vowels)Output
True
Falseletter holds "a", and "a" in vowels is True, since vowels contains that letter. "z" in vowels is False, since vowels does not contain "z".
Branching with if and else
An if statement runs a block of code only when a condition is True, and skips it otherwise. Adding else gives the program something to run instead, when the condition is False.
score = 42if score >= 50: print("pass")else: print("fail")Output
failscore holds 42. The condition score >= 50 is False, so the if block never runs, and Python runs the else block instead, printing "fail".
Only one of the two blocks ever runs for a given value of score. Indentation marks which lines belong to which block; every line indented under if or else belongs to that branch alone.
Three or more branches with elif
Some decisions need more than two outcomes. The elif keyword, short for "else if", checks another condition when the one above it was False, and can appear as many times as you need between if and an optional final else.
temp = 15if temp < 10: print("cold")elif temp < 25: print("mild")else: print("hot")Output
mildtemp holds 15. temp < 10 is False, so Python checks the elif: temp < 25 is True, so it prints "mild" and stops there. The final else never runs, since the elif above already matched. Python checks each condition in order and stops at the first one that is True, so only one branch ever runs, however many elif lines a chain has.
Combining conditions with and, or and not
A boolean operatorAn operator that combines or inverts boolean values, such as and, or, and not.In the glossary combines or inverts boolean values. and gives True only when both sides are True. or gives True when at least one side is True. not flips a single boolean the other way.
age = 13height = 140print(age >= 12 and height >= 130)print(age < 10 or height < 100)print(not age >= 18)Output
True
False
Trueage holds 13 and height holds 140. age >= 12 and height >= 130 is True, since both conditions hold. age < 10 or height < 100 is False, since neither condition holds on its own. not age >= 18 is True, since age >= 18 is False, and not flips it.
A comparison that raises an error
Python can only compare values it knows how to order. Comparing a piece of text straight from input() against a number, without converting it first, raises a TypeError.
age = input()if age < 18: print("minor")Input
15Error: TypeError
Traceback (most recent call last):
File "compare_raw_input.py", line 2, in <module>
if age < 18:
TypeError: '<' not supported between instances of 'str' and 'int'age holds the text input() returned, never converted with int(). Python cannot decide whether a piece of text is less than the number 18, so it stops with a TypeError instead of guessing. The fix is the one earlier modules already covered: convert with int() before comparing a value read from input.
Conditional expressions
A conditional expressionA one-line either/or expression of the form a if condition else b, which evaluates to a or b depending on the condition.In the glossary picks one of two values in a single line, without a full if block. It reads as a if condition else b: a when the condition is True, b when it is False.
count = 7label = "odd" if count % 2 == 1 else "even"print(label)Output
oddcount % 2 is 1 for the odd number 7, so count % 2 == 1 is True and the expression picks "odd". Reach for a conditional expression when you need a single either/or value. A decision with more than two outcomes, or one that runs more than one line, still needs a full if/elif/else block.
Chaining comparisons
Python also lets you chain comparisons in one expression, without writing and yourself.
age = 13print(0 <= age <= 130)print(0 <= age <= 10)Output
True
Falseage holds 13. 0 <= age <= 130 is True exactly when both 0 <= age and age <= 130 hold, which they do here. 0 <= age <= 10 is False, since age is not less than or equal to 10. A chained comparison reads the same way you would say the bound aloud. Reach for one whenever a problem asks whether a value sits between two limits, instead of writing the same check with and by hand.
Tracing an if/elif/else chain
(nothing printed yet)- Just changed
Figure 1Reading a score and choosing one of three letter grades
Read the steps as text
The program reads a score, then an if/elif/else chain assigns a letter grade, taking a different branch for each preset.
A high score
- Python starts at the top of the file. Line 1 runs first.
- Line 1 runs:
scoreis created with the value95. - Line 2 checks the condition: it is true, so line 3 runs next.
score >= 90is checked first. When it isTrue, theifbranch runs and neitherelifnorelseis checked at all. - Line 3 runs:
gradeis created with the value'A'. - Line 8 runs: it prints
A. The program has finished: no lines are left to run.
A middle score
- Python starts at the top of the file. Line 1 runs first.
- Line 1 runs:
scoreis created with the value75. - Line 2 checks the condition: it is false, so line 4 runs next.
score >= 90is checked first. When it isTrue, theifbranch runs and neitherelifnorelseis checked at all. - Line 4 checks the condition: it is true, so line 5 runs next. This
elifonly runs when theifabove wasFalse. It is true for scores from70to89. - Line 5 runs:
gradeis created with the value'B'. - Line 8 runs: it prints
B. The program has finished: no lines are left to run.
A low score
- Python starts at the top of the file. Line 1 runs first.
- Line 1 runs:
scoreis created with the value50. - Line 2 checks the condition: it is false, so line 4 runs next.
score >= 90is checked first. When it isTrue, theifbranch runs and neitherelifnorelseis checked at all. - Line 4 checks the condition: it is false, so line 7 runs next. This
elifonly runs when theifabove wasFalse. It is true for scores from70to89. - Line 7 runs:
gradeis created with the value'C'.elsecatches whatever theifandelifabove missed, here any score below70. - Line 8 runs: it prints
C. The program has finished: no lines are left to run.
All three presets read one score from standard input and run the exact same if/elif/else chain of code, but each one still takes a different branch depending on what it read. A score of 95 matches the if. A score of 75 skips the if and matches the elif. A score of 50 matches neither, so it falls through to else. Watch how grade gets its value from only one of the three assignments, whichever branch the score in that preset lands in.
Recap
This lesson covered the six comparison operators and in, branching with if, elif and else, and combining or chaining conditions with and, or, not and chained comparisons. It also covered picking a single either/or value with a conditional expression. The four problems below all turn a small set of numbers into a decision.
Practice
Try these on the judges. Each link opens the problem on WMOJ or DMOJ.
- 2021 J1Boiling Water (opens on WMOJ in a new tab) WMOJ
Turn a boiling point into an atmospheric pressure and a three-way elevation reading.
- 2023 J1Deliv-e-droid (opens on WMOJ in a new tab) WMOJ
Score a delivery robot's run from its package count and its collisions, with a bonus condition.
- 2026 J1Concert Tickets (opens on WMOJ in a new tab) WMOJ
Decide whether a concert-goer can buy their tickets from the remaining supply.
- 2017 J1Quadrant Selection (opens on DMOJ in a new tab) DMOJ
Decide which quadrant a point falls in from the signs of its coordinates.
Why DMOJ: Tries the same kind of decision on DMOJ, which holds 2014 to 2020.