Skip to content

Making Decisions: if / elif / else

Programming Python Difficulty 1/5

Beginning of the lesson

Making Decisions: if / elif / else

Teach your Python program to choose different paths

Big Idea: Real programs need to make decisions. "If it is raining, take an umbrella. Otherwise, wear sunglasses." In Python we make decisions with if, elif, and else. The program checks a condition (something that is either True or False) and runs different code depending on the answer.
By the end you will be able to:
  • compare values with ==, !=, <, >, <=, >=,
  • run code only when a condition is True using if,
  • give a backup path with else and extra paths with elif,
  • combine conditions with and, or, and not.

1. Comparing values: True or False

A comparison asks a yes/no question about two values. Python answers with a boolean value: either True or False (note the capital letters).

OperatorMeansExampleResult
==is equal to5 == 5True
!=is not equal to5 != 3True
>is greater than5 > 8False
<is less than5 < 8True
>=greater than or equal5 >= 5True
<=less than or equal9 <= 5False

Let's try it in real code:

age = 20
print(age >= 18)
print(age == 18)
print(age != 18)

Output:

True
False
True
Watch out: one = assigns a value (age = 20). Two == compares (age == 20). They are not the same!

2. The if statement

An if statement runs a block of code only when its condition is True. Two things are very important:

  • The if line ends with a colon :
  • The code to run is indented (moved to the right, usually 4 spaces). The indented lines are "inside" the if.
age = 20
if age >= 18:
    print("You can vote!")
print("Program finished")

Output:

You can vote!
Program finished

Because age >= 18 is True, the indented line runs. The last line is not indented, so it always runs. If age were 10, the first message would be skipped and only "Program finished" would appear.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers