Skip to main content

🔀 Lesson 3.1: Conditionals — if, else, and switch

Programs that can make decisions are programs that can do real work. Time to teach your code to think.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Write if, else if/elif, and else blocks in all three languages
  • Understand the difference between indentation-based (Python) and brace-based (JS/C#) code blocks
  • Use comparison operators (==, !=, <, >, <=, >=)
  • Write switch/match statements for multi-way branching
  • Use the ternary operator for quick inline decisions

Estimated Time: 45 minutes

Project: A grade calculator that converts numeric scores to letter grades

📑 In This Lesson

The Basic if Statement

An if statement runs a block of code only when a condition is true. If the condition is false, the block is skipped entirely.

graph TD A["Start"] --> B{"Is temperature
> 30?"} B -->|Yes| C["Print 'It's hot!'"] B -->|No| D["Skip"] C --> E["Continue"] D --> E style B fill:#f59e0b,stroke:#d97706,color:#fff,stroke-width:2px style C fill:#10b981,stroke:#059669,color:#fff,stroke-width:2px
# Python: colon + indentation (no braces!)
temperature = 35

if temperature > 30:
    print("It's hot outside!")
    print("Stay hydrated!")

print("This always runs — it's outside the if block")
// JavaScript: parentheses around condition + curly braces
let temperature = 35;

if (temperature > 30) {
    console.log("It's hot outside!");
    console.log("Stay hydrated!");
}

console.log("This always runs — it's outside the if block");
// C#: same as JavaScript — parentheses + curly braces
int temperature = 35;

if (temperature > 30)
{
    Console.WriteLine("It's hot outside!");
    Console.WriteLine("Stay hydrated!");
}

Console.WriteLine("This always runs — it's outside the if block");

Syntax Differences at a Glance

Feature 🐍 Python ⚡ JavaScript 🔷 C#
Parentheses around condition Optional (not idiomatic) Required Required
Code block defined by Colon + indentation Curly braces {} Curly braces {}
Semicolons None After each statement After each statement

if / else

Add an else block to handle the case when the condition is false:

age = 16

if age >= 18:
    print("You can vote!")
else:
    print(f"You can vote in {18 - age} year(s).")
let age = 16;

if (age >= 18) {
    console.log("You can vote!");
} else {
    console.log(`You can vote in ${18 - age} year(s).`);
}
int age = 16;

if (age >= 18)
{
    Console.WriteLine("You can vote!");
}
else
{
    Console.WriteLine($"You can vote in {18 - age} year(s).");
}

Chained Conditions (elif / else if)

When you need to check multiple conditions, chain them together. The first true condition wins — the rest are skipped.

graph TD A["Score = 85"] --> B{"score >= 90?"} B -->|No| C{"score >= 80?"} B -->|Yes| D["Grade: A"] C -->|No| E{"score >= 70?"} C -->|Yes| F["Grade: B ✓"] E -->|No| G["Grade: F"] E -->|Yes| H["Grade: C"] style F fill:#10b981,stroke:#059669,color:#fff,stroke-width:2px
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score} → Grade: {grade}")  # Score: 85 → Grade: B
let score = 85;
let grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}

console.log(`Score: ${score} → Grade: ${grade}`);
int score = 85;
string grade;

if (score >= 90)
{
    grade = "A";
}
else if (score >= 80)
{
    grade = "B";
}
else if (score >= 70)
{
    grade = "C";
}
else if (score >= 60)
{
    grade = "D";
}
else
{
    grade = "F";
}

Console.WriteLine($"Score: {score} → Grade: {grade}");

⚠️ Python's elif vs. else if

Python uses the unique keyword elif (one word). JavaScript and C# use else if (two words). Writing else if in Python is a syntax error. Writing elif in JS or C# is also an error. Watch out when switching between languages!

Indentation vs. Braces

This is one of the biggest visible differences between Python and the other two languages. It affects how you write every block of code.

# Python: indentation IS the code block
# The colon (:) starts the block
# Everything indented one level deeper belongs to the block

if True:
    print("Inside the if")     # ← indented: part of if
    print("Still inside")      # ← indented: part of if
print("Outside the if")        # ← not indented: NOT part of if

