If statements
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
temperature = 31
if temperature > 30:
print("It's hot!")
print("Drink some water.")
print("Have a nice day.")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).
if temperature > 30:
print("It's hot!")
print("Drink water") # IndentationError: unindent does not match any outer indentation levelEvery 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:
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:
score = 82
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "F"
print(grade) # BPython 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:
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:
if total < 0:
print("Invalid total")
elif total >= 100:
shipping = 0
else:
shipping = 15Useful conditions
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:
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:
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.
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.
total = float(input("Order total: "))
country = input("Country code: ")
# Your if / elif / else heretotal = float(input("Order total: "))
country = input("Country code: ").strip().upper()
if total < 0:
print("Invalid total")
else:
if total >= 100:
shipping = 0
elif country == "IN":
shipping = 5
elif country in ("US", "GB"):
shipping = 15
else:
shipping = 25
print(f"Shipping: {shipping}")
print(f"Total: {total + shipping}")Summary
if condition:runs the indented block only when the condition is truthy.elifadds more conditions;elsecatches 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_falsechooses between two values in one expression.