Course curriculum
Python · LESSON 3 OF 5

Make decisions with conditions

Use comparisons, if/elif/else and boolean expressions to choose the correct branch.

About 8 minutes · Beginner

Choose a branch

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

Indentation is part of Python syntax. Use four spaces for each block and keep statements at the same level aligned.

Python
score = 72
if score >= 75:
    print("Distinction")
elif score >= 40:
    print("Pass")
else:
    print("Try again")
Expected output
Pass

Order your comparisons

Check the most specific or highest threshold first. If score >= 40 came first, a score of 90 would enter that branch and never reach the distinction check.

Use and when both conditions must hold, or when either is enough, and not to reverse a boolean. Parentheses can make a longer expression easier to read.

Python
age = 19
has_id = True
can_register = age >= 18 and has_id
print(can_register)
Expected output
True

Test boundaries

For a pass threshold of 40, test 39, 40 and 41. Boundary cases expose mistakes such as using > when you meant >=.

Also decide how your program should handle values outside the valid range, such as a negative exam score. Conditions are useful for validation as well as business rules.

Try it yourself

Given temperature = 31, print “Hot” for temperatures at least 30, otherwise print “Comfortable”.

Show a possible solution
Python
temperature = 31
if temperature >= 30:
    print("Hot")
else:
    print("Comfortable")

Keep exploring: official Python documentation.

0 of 5 completed on this device