# WRONG — inconsistent indentation:
# if True:
#     print("line 1")
#   print("line 2")    # IndentationError!

# Use 4 spaces per level (Python convention)
// JavaScript: braces define the block
// Indentation is for readability only (not enforced)

if (true) {
    console.log("Inside the if");   // inside braces
    console.log("Still inside");    // inside braces
}
console.log("Outside the if");      // after closing brace

// This works but is UGLY (don't do this):
if (true) {
console.log("no indentation");
console.log("hard to read");
}

// Use 2 or 4 spaces per level (team preference)
// C#: braces define the block (same as JavaScript)
// C# convention: opening brace on its own line

if (true)
{
    Console.WriteLine("Inside the if");
    Console.WriteLine("Still inside");
}
Console.WriteLine("Outside the if");

// Alternate style (opening brace on same line):
// if (true) {
//     Console.WriteLine("Also valid");
// }
// Both styles work — be consistent within a project

💡 Why Python Uses Indentation

Python's creator believed that code should look the way it works. Since good programmers indent their code anyway, why not make the indentation mean something? This forces everyone to write readable code — there are no "ugly but valid" Python programs. The trade-off: a misplaced space can change your program's behavior.

🎓 Instructor Note: Delivery Guidance

This is a crucial section for true beginners. Show a side-by-side comparison where Python code has a subtle indentation bug (one line under-indented) that changes behavior. Then show the JS/C# equivalent where braces make the block boundary explicit. Have students configure their editors to show whitespace characters and set tab = 4 spaces. Most beginners' first Python bugs are indentation-related.

Comparison Operators

Comparison operators produce boolean values — they're how you build conditions.

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 3 < 5 True
>= Greater than or equal 5 >= 5 True
<= Less than or equal 3 <= 5 True
# Python: == compares values, 'is' compares identity
print(5 == 5.0)        # True (same value)
print(5 is 5.0)        # False (different types/objects)
print("hello" == "hello")  # True

# Python also lets you chain comparisons!
age = 25
print(18 <= age <= 65)  # True — is age between 18 and 65?
# This is unique to Python and very readable
// JavaScript: === (strict) vs == (loose) — ALWAYS use ===
console.log(5 === 5);      // true
console.log(5 === "5");    // false (different types)
console.log(5 == "5");     // true! (loose: converts, then compares)
console.log(0 == false);   // true! (loose equality strikes again)
console.log(0 === false);  // false (strict: different types)

// Rule: ALWAYS use === and !== in JavaScript
// The only exception: checking for null/undefined
console.log(null == undefined);   // true
console.log(null === undefined);  // false
// C#: == works correctly (no loose equality issue)
Console.WriteLine(5 == 5);          // True
// Console.WriteLine(5 == "5");     // Compile error! Can't compare
Console.WriteLine("hello" == "hello");  // True

// String comparison is case-sensitive by default
Console.WriteLine("Hello" == "hello");  // False

// Case-insensitive comparison:
Console.WriteLine(string.Equals("Hello", "hello",
    StringComparison.OrdinalIgnoreCase));  // True

Switch / Match Statements

When you need to check one value against many specific options, a switch (or match) statement is cleaner than a long chain of if/elif/else.

# Python 3.10+: match/case (structural pattern matching)
day = "Monday"

match day:
    case "Monday":
        print("Start of the work week")
    case "Friday":
        print("Almost weekend!")
    case "Saturday" | "Sunday":
        print("Weekend!")
    case _:
        print("Midweek day")

# The _ is the wildcard — matches anything (like 'default')
# The | means "or" — matches either pattern

# Before Python 3.10, use if/elif chains instead
// JavaScript: classic switch/case
let day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the work week");
        break;
    case "Friday":
        console.log("Almost weekend!");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Midweek day");
}

// WARNING: forgetting 'break' causes "fall-through"
// — execution continues into the next case!
// C#: switch with no fall-through (safer than JavaScript)
string day = "Monday";

switch (day)
{
    case "Monday":
        Console.WriteLine("Start of the work week");
        break;
    case "Friday":
        Console.WriteLine("Almost weekend!");
        break;
    case "Saturday":
    case "Sunday":
        Console.WriteLine("Weekend!");
        break;
    default:
        Console.WriteLine("Midweek day");
        break;
}

