← All lessons
Programming basics · Lesson 3 of 9

Making decisions

Programs need to make choices: show the next level only if the player won, charge postage only if the order is small. Choices are built from questions whose answer is True or False. These two values are called booleans.

Comparisons give booleans: == (is equal to; two signs, because one = stores a value), != (is not equal), <, >, <= and >=. You can join questions with and (both must be true), or (at least one) and not (flips it).

age = 15
print(age >= 13)
print(age >= 13 and age < 18)
print(age == 16)
Prints
True
True
False

if runs a block of code only when its condition is true. The block is the indented lines under it: Python uses the indentation (usually four spaces) to see where the block ends, so it matters. else catches everything else, and elif ("else if") adds more checks in between. Python tries them from the top and runs only the first one that's true.

temp = 18
if temp > 25:
    print("Hot")
elif temp > 15:
    print("Mild")
else:
    print("Cold")
Prints
Mild

Notice the colon at the end of each if, elif and else line. Forgetting it, or mixing up the indentation, is the most common first error.

Practice

What does this print?

print(7 != 7)
More info

Quick reference

True / FalseThe two boolean values (capital first letter).
== != < > <= >=Comparisons. == compares; = stores.
and / or / notBoth true / at least one true / the opposite.
if … elif … else:Runs the first block whose condition is true. Blocks are the indented lines.

The other computer science courses