Kodokon kodokon.com

Conditions: if, elif, else

You learn to make your programs take decisions with if, elif, else, and logical operators.

8 min · 3 questions

Open this lesson in Kodokon

A program often has to choose between several paths. The if keyword runs a block of instructions only if a condition is true. A condition is an expression that evaluates to True or False. The if line ends with a colon :, and the block that follows is indented by 4 spaces: this indentation tells Python which lines belong to the block.

PYTHON
age = 20
if age >= 18:
    print("You are an adult.")
The message is displayed only if the condition is true.

Conditions are written with comparison operators: == (equal to), != (not equal to), < (less than), > (greater than), <= and >=. To chain several cases, add elif ("else if") which tests another condition, then else ("otherwise") which runs when everything else is false.

PYTHON
temperature = 15
if temperature > 25:
    print("It's hot.")
elif temperature > 10:
    print("It's mild.")
else:
    print("It's cold.")
With 15, the first condition is false and the second is true: displays "It's mild."

To combine several conditions, use the logical operators: and (true if both conditions are true), or (true if at least one is true), and not (inverts the result: not True is False).

PYTHON
age = 30
has_ticket = True
if age >= 18 and has_ticket:
    print("Entry allowed.")
if not has_ticket:
    print("Ticket missing.")
The first message is displayed, not the second.

Knowledge check

Make sure you remember the key points of this lesson.

  1. Which operator tests equality between two values?
    • =
    • ==
    • !=
    • <=
  2. When is the else block run?
    • Every time the program runs
    • When the if condition (and those of the elifs) are false
    • When the if condition is true
  3. What does the expression True and False evaluate to?
    • True
    • False
    • An error