// C# switch expressions (modern, concise):
string message = day switch
{
    "Monday" => "Start of the work week",
    "Friday" => "Almost weekend!",
    "Saturday" or "Sunday" => "Weekend!",
    _ => "Midweek day"
};
Console.WriteLine(message);

⚠️ JavaScript's Fall-Through Trap

In JavaScript, if you forget the break statement, execution "falls through" to the next case. This is a common bug source. C# prevents this — it requires break (or return) after each case. Python's match/case doesn't have this problem at all.

The Ternary Operator

For simple if/else decisions that just pick between two values, all three languages have a compact one-line syntax:

# Python: value_if_true if condition else value_if_false
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

# Works in f-strings too:
print(f"You are {'old enough' if age >= 21 else 'too young'} to drink.")

# Don't nest ternaries — they get unreadable fast
# bad = "A" if x > 90 else "B" if x > 80 else "C"  # confusing!
// JavaScript: condition ? value_if_true : value_if_false
let age = 20;
let status = age >= 18 ? "adult" : "minor";
console.log(status);  // adult

// Works in template literals too:
console.log(`You are ${age >= 21 ? "old enough" : "too young"} to drink.`);

// Don't nest ternaries:
// let bad = x > 90 ? "A" : x > 80 ? "B" : "C";  // hard to read
// C#: same as JavaScript — condition ? true : false
int age = 20;
string status = age >= 18 ? "adult" : "minor";
Console.WriteLine(status);  // adult

// Works in interpolation:
Console.WriteLine($"You are {(age >= 21 ? "old enough" : "too young")} to drink.");

// Note: C# requires parentheses around ternary in interpolation

✅ When to Use the Ternary

Use the ternary for simple, short either/or assignments. If the logic is complex or either branch is more than a short expression, use a regular if/else. Code readability always wins over brevity.

Exercises

🏋️ Exercise 1: Grade Calculator

Objective: Write a program that converts a numeric score (0–100) to a letter grade with +/- modifiers.

  • 90–100: A, 80–89: B, 70–79: C, 60–69: D, below 60: F
  • Bonus: Add + and - modifiers (e.g., 87–89 = B+, 80–82 = B-)
✅ Solution
score = 87

if score >= 90:
    letter = "A"
elif score >= 80:
    letter = "B"
elif score >= 70:
    letter = "C"
elif score >= 60:
    letter = "D"
else:
    letter = "F"

# Add +/- modifier
if letter != "F":
    last_digit = score % 10
    if last_digit >= 7 or score >= 97:
        modifier = "+"
    elif last_digit <= 2 and score < 97:
        modifier = "-"
    else:
        modifier = ""
else:
    modifier = ""

print(f"Score: {score} → Grade: {letter}{modifier}")
# Score: 87 → Grade: B+
let score = 87;
let letter;

if (score >= 90) {
    letter = "A";
} else if (score >= 80) {
    letter = "B";
} else if (score >= 70) {
    letter = "C";
} else if (score >= 60) {
    letter = "D";
} else {
    letter = "F";
}

// Add +/- modifier
let modifier = "";
if (letter !== "F") {
    let lastDigit = score % 10;
    if (lastDigit >= 7 || score >= 97) {
        modifier = "+";
    } else if (lastDigit <= 2 && score < 97) {
        modifier = "-";
    }
}

console.log(`Score: ${score} → Grade: ${letter}${modifier}`);
int score = 87;
string letter;

if (score >= 90)
    letter = "A";
else if (score >= 80)
    letter = "B";
else if (score >= 70)
    letter = "C";
else if (score >= 60)
    letter = "D";
else
    letter = "F";

string modifier = "";
if (letter != "F")
{
    int lastDigit = score % 10;
    if (lastDigit >= 7 || score >= 97)
        modifier = "+";
    else if (lastDigit <= 2 && score < 97)
        modifier = "-";
}

Console.WriteLine($"Score: {score} → Grade: {letter}{modifier}");

🏋️ Exercise 2: Day Planner

Objective: Use a switch/match statement to print a suggested activity based on the day of the week.

  1. Store a day of the week in a variable
  2. Use switch/match to print a different activity for each day
  3. Group Saturday and Sunday together as "Relax and recharge!"
