Decisions with if, elif, and else

← Back to Blog & Articles

Programs become interesting when they can choose between actions. In Python, if statements make those choices.

The basic idea

An if checks a condition. If it is true, the indented code underneath runs. If not, Python skips it.

temperature = 30
if temperature > 25:
    print("Wear a hat!")

Adding an alternative

else handles every other case:

if temperature > 25:
    print("Wear a hat!")
else:
    print("Bring a jacket!")

Several choices with elif

When there are more than two possibilities, use elif, which means "else if". Python checks the conditions from top to bottom and runs the first one that is true.

Comparing things

Use == to check whether two values are equal, and != for not equal. Also available are <, >, <=, and >=. A common beginner mistake is using a single =, which stores a value instead of comparing.

Indentation matters

The indented lines belong to the if. In Python, spacing is part of the code, so keep it consistent.

A game idea

Write a number guessing game: the program picks a secret number, and if, elif, and else decide whether to say "too high", "too low", or "you got it!".

Takeaway

Conditions let a program react to the situation, which makes it feel smart.

Continue with the book

Explore the full treatment, worked examples, and exercises in Code Quest with Python.


Adapted from Code Quest with Python, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top