Skip to content
CCC Python Course

Booleans and conditionals

Module
M1.4
Lesson
1 of 1
Reading time
4 min

In this lesson

  • Compare values with ==, !=, <, <=, >, >=, and test membership with in.
  • Branch a program's logic with if, elif and else.
  • Combine conditions with and, or and not, and chain comparisons like 0 <= 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).

examples/compare_scores.py
a = 7b = 10print(a == b)print(a != b)print(a < b)print(a >= b)

Output

False
True
True
False
Six comparison operators on two numbers

a 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.

examples/letter_in_vowels.py
letter = "a"vowels = "aeiou"print(letter in vowels)print("z" in vowels)

Output

True
False
Testing membership with in

letter 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.

examples/pass_fail.py
score = 42if score >= 50:    print("pass")else:    print("fail")

Output

fail
A two-way branch with if and else

score 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.

examples/temperature_band.py
temp = 15if temp < 10:    print("cold")elif temp < 25:    print("mild")else:    print("hot")

Output

mild
Three outcomes with if, elif and else

temp 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.

examples/age_and_height.py
age = 13height = 140print(age >= 12 and height >= 130)print(age < 10 or height < 100)print(not age >= 18)

Output

True
False
True
and, or and not combining conditions

age 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.

examples/compare_raw_input.py
age = input()if age < 18:    print("minor")

Input

15

Error: 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'
Comparing text against a number without converting it first

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.

examples/parity_label.py
count = 7label = "odd" if count % 2 == 1 else "even"print(label)

Output

odd
Picking one of two values with a conditional expression

count % 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.

examples/age_in_range.py
age = 13print(0 <= age <= 130)print(0 <= age <= 10)

Output

True
False
Chaining two comparisons into one bounds check

age 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

Input
1score = int(input())
2if score >= 90:
3 grade = "A"
4elif score >= 70:
5 grade = "B"
6else:
7 grade = "C"
8print(grade)
Output so far
(nothing printed yet)
Frames and objects, step 1 of 5FramesGlobal frame
Speed
Python starts at the top of the file. Line 1 runs first.
  • 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

  1. Python starts at the top of the file. Line 1 runs first.
  2. Line 1 runs: score is created with the value 95.
  3. Line 2 checks the condition: it is true, so line 3 runs next. score >= 90 is checked first. When it is True, the if branch runs and neither elif nor else is checked at all.
  4. Line 3 runs: grade is created with the value 'A'.
  5. Line 8 runs: it prints A. The program has finished: no lines are left to run.

A middle score

  1. Python starts at the top of the file. Line 1 runs first.
  2. Line 1 runs: score is created with the value 75.
  3. Line 2 checks the condition: it is false, so line 4 runs next. score >= 90 is checked first. When it is True, the if branch runs and neither elif nor else is checked at all.
  4. Line 4 checks the condition: it is true, so line 5 runs next. This elif only runs when the if above was False. It is true for scores from 70 to 89.
  5. Line 5 runs: grade is created with the value 'B'.
  6. Line 8 runs: it prints B. The program has finished: no lines are left to run.

A low score

  1. Python starts at the top of the file. Line 1 runs first.
  2. Line 1 runs: score is created with the value 50.
  3. Line 2 checks the condition: it is false, so line 4 runs next. score >= 90 is checked first. When it is True, the if branch runs and neither elif nor else is checked at all.
  4. Line 4 checks the condition: it is false, so line 7 runs next. This elif only runs when the if above was False. It is true for scores from 70 to 89.
  5. Line 7 runs: grade is created with the value 'C'. else catches whatever the if and elif above missed, here any score below 70.
  6. 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.

  1. 2021 J1
    Boiling Water (opens on WMOJ in a new tab) WMOJ

    Turn a boiling point into an atmospheric pressure and a three-way elevation reading.

  2. 2023 J1
    Deliv-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.

  3. 2026 J1
    Concert Tickets (opens on WMOJ in a new tab) WMOJ

    Decide whether a concert-goer can buy their tickets from the remaining supply.

  4. 2017 J1
    Quadrant 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.