✅ Solution
day = "Wednesday"

match day:
    case "Monday":
        activity = "Team standup and planning"
    case "Tuesday":
        activity = "Deep focus work"
    case "Wednesday":
        activity = "Mid-week review"
    case "Thursday":
        activity = "Collaboration and pair programming"
    case "Friday":
        activity = "Code review and learning"
    case "Saturday" | "Sunday":
        activity = "Relax and recharge!"
    case _:
        activity = "Unknown day"

print(f"{day}: {activity}")
let day = "Wednesday";
let activity;

switch (day) {
    case "Monday":
        activity = "Team standup and planning";
        break;
    case "Tuesday":
        activity = "Deep focus work";
        break;
    case "Wednesday":
        activity = "Mid-week review";
        break;
    case "Thursday":
        activity = "Collaboration and pair programming";
        break;
    case "Friday":
        activity = "Code review and learning";
        break;
    case "Saturday":
    case "Sunday":
        activity = "Relax and recharge!";
        break;
    default:
        activity = "Unknown day";
}

console.log(`${day}: ${activity}`);
string day = "Wednesday";

string activity = day switch
{
    "Monday" => "Team standup and planning",
    "Tuesday" => "Deep focus work",
    "Wednesday" => "Mid-week review",
    "Thursday" => "Collaboration and pair programming",
    "Friday" => "Code review and learning",
    "Saturday" or "Sunday" => "Relax and recharge!",
    _ => "Unknown day"
};

Console.WriteLine($"{day}: {activity}");

🏋️ Exercise 3: Ticket Pricing

Objective: Calculate ticket price based on age and membership status.

  • Children (under 12): $5
  • Seniors (65+): $7
  • Adults: $12
  • Members get 20% off any price

Use variables for age and is_member, then print the final price.

✅ Solution
age = 30
is_member = True

if age < 12:
    price = 5.00
elif age >= 65:
    price = 7.00
else:
    price = 12.00

if is_member:
    price *= 0.80   # 20% discount

label = "Member" if is_member else "Non-member"
print(f"Age: {age} ({label})")
print(f"Ticket price: ${price:.2f}")
let age = 30;
let isMember = true;
let price;

if (age < 12) {
    price = 5.00;
} else if (age >= 65) {
    price = 7.00;
} else {
    price = 12.00;
}

if (isMember) {
    price *= 0.80;
}

let label = isMember ? "Member" : "Non-member";
console.log(`Age: ${age} (${label})`);
console.log(`Ticket price: $${price.toFixed(2)}`);
int age = 30;
bool isMember = true;
decimal price;

if (age < 12)
    price = 5.00m;
else if (age >= 65)
    price = 7.00m;
else
    price = 12.00m;

if (isMember)
    price *= 0.80m;

string label = isMember ? "Member" : "Non-member";
Console.WriteLine($"Age: {age} ({label})");
Console.WriteLine($"Ticket price: {price:C}");
🎓 Instructor Note: Delivery Guidance

The grade calculator (Exercise 1) is the must-do — it ties together if/elif/else chains with modular logic. Exercise 2 is great for contrasting switch syntax. Exercise 3 introduces the idea of compound conditions (two separate if blocks working together) which previews the next lesson on logical operators. If time is short, do Exercise 1 as a class and assign 2 and 3 as homework.

Summary

🎉 Key Takeaways

  • if statements run code only when a condition is true
  • else handles the false case; elif/else if chains multiple conditions
  • Python uses indentation for code blocks; JavaScript and C# use curly braces
  • Python says elif, JS/C# say else if — don't mix them up
  • switch/match is cleaner than long if/elif chains when checking one value against many options
  • JavaScript switch requires break to prevent fall-through; Python match and C# switch don't have this trap
  • The ternary operator is great for simple inline choices but bad for complex logic

🚀 What's Next?

You can now make decisions — but what about repeating actions? In the next lesson, we'll learn loops: for and while — the tools that let your code do boring repetitive work so you don't have to.

🎯 Quick Check

Question 1: What keyword does Python use for chaining conditions?

Question 2: What happens if you forget break in a JavaScript switch case?