If…Else Statements
Programs constantly need to make decisions: is the PIN correct, is the balance high enough, did the student pass? The if, elif and else statements let your code choose which lines to run depending on whether a condition is True or False.
The if statement
An if statement checks a condition. If the condition is true, the indented block below it runs; if it is false, Python skips the block. Remember the colon at the end of the if line and the four-space indentation (see Comments & Indentation).
temperature = 31
if temperature > 30:
print("It's hot today.")
print("Carry water.")
print("Have a good day!")
The condition can be any expression that gives True or False, usually built with the comparison and logical operators.
Adding else
else gives the "otherwise" path. Exactly one of the two blocks runs, never both.
balance = 1500
amount = 2000
if amount <= balance:
balance -= amount
print("Withdrawal successful. New balance:", balance)
else:
print("Insufficient funds. Balance:", balance)
Several choices with elif
elif (short for "else if") lets you test more conditions in order. Python checks them from top to bottom and runs the block for the first true condition only. The final else catches everything that didn't match.
marks = 67
if marks >= 80:
grade = "A"
elif marks >= 65:
grade = "B"
elif marks >= 50:
grade = "C"
else:
grade = "D"
print("Grade:", grade)
67 is not 80 or more, so the first test fails. 67 is 65 or more, so grade becomes "B" and Python skips the remaining tests, even though marks >= 50 is also true.
marks = 67 the first test is False and the second is True, so the program takes the highlighted "B" branch and skips the rest.Putting conditions in the wrong order. Because only the first true branch runs, broad tests must come after narrow ones. If you check marks >= 50 before marks >= 80, a student with 85 gets a C, because the first test was already true.
Combining conditions
Use and, or and not to build richer conditions. Brackets make the logic easy to follow.
year = 1900
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
A year is a leap year if it divides by 4 but not by 100, or if it divides by 400. 1900 divides by 4 and by 100, but not by 400, so it isn't one. Try 2024 and 2000: both are leap years.
Writing if answer == "yes" or "y":. Python reads this as (answer == "yes") or ("y"), and the non-empty string "y" is always truthy, so the condition is always true. Write if answer == "yes" or answer == "y":, or more neatly if answer in ("yes", "y"):.
Nested if statements
You can put an if inside another if. Each level is indented four more spaces.
age = 20
has_id = False
if age >= 18:
if has_id:
print("Welcome in.")
else:
print("Please show your ID.")
else:
print("Sorry, adults only.")
Nesting is fine for one or two levels. Deeper nesting gets hard to read; combining conditions with and, or using elif, is often clearer.
Truthy and falsy conditions
A condition doesn't have to be a comparison. Python treats 0, 0.0, empty strings, empty collections and None as false, and everything else as true (see Type Conversion). This gives a short way to check whether the user typed anything. In the sample run, the user just presses Enter:
name = input("Your name: ").strip()
if name:
print(f"Hello, {name}!")
else:
print("You didn't enter a name.")
The conditional expression
When you only need to choose between two values, a one-line conditional expression (sometimes called a ternary) is neater: value_if_true if condition else value_if_false.
age = 4
fare = 0 if age < 5 else 50
print("Fare: KES", fare)
stock = 3
print("In stock" if stock > 0 else "Sold out")
Use it for simple choices only. If you need several lines in either branch, use a normal if/else statement.
A complete example
units = int(input("Electricity units used: "))
if units <= 0:
print("Please enter a positive number.")
elif units <= 30:
print(f"Lifeline rate: KES {units * 12.5:,.2f}")
else:
print(f"Standard rate: KES {units * 20:,.2f}")
(The rates here are made up for practice.) The first branch guards against bad input before the real calculation, a pattern you'll use often.
Forgetting the colon (if x > 5) or using = instead of == (if x = 5:). Both are SyntaxErrors. Python's message for the second even suggests you might have meant ==.
Key points
ifruns a block only when its condition is true;elsehandles the other case.eliftests further conditions in order, and only the first true branch runs.- Combine conditions with
and,orandnot; compare each value fully. - Empty, zero and
Nonevalues count as false in conditions. a if condition else bchooses between two values in one line.
Tip: use the ← and → keys to move between pages.
