Python with AI Tutorial · Chapter 17 of 48
A Python if else statement lets your program make decisions. Python evaluates a condition, runs one block of code when it is True and a different block when it is False. With elif you can test several conditions in order, and by nesting one if inside another you can model more detailed business rules.
The if statement
An if statement starts with the keyword if, a condition and a colon. The indented lines beneath it only run when the condition is true.
invoice_total = 1250
if invoice_total > 1000:
print("Large invoice - needs manager approval")
print("Invoice processed")
Output: Large invoice - needs manager approval Invoice processed
The last print() is not indented, so it runs regardless of the condition. Indentation is how Python knows which lines belong to the if block.
Comparison operators
Conditions are usually built with comparison operators. Each one returns a Boolean value, True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 10 > 20 |
False |
< |
Less than | 10 < 20 |
True |
>= |
Greater than or equal | 7 >= 7 |
True |
<= |
Less than or equal | 8 <= 7 |
False |
in |
Contained in | "a" in "sales" |
True |
Strings can be compared as well. "apple" < "banana" is True because Python compares character by character in Unicode order, which also means uppercase letters sort before lowercase ones. When you compare user-entered text, normalise it with .lower() or .strip() first so that “Paid” and “paid ” are treated the same.
if…else
Add an else block to run code when the condition is false. Exactly one of the two blocks will execute.
stock = 4
reorder_level = 10
if stock < reorder_level:
print("Reorder now")
else:
print("Stock is fine")
Output: Reorder now
elif for several conditions
elif is short for “else if”. Python checks each condition from top to bottom and runs the first block that matches, then skips the rest.
monthly_sales = 48000
if monthly_sales >= 60000:
bonus = 0.10
elif monthly_sales >= 40000:
bonus = 0.05
elif monthly_sales >= 20000:
bonus = 0.02
else:
bonus = 0
print(f"Bonus rate: {bonus:.0%}")
print(f"Bonus amount: {monthly_sales * bonus:,.2f}")
Output: Bonus rate: 5% Bonus amount: 2,400.00
Order matters. If the >= 20000 test came first, a salesperson with 48,000 in sales would receive the 2% rate because that condition is also true.
Ask an assistant to turn a commission table from your business into an if/elif chain and to explain why the order of the tests matters.
Write a Python function commission_rate(sales) using if, elif and else. Rates: 0% below 10,000; 3% from 10,000 to 24,999; 5% from 25,000 to 49,999; 8% at 50,000 or above. Then show what goes wrong if the conditions are written in the opposite order.
Combining conditions with and, or, not
Logical operators let one if check several things at once. and needs every part to be true, or needs at least one and not flips the result.
department = "Finance"
years_of_service = 6
is_contractor = False
if department == "Finance" and years_of_service >= 5:
print("Eligible for the leadership programme")
if department == "Sales" or department == "Marketing":
print("Attends the quarterly revenue meeting")
if not is_contractor:
print("Receives the annual bonus")
Output: Eligible for the leadership programme Receives the annual bonus
Python evaluates these operators lazily, a behaviour called short-circuiting. With and, if the first part is False the second part is never checked; with or, a True first part ends the test. That lets you write safe checks such as if customer and customer.get("email"):, where the second test only runs when customer is not empty.
Nested if statements
An if can sit inside another if. The inner test only runs when the outer condition passed, which is handy for rules that depend on an earlier decision.
order_value = 850
customer_type = "wholesale"
if order_value > 500:
if customer_type == "wholesale":
discount = 0.15
else:
discount = 0.10
else:
discount = 0
print(f"Discount: {discount:.0%}, pay {order_value * (1 - discount):.2f}")
Output: Discount: 15%, pay 722.50
Two levels of nesting are usually fine. Deeper than that, consider rewriting with and or moving the logic into a function.
Truthy and falsy values
Any object can be used as a condition. Empty containers, zero and None count as false; almost everything else counts as true. This makes checks like “is the list empty?” very short.
overdue_invoices = []
if overdue_invoices:
print(f"{len(overdue_invoices)} invoices overdue")
else:
print("No overdue invoices")
Output: No overdue invoices
A related idiom is checking for None, which Python uses to mean “no value yet”. Write if manager is None: rather than == None; the is operator tests identity and is the form recommended by the official style guide. The same applies to if result is not None:.
Short hand if and the conditional expression
A single-line if is allowed, and Python also has a conditional expression (often called a ternary) that picks one of two values.
temperature = 31
if temperature > 30: print("Warehouse cooling on")
balance = 120.0
label = "Paid" if balance == 0 else "Unpaid"
print(label)
Output: Warehouse cooling on Unpaid
Use the conditional expression for simple value choices only. If each branch needs several statements, write a normal if...else block.
if status = "Paid": with a single equals sign. That is assignment, not comparison, and Python raises a SyntaxError. Always use == inside a condition.The pass statement
An if block cannot be empty. When you have not written the logic yet, use pass as a placeholder so the file still runs.
region = "EMEA"
if region == "EMEA":
pass # tax rules to be added
print("Done")
Output: Done
Paste a nested if block and ask the assistant to flatten it, then check that both versions give the same answer for a few test inputs.
Here is a nested Python if statement that decides shipping cost from order_value and country. Rewrite it with a flat if/elif chain using "and", keep the same behaviour, and give me a table of 6 test inputs with the expected output for both versions.
Common mistakes
- Forgetting the colon at the end of the
if,eliforelseline. - Mixing tabs and spaces in the indented block, which causes an
IndentationError. - Comparing a number to a string, for example
input()returns text, so"5" > 3raises aTypeError. - Writing
elifconditions in the wrong order so a broader test hides a narrower one. - Using
==to compare withNone; the idiomatic form isis None.
Exercise
Write a program that stores an employee’s hours_worked (a number) and prints “Overtime” if it is above 40, “Full time” if it is exactly 40, “Part time” if it is at least 20, and “Casual” otherwise. Test it with 45, 40, 25 and 10.
Show answer
for hours_worked in (45, 40, 25, 10):
if hours_worked > 40:
category = "Overtime"
elif hours_worked == 40:
category = "Full time"
elif hours_worked >= 20:
category = "Part time"
else:
category = "Casual"
print(hours_worked, category)
Output: 45 Overtime 40 Full time 25 Part time 10 Casual
Related chapters
FAQ
What is the difference between if, elif and else in Python?
if tests the first condition, elif tests further conditions only when the earlier ones were false, and else runs when none of the conditions matched. Only one block in the chain executes.
Does Python have a switch or case statement?
Python 3.10 added match...case for structural pattern matching, but for simple value checks an if...elif chain or a dictionary lookup is still the most common approach.
Can I write an if statement on one line in Python?
Yes. if x > 5: print(x) is valid, and the conditional expression a if condition else b chooses between two values on one line.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 17 of 48 · Python with AI: all 48 chapters



