4. Conditionals / Decision Making

Letting a program choose

Without decisions a program would do exactly the same thing every time. Conditionals let it branch: run one block of code when a condition is true, and perhaps a different block when it is false. The condition is any expression that evaluates to a boolean — true or false.

age >= 18 ? condition False True deny entry allow entry continue

if, else

The simplest conditional runs a block only when a condition holds. Add else to specify what happens otherwise. Notice how indentation (or braces, in other languages) marks which statements belong to each branch.

age = 20
if age >= 18:
    print("You may enter.")
else:
    print("Sorry, you are too young.")

else if: choosing among many paths

Often there are more than two outcomes. Chain conditions with else if (written elif in Python). The computer checks each condition in order and runs the first one that is true, skipping the rest — so order matters.

score = 82
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)   # B

If you reversed the order and tested score >= 70 first, everyone above 70 would get a C, because the first matching branch wins. Put the most specific or highest conditions first.

Combining conditions

Use the logical operators from the previous chapter to build richer tests. The table shows how a two-part condition behaves:

age >= 18has_ticketage >= 18 AND has_ticketOutcome
TrueTrueTrueEnter
TrueFalseFalseBlocked
FalseTrueFalseBlocked
FalseFalseFalseBlocked

Nested conditions

A conditional can live inside another conditional. This is useful when a second question only makes sense after the first is answered. Keep nesting shallow — deeply nested ifs become hard to read, and can often be flattened with and or an early return.

if logged_in:
    if is_admin:
        print("Admin dashboard")
    else:
        print("User dashboard")
else:
    print("Please log in")

Key idea: conditionals steer the flow of a program using boolean expressions; elif chains pick the first true branch, and clear conditions beat clever ones.