Course contentsLesson 5 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 05

Decisions with conditionals

Edit lesson

Compare values and choose a branch with if, elif, and else.

15 minProgress saves on this device
In this lesson
  • Write comparisons
  • Choose between branches
  • Combine conditions and read indentation

Helpful background: Know how to assign variables and work with numbers.

Compare values

Comparisons such as ==, !=, <, and >= produce boolean values. Use == to compare two values; a single = is used for assignment.

For numbers, the usual order comparisons apply. For strings, comparisons are case-sensitive.

Comparepython
temperature = 24
print(temperature >= 20)  # True
print(temperature == 20)  # False

Choose a branch

An if statement runs its indented block when the condition is true. elif checks another condition only if the previous conditions were false; else handles the remaining case.

Python uses indentation to define a block. Use a consistent four spaces for each level.

A simple decisionpython
score = 72
if score >= 80:
    print("Excellent")
elif score >= 60:
    print("Passed")
else:
    print("Keep practicing")

Combine conditions

Use and when both conditions must be true, or when either is enough, and not to invert a condition. Parentheses can make a longer condition easier to understand.

Order matters: Python evaluates conditions from left to right and may stop once the result is known.

Combine checkspython
age = 18
has_ticket = True
if age >= 18 and has_ticket:
    print("Entry allowed")

Test the boundaries

Try values exactly on either side of a boundary. If the rule is at least 18, test 17, 18, and 19. These examples help reveal an accidental > where >= was intended.

Knowledge check

Which operator checks whether two values are equal?

Try first; feedback appears after you check.
Apply it

Your turn

Print "warm" when temperature is at least 20; otherwise print "cool".

Continue readingPython: if statements

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson