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:

PYTHON
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.

PYTHON
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:

TEXT
You are an adult!
This is also inside the if block.
This is outside the if and always executes.
💡 Tip: Python uses indentation to define code blocks (other languages use {}). 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 ⭐)

PYTHON
score = 75

if score >= 60:
    print("Congratulations, you passed!")
    print(f"Your score is {score}.")

print("Score recorded.")
▶ Try it Yourself

Output:

TEXT
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:

PYTHON
if condition:
    execute when True
else:
    execute when False
PYTHON
score = 45

if score >= 60:
    print("Passed!")
else:
    print("Failed, need to retake.")

Output:

TEXT
Failed, need to retake.

Indentation for if and else

PYTHON
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'.")
⚠️ Note: 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:

PYTHON
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.

PYTHON
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!
💡 Tip: Pay attention to condition order. If you put 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 ⭐⭐)

PYTHON
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!")
▶ Try it Yourself

Output:

TEXT
=== 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.

PYTHON
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:

TEXT
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:

PYTHON
# ❌ 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:

PYTHON
# ✅ 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.")
💡 Tip: A practical rule: if nesting exceeds 3 levels, consider combining conditions with and/or, or extracting the deep logic into a function. Good code is "flat," not "deep."

Example: Shipping Cost Calculator (Difficulty ⭐⭐)

PYTHON
# 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}")
▶ Try it Yourself

Output:

TEXT
Region: domestic
Weight: 3.5kg
Shipping: $15

5. Ternary Expression (Conditional Expression)

Python has a one-line if-else syntax called the ternary expression:

PYTHON
# 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:

TEXT
value1 if condition else value2

If the condition is true, take value1; otherwise, take value2.

Practical Use

PYTHON
# 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)
⚠️ Note: Ternary expressions are concise, but don't overuse them. If the logic is complex (needing 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:

PYTHON
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:

PYTHON
# Real-world usage
if user_age >= 18:
    register_user()      # Proceed with registration
else:
    pass                 # No special handling for minors yet
💡 Tip: If you use VS Code, write a # TODO comment with pass. VS Code will collect all TODO items for easy reference later.


Common Use Cases


❓ FAQ

Q What's the difference between elif and if? Why not use all ifs?
A The key difference: 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

  • if is followed by a condition; if true, the indented block runs
  • else handles the false case; can't be used alone
  • elif handles 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 y for simple one-line choices
  • pass is 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/or when possible

📝 Exercises

  1. Basic (Difficulty ⭐): Write a program to check if a number is odd or even. Input an integer; output "odd" or "even." Hint: n % 2 == 0 means even.

  2. 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"
  3. 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
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