Day 6 · ~13m

Python if/else: Branch Logic and Conditional Output

An if/else statement in Python runs one block of code when a condition is true and a different block when false. Use elif for additional branches and conditions to control which code executes.

student (curious)

Hey Sam, the format_sale function we built yesterday works great with f-strings. But I just realized — every sale looks the same in the output. A $50 transaction gets the same formatting as a $50,000 one. That can't be what Diane wants for the report.

teacher (encouraging)

You caught the exact problem. Diane wants the big deals to stand out. We need to add a tier label based on the sale amount. That's where if/else comes in.

student (thinking)

If/else? Like... if the amount is big, do something different?

teacher (focused)

Exactly. An if/else statement in Python runs one block of code when a condition is true and a different block when it's false. The condition goes right after if, and Python uses a colon and indentation to know where each block begins and ends.

if amount >= 5000:
    tier = "⭐ VIP"
else:
    tier = "Standard"

Notice the colon after the condition and the indentation on the next line. That's how Python knows the tier assignment belongs inside the if block.

student (confused)

Wait, why no parentheses around amount >= 5000? In Excel, I'd write =IF(amount >= 5000, ...).

teacher (amused)

Great question. Many beginners think you need parentheses like if (amount > 1000). You don't — the colon alone marks the end of the condition. Python doesn't need those extra parentheses.

student (excited)

Okay, so what if I want three tiers instead of two? Like VIP, High Value, and Standard?

teacher (focused)

That's where elif comes in. elif means "else if" — you can chain conditions.

if amount >= 5000:
    tier = "⭐ VIP"
elif amount >= 1000:
    tier = "High Value"
else:
    tier = "Standard"

Python checks the conditions top to bottom. If amount is 6000, the first condition is true, so Python assigns "⭐ VIP" and skips the rest. If amount is 1500, the first is false, but the elif is true, so it assigns "High Value". If it's 300, both are false, so else runs.

student (proud)

So we just nest this logic inside format_sale and we're done?

teacher (encouraging)

Exactly. Update the function to check the amount and assign the tier, then include it in the f-string. Let's use {tier} right in the output.

student (excited)

So the output would be like Alice Chen [⭐ VIP]: $6800.00?

teacher (proud)

You've got it. That's the whole pattern. Right now format_sale handles one sale at a time. Tomorrow I'm going to give you a list of sales and you'll process all of them — without calling format_sale fifty times.