Conditionals
In the last lesson we learned how to make true/false judgments with boolean logic. Now let's learn conditionals — making the program execute different code based on different conditions. This is one of the most fundamental control structures in any programming language.
1. The if Statement: Simple Condition
The if format is straightforward:
if condition:
code to execute when condition is True
Note the colon : and indentation (usually 4 spaces) — indentation tells Python which code belongs to the if.
age = 18
if age >= 18:
print("You are an adult!")
print("This is also inside the if block.")
print("This is outside the if and always executes.")
Output:
You are an adult!
This is also inside the if block.
This is outside the if and always executes.
{}). Code inside the same if block must have the same indentation. If you're used to C or Java, this takes some getting used to, but Python forces you to write clean code.
Example: Pass/Fail Check (Difficulty ⭐)
score = 75
if score >= 60:
print("Congratulations, you passed!")
print(f"Your score is {score}.")
print("Score recorded.")
Output:
Congratulations, you passed!
Your score is 75.
Score recorded.
2. if-else: Choose Between Two
When the condition is true, do one thing; when false, do another:
if condition:
execute when True
else:
execute when False
score = 45
if score >= 60:
print("Passed!")
else:
print("Failed, need to retake.")
Output:
Failed, need to retake.
Indentation for if and else
password = "123456"
if password == "123456":
print("Password correct, welcome back!")
else:
print("Wrong password, try again.")
print("If you forgot your password, click 'Forgot Password'.")
else also needs a colon :, and else must align with its matching if (same indentation level).
3. if-elif-else: Choose from Multiple Options
Real-world scenarios often have more than two possibilities. Use elif (short for else if) to handle multiple branches:
if condition1:
execute when condition1 is True
elif condition2:
execute when condition2 is True
elif condition3:
execute when condition3 is True
else:
execute when none of the above are True
Python checks from top to bottom — the first true condition gets executed, then the entire if-elif-else structure is exited.
score = 85
if score >= 90:
print("Excellent!")
elif score >= 80:
print("Good!")
elif score >= 70:
print("Average.")
elif score >= 60:
print("Pass.")
else:
print("Failed, need to retake.")
# Output: Good!
if score >= 60: first, a score of 85 would enter the "Pass" branch and never reach "Good" or "Excellent." Put stricter conditions first.
Example: Restaurant Ordering System (Difficulty ⭐⭐)
print("=== Today's Meals ===")
print("1. Braised Beef Noodles $10")
print("2. Shredded Pork Rice $8")
print("3. Tomato Egg Rice $6")
print("4. Egg Fried Rice $4")
choice = 3
if choice == 1:
print("You ordered Braised Beef Noodles, $10.")
elif choice == 2:
print("You ordered Shredded Pork Rice, $8.")
elif choice == 3:
print("You ordered Tomato Egg Rice, $6.")
elif choice == 4:
print("You ordered Egg Fried Rice, $4.")
else:
print("Sorry, invalid option.")
print("Enjoy your meal!")
Output:
=== Today's Meals ===
1. Braised Beef Noodles $10
2. Shredded Pork Rice $8
3. Tomato Egg Rice $6
4. Egg Fried Rice $4
You ordered Tomato Egg Rice, $6.
Enjoy your meal!
4. Nested Conditions
Conditions can contain other conditions. This is called nesting.
age = 20
has_ticket = True
if age >= 18:
print("Adult, can enter.")
if has_ticket:
print("Has ticket, please proceed.")
else:
print("Please buy a ticket first.")
else:
print("Minor, entry denied.")
Output:
Adult, can enter.
Has ticket, please proceed.
Don't Nest Too Deep
Nesting itself isn't wrong, but more than 3 levels deep makes code hard to read:
# ❌ Not recommended: too much nesting
user_input = "y"
is_admin = True
has_permission = True
if user_input == "y":
if is_admin:
if has_permission:
print("Operation successful!")
else:
print("No permission.")
else:
print("Not an admin.")
else:
print("Operation canceled.")
Flatten it using logical operators:
# ✅ Recommended: use and to reduce nesting
user_input = "y"
is_admin = True
has_permission = True
if user_input != "y":
print("Operation canceled.")
elif is_admin and has_permission:
print("Operation successful!")
else:
print("Insufficient permissions.")
and/or, or extracting the deep logic into a function. Good code is "flat," not "deep."
Example: Shipping Cost Calculator (Difficulty ⭐⭐)
# Calculate shipping based on region, weight, and member level
region = "domestic" # "domestic" or "international"
weight = 3.5 # kg
is_vip = False
if region == "domestic":
if weight <= 1:
shipping = 10
elif weight <= 5:
shipping = 15
else:
shipping = 20
else:
if weight <= 1:
shipping = 50
elif weight <= 5:
shipping = 80
else:
shipping = 120
# VIP gets 20% off
if is_vip:
shipping *= 0.8
print(f"Region: {region}")
print(f"Weight: {weight}kg")
print(f"Shipping: ${shipping:.0f}")
Output:
Region: domestic
Weight: 3.5kg
Shipping: $15
5. Ternary Expression (Conditional Expression)
Python has a one-line if-else syntax called the ternary expression:
# Regular way
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
# Ternary expression (one line)
status = "adult" if age >= 18 else "minor"
print(status) # adult
The structure:
value1 if condition else value2
If the condition is true, take value1; otherwise, take value2.
Practical Use
# Output a result based on score
score = 88
result = "passed" if score >= 60 else "failed"
print(f"Exam result: {result}") # Exam result: passed
# Default value lookup
name = input("Enter your name: ") or "Guest"
greeting = f"Hello, {name}" if name else "Hello, Guest"
print(greeting)
elif) or branches are long, stick to regular if-elif-else. Concise ≠ Readable.
6. pass: Do Nothing
Sometimes you need a placeholder — syntax requires code, but you haven't decided what to write yet. Use pass:
if age >= 18:
pass # TODO: add adult logic later
else:
print("Minor, cannot register.")
pass means "do nothing here, move along." It's often used for:
- Placeholder: structure first, fill in details later
- Empty function:
def my_function(): pass - Empty class:
class MyClass: pass
# Real-world usage
if user_age >= 18:
register_user() # Proceed with registration
else:
pass # No special handling for minors yet
# TODO comment with pass. VS Code will collect all TODO items for easy reference later.
Common Use Cases
- Form validation: Check if input is empty, format is correct, length meets requirements.
- Permission levels: Regular users see UI A, VIP users see UI B, admins see UI C.
- Game state machine: Check if the game is over, a level is cleared, or an achievement is earned.
- Price calculation: Discounts, member deals, seasonal promotions — different condition combinations yield different final prices.
- Menu navigation: The user enters 1/2/3/4 on the console, and the program enters different function modules.
❓ FAQ
elif and if? Why not use all ifs?elif is only checked if previous conditions weren't met, while independent if statements are checked regardless. With three independent if statements for a score of 85, "Excellent," "Good," and "Average" would all execute. With if-elif-elif, only the first matching "Good" branch runs. Use elif for "choose one," use multiple ifs for "check each independently."
⚠️ Q: Why does VS Code auto-indent 4 spaces after I write if condition:? A: Python requires indentation after a colon. VS Code's Python extension handles this automatically. If you forget to indent, Python raises IndentationError: expected an indented block. Indentation in Python isn't a "style suggestion" — it's syntax. Wrong indentation means the code won't run.
Q: Can ternary expressions use elif? A: No. Ternary expressions only handle "choose between two" (value1 if condition else value2). For multiple choices, you can nest ternaries: a if cond1 else b if cond2 else c, but this is strongly discouraged — nested ternaries are nearly unreadable. Use regular if-elif-else for multiple branches.
Q: What's the difference between pass and return? A: pass means "do nothing, continue execution"; return means "immediately exit the current function and return a value" (we'll cover this later). Using pass in an if block skips that block and continues. Using return in a function exits the function immediately. They're completely different concepts.📖 Summary
ifis followed by a condition; if true, the indented block runselsehandles the false case; can't be used aloneelifhandles multiple branches, checked top to bottom; the first true one runs- Nested conditions handle complex hierarchies, but keep nesting under 3 levels
- Ternary expression
x if condition else yfor simple one-line choices passis a placeholder for when syntax requires code but you have nothing to do yet- Good habits: stricter conditions first, keep nesting under 3 levels, flatten with
and/orwhen possible
📝 Exercises
-
Basic (Difficulty ⭐): Write a program to check if a number is odd or even. Input an integer; output "odd" or "even." Hint:
n % 2 == 0means even. -
Intermediate (Difficulty ⭐⭐): Write a BMI health assessment program. Input weight (kg) and height (m), calculate BMI, then output:
- BMI < 18.5 → "Underweight"
- 18.5 ≤ BMI < 24 → "Normal"
- 24 ≤ BMI < 28 → "Overweight"
- BMI ≥ 28 → "Obese"
-
Challenge (Difficulty ⭐⭐⭐): Write a simple calculator. The program receives three inputs: first number, operator (
+-*/), second number. Execute the operation and output the result. Handle:- Division by zero: output "Cannot divide by zero"
- Invalid operator: output "Invalid operator"
- Normal case: output the calculation result



