Definition
How does an app decide your grade from your marks?
A conditional statement runs a block of code only when a condition is True. if checks the first condition, elif checks further conditions in order, and else runs when none of them are True. Only the first matching branch runs. Conditions can be nested inside each other.
In simple words
It's the diamond in a flowchart, written in Python. if marks >= 90, the grade is A; elif marks >= 75, it's B; and so on, ending with else for everything else. Python checks from the top and stops at the first True.
Overview
- Conditional statements let a program choose which code to run based on whether a condition is True or False.
- Conditions are expressions that give True or False, built with comparison and logical operators.
- The block under an if must be indented; the colon at the end of the if line is required.
- Python treats 0, empty strings, empty collections and None as False (falsy); everything else is truthy.
- Only the first matching branch of an if-elif-else chain runs.
- Decision rules like these are the heart of rule-based AI and expert systems.
Why it matters
Programs must react differently to different situations: approve or decline a payment, show or hide a message, label an email spam or not. Even the simplest AI, a rule-based chatbot, is built from conditions.
Key terms
- Condition
- An expression that is True or False.
- if statement
- Runs its block only when its condition is True.
- elif
- Short for "else if": checks another condition when earlier ones were False.
- else
- Runs when none of the conditions above were True.
- Nested condition
- An if statement inside another if block.
- Conditional expression
- A one-line choice: value_if_true if condition else value_if_false.
Types
Python offers several forms of decision-making. Each fits a different number of choices or a different style of code.
1. Simple if
Runs a block only when the condition is True, and does nothing otherwise.
- How it works: Python evaluates the condition; if it is True the indented block runs, then the program continues after it either way.
- Example: if temperature > 40: print("Heatwave warning")
- When to use it: Use it for an optional extra action, such as a warning.
2. if-else
Chooses between exactly two blocks: one for True, one for False.
- How it works: If the condition is True the if-block runs; otherwise the else-block runs; exactly one of them always runs.
- Example: if marks >= 33: print("Pass") else: print("Fail")
- When to use it: Use it for yes-or-no decisions with an action on both sides.
3. if-elif-else ladder
Checks several conditions in order and runs the first one that is True.
- How it works: Python tests each elif from the top; once one matches, the rest are skipped; else catches everything left.
- Example: Grades: marks ≥ 90 gives A, ≥ 75 gives B, ≥ 50 gives C, otherwise D.
- When to use it: Use it for three or more ranges or categories; order the conditions from most to least specific.
4. Nested if
An if statement placed inside another if or else block.
- How it works: The inner condition is checked only when the outer one has already been met, adding a second level of decision.
- Example: if has_ticket: then inside it, if age < 5: "free entry" else: "check the ticket".
- When to use it: Use it when a second question only makes sense after the first answer; avoid deep nesting by combining conditions with and.
5. Conditional expression (ternary)
A one-line form that picks one of two values: a if condition else b.
- How it works: It is an expression, so it produces a value that can be assigned or printed directly.
- Example: result = "Pass" if marks >= 33 else "Fail"
- When to use it: Use it for short choices between two values; use a full if-else for anything longer.
6. match-case (structural pattern matching)
A statement, added in Python 3.10, that compares a value against several patterns.
- How it works: Python checks each case from the top and runs the first that matches; case _ catches anything else; patterns can also unpack lists and tuples.
- Example: match command: case "start": ... case "stop": ... case _: print("Unknown")
- When to use it: Use it for menus, commands and messages with many fixed options.
Explained in detail
How Python chooses a branch
An if-elif-else chain is checked from the top down, and only the first branch whose condition is True runs. The rest are skipped, even if their conditions are also True. That makes the order of conditions crucial. To give grades, checking mark >= 90 before mark >= 75 works correctly. Reversing them would give a learner with 95 the lower grade, because 95 >= 75 is True and the chain would stop there. A useful check is to ask, for each branch, "could a value that belongs to a later branch stop here first?"
Separate ifs versus one chain
| Pattern | Behaviour | Use when |
|---|---|---|
| if … elif … else | Exactly one branch runs | The options are mutually exclusive, like grades |
| Several separate if statements | Every true condition runs its block | Several independent checks, like listing every warning that applies |
| Nested if | Inner check only when the outer one is True | A second question only makes sense after the first, like checking a password only if the user exists |
Writing clear conditions
- Combine checks with and/or instead of nesting when possible: if age >= 18 and has_id:.
- Use chained comparisons for ranges: if 0 <= mark <= 100:.
- Use in for several allowed values: if day in ("Sat", "Sun"):.
- Handle invalid input first and return early, so the main logic is not deeply indented.
- Give complicated conditions a name: is_eligible = age >= 18 and has_id.
One-line choices and match
For a simple choice between two values, a conditional expression keeps code short: result = "pass" if mark >= 40 else "fail". Use it only when it stays readable. Python 3.10, released in 2021, added the match statement, which compares a value against several patterns, somewhat like the switch statement of other languages. For most conditions in this course, if-elif-else is clearer and enough.
Decision rules like these are the oldest form of AI. The expert systems of the 1970s and 1980s, such as MYCIN, which suggested treatments for blood infections, were essentially thousands of carefully ordered if-then rules written by experts.
Finally, test every branch. A chain with four branches needs at least four test inputs, plus the boundary values between them, before you can trust it.
How it works
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 40:
grade = "C"
else:
grade = "Fail"- Each condition ends with a colon, and its block is indented.
- Order matters: put the most specific or highest check first.
- Combine conditions with and, or and not.
In code
The same grading rule applied to several marks, plus a nested check.
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 40:
return "C"
else:
return "Fail"
for marks in [95, 82, 40, 39]:
print(marks, "->", grade(marks))
age, has_ticket = 16, True
if has_ticket:
if age >= 18:
print("Enter the adult section")
else:
print("Enter the family section")
else:
print("Please buy a ticket")Output
95 -> A 82 -> B 40 -> C 39 -> Fail Enter the family section
Try it yourself
Which branch runs?
Using the grading rule above, which grade does each mark get?
marks = 12
marks = 75
marks = 90
marks = 40
marks = 89
Common mistakes
- Putting the lowest check first, so every mark above 40 gets C.
- Forgetting the colon or the indentation.
- Using = instead of == inside a condition.
Check yourself
Summary
- if, elif and else choose one branch to run.
- Python checks from the top and stops at the first True.
- Order the checks carefully, and indent each block.
Finished reading?
Sources: W3Schools: Python If...Else