Introduction
In this lesson, you will learn how to make your Python programs actually decide things using if, elif, and else. You already know how to build Boolean expressions with comparison and logical operators; now you’ll use those expressions to control which code runs and when. We’ll build decision trees, combine multiple conditions, define fallback behavior, and avoid common pitfalls that often trip up beginners.
1. Basic Conditional Logic with if
An if statement lets you run a block of code only when a condition is true. You already know how to produce a Boolean expression; here we attach code to it.
age = 20
if age >= 18:
print("You are allowed to enter.")
print("Program finished.")
# Output:
You are allowed to enter.
Program finished.
Explanation:
age >= 18evaluates toTrue, so the indented block underifruns.- The final
print("Program finished.")always runs because it’s not indented under theif.
Key idea: Only the indented block belongs to the if. Everything at that indentation level or less is outside the conditional.
2. Adding Alternative Paths with else
else defines what should happen when the if condition is not true—your fallback behavior.
password = "abc123"
if len(password) >= 8:
print("Password length is OK.")
else:
print("Password is too short; it must be at least 8 characters.")
# Output:
Password is too short; it must be at least 8 characters.
Explanation:
len(password) >= 8isFalse(len("abc123")is 6).- The
ifblock is skipped, and theelseblock runs instead. - Exactly one of
iforelseruns, never both.
Use else when you want a default action if no earlier condition is satisfied.
3. Handling Multiple Cases with elif
When you have more than two possible outcomes, chaining conditions with elif (short for else if) is cleaner than nesting many if statements.
score = 72
tag = None
if score >= 90:
tag = "Excellent"
elif score >= 75:
tag = "Good"
elif score >= 60:
tag = "Pass"
else:
tag = "Fail"
print(f"Score: {score}, Result: {tag}")
# Output:
Score: 72, Result: Pass
How this flows:
- Python checks conditions top to bottom:
score >= 90→Falsescore >= 75→Falsescore >= 60→True→ executestag = "Pass"
- Once a condition is
True, the remainingelifandelseblocks are skipped.
Guidelines:
- Use
iffor the first condition. - Use as many
elifbranches as needed. - Use
elseoptionally at the end for “none of the above”.
4. Combining Conditions for Richer Logic
You can mix comparison and logical operators (and, or, not) to build more complex decision rules.
Example: Ticket Pricing Logic
age = 14
is_student = True
if age < 5:
price = 0
elif age <= 18 and is_student:
price = 5
elif age >= 65:
price = 6
else:
price = 10
print(f"Ticket price: ${price}")
# Output:
Ticket price: $5
Explanation:
age < 5→False.age <= 18 and is_student→14 <= 18isTrueandis_studentisTrue, so the combined condition isTrue.- Because that
elifis matched, later conditions (age >= 65andelse) are ignored.
Example: Validating User Login
username = "alice"
password = "secret123"
if not username:
print("Username is required.")
elif not password:
print("Password is required.")
elif len(password) < 8 or " " in password:
print("Password must be at least 8 characters and contain no spaces.")
else:
print("Credentials look valid (not checking against a real database here).")
# Output:
Credentials look valid (not checking against a real database here).
Highlights:
not usernameuses truthiness: empty strings are falsy.len(password) < 8 or " " in passwordusesorto express either condition being bad.- The final
elseis your fallback success path once all validation checks are passed.
5. Avoiding Common Conditional Pitfalls
5.1 Indentation Errors
Misaligned indentation changes which lines are controlled by which condition.
value = 10
if value > 0:
print("Positive number")
print("Still inside the if block")
print("Outside the if block")
# Output:
Positive number
Still inside the if block
Outside the if block
If you accidentally over‑indent or under‑indent, you might:
- Run code only in some cases when you meant to always run it.
- Get
IndentationErroror subtle logic bugs.
5.2 Misusing if Chains vs Independent if Statements
Remember: in an if/elif/else chain, only one block runs. If you need multiple independent checks, use separate if statements.
temperature = 30
if temperature > 25:
print("It's warm.")
if temperature > 30:
print("It's hot.")
# Output:
It's warm.
Compare with a chain:
temperature = 30
if temperature > 25:
print("It's warm.")
elif temperature > 30:
print("It's hot.")
# Output:
It's warm.
The elif is never considered because the first if is True.
5.3 Overly Nested Conditionals
Deep nesting is hard to read and debug. Prefer guard clauses and restructuring.
Instead of:
user_age = 19
has_id = True
if user_age >= 18:
if has_id:
print("Access granted.")
else:
print("ID required.")
else:
print("Too young.")
You can flatten it:
user_age = 19
has_id = True
if user_age < 18:
print("Too young.")
elif not has_id:
print("ID required.")
else:
print("Access granted.")
# Output:
Access granted.
This structure is easier to scan: it reads like a clear decision tree.
6. Practical Example: Simple Grading Helper
Let’s put everything together in a slightly more complete example.
score = 87
attendance_rate = 0.92 # 92%
if score < 0 or score > 100:
message = "Score must be between 0 and 100."
elif attendance_rate < 0.75:
message = "Fail due to low attendance."
elif score >= 90:
message = "Grade: A"
elif score >= 80:
message = "Grade: B"
elif score >= 70:
message = "Grade: C"
elif score >= 60:
message = "Grade: D"
else:
message = "Grade: F"
print(message)
# Output:
Grade: B
What’s happening:
- First, we validate that
scoreis in a valid range. - Second, we apply a separate condition about attendance using
elif. - Then we use a descending series of
elifchecks to assign a letter grade. - The
elseblock is the fallback for all lower scores.
This pattern—input validation, special rules, then main logic—is very common in real-world code.
Summary / Key Takeaways
In this lesson Writing Conditional Logic with if, elif, else, you have learned:
- Control execution with
if: Attach blocks of code to Boolean conditions so they run only when those conditions evaluate toTrue. - Use
eliffor multiple branches: Build clear decision trees where only the first matching condition’s block executes. - Define fallback behavior with
else: Provide a default path that runs when none of the previousif/elifconditions are satisfied. - Combine conditions effectively: Leverage comparison and logical operators (
and,or,not) to express complex business rules in a single conditional. - Keep indentation precise: Understand that indentation defines which statements belong to which conditional blocks and avoid shifting code unintentionally.
- Choose between chains and separate
ifs: Recognize when conditions are mutually exclusive (if/elif/else) versus when multiple independent checks are needed (separateifstatements). - Reduce nesting for readability: Replace deeply nested
ifstatements with guard clauses and well-orderedelifchains to keep logic easy to follow. - Apply conditionals to realistic scenarios: Use
if,elif, andelsetogether with previous knowledge of expressions to implement real-world logic like validation, grading, and pricing.
