If statements

Topic 2 of 3 in Making decisions6 min readBeginnerFree course

Overview

Until now your programs have run every line, top to bottom. if statements let a program choose: run some code only when a condition is true, or pick one of several paths. This is where programs start to feel smart.

if

Python
temperature = 31
if temperature > 30:
    print("It's hot!")
    print("Drink some water.")
print("Have a nice day.")
Text
It's hot!
Drink some water.
Have a nice day.

The parts:

  • the keyword if, a condition, and a colon :;
  • an indented block — the lines that run only when the condition is true;
  • the block ends where the indentation ends. “Have a nice day.” isn’t indented, so it always runs.

Indentation defines blocks

Python uses indentation instead of braces to group lines. The convention is 4 spaces per level (your editor inserts them when you press Tab).

Python
if temperature > 30:
    print("It's hot!")
  print("Drink water")     # IndentationError: unindent does not match any outer indentation level

Every line in a block must be indented by the same amount. Mixing tabs and spaces causes confusing errors — let your editor handle it (VS Code uses spaces by default for Python).

else

else runs when the condition is false:

Python
if age >= 18:
    print("You can vote.")
else:
    print(f"You can vote in {18 - age} years.")

elif: several choices

For more than two paths, add elif (“else if”) branches:

How if / elif / else chooses one path. The code checks if score >= 90 then grade = “A”, elif score >= 75 then “B”, elif score >= 50 then “C”, else “F”. As a flowchart: score >= 90? yes leads to grade “A”, no leads to score >= 75? — yes “B”, no leads to score >= 50? — yes “C”, no “F”. Conditions are checked top to bottom; only the first true branch runs.

Python
score = 82
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 50:
    grade = "C"
else:
    grade = "F"
print(grade)     # B

Python checks the conditions top to bottom and runs only the first branch whose condition is true; the rest are skipped. That’s why the order matters: a score of 95 is also >= 75, but it never gets there because the first branch already matched.

Order conditions from most specific to least specific. If you wrote score >= 50 first, everyone with 50 or more would get a C.

else is optional; without it, nothing happens when no condition matches.

Nested ifs

A block can contain another if:

Python
if total >= 0:
    if total >= 100:
        shipping = 0
    else:
        shipping = 15
else:
    print("Invalid total")

Nesting is sometimes the clearest option, but deep nesting is hard to read. Often you can flatten it with elif or and, or by handling the special case first:

Python
if total < 0:
    print("Invalid total")
elif total >= 100:
    shipping = 0
else:
    shipping = 15

Useful conditions

Python
if country in ("US", "GB", "CA"):     # one of several values
if not name:                          # empty string
if 18 <= age < 65:                    # a range
if password == confirm and len(password) >= 12:
if item is None:

in with a tuple of values is much tidier than country == "US" or country == "GB" or ….

Conditional expressions

When you just need to choose between two values, there’s a one-line form:

Python
label = "adult" if age >= 18 else "child"
print(f"{count} item{'s' if count != 1 else ''}")

Read it as: “adult”, if age is at least 18, otherwise “child”. Keep it for simple choices; anything with side effects or more than two options deserves a full if.

pass: an empty block

A block can’t be empty. While sketching code, use pass as a placeholder:

Python
if user_is_admin:
    pass    # TODO: admin features
else:
    print("Welcome")

Checklist for every if: a colon at the end, a consistently indented block, conditions in the right order — and test each branch, including the else.

Exercise

Shipping cost calculator

Ask for an order total (a number) and a country code. Shipping rules: orders of 100 or more ship free; otherwise domestic orders (country IN) cost 5, orders to US or GB cost 15, and everywhere else costs 25. Also: if the order total is below 0, print Invalid total and don’t print anything else. Accept the country code in any case and with extra spaces ( in should count as IN). Print the shipping cost and the grand total, e.g. Shipping: 15 and Total: 75.0.

Python
total = float(input("Order total: "))
country = input("Country code: ")

# Your if / elif / else here

Summary

  • if condition: runs the indented block only when the condition is truthy.
  • elif adds more conditions; else catches everything else; only the first matching branch runs.
  • Indentation (4 spaces) defines the block — every line in it must be indented the same.
  • Order conditions from most specific to least specific.
  • value_if_true if condition else value_if_false chooses between two values in one expression.