Index Ai Academy
Phase 0 · Tools · Python core

Decisions with if/else

Compare values and choose what happens next.

About 20 minutes · Free lesson

Start this lesson

Why it matters

Programs earn their keep by reacting to data. Send a lead to sales or to a slower email series. Flag a campaign that's overspending. Retry an API call that failed. Decide whether a model's answer passed a check. Every test you'll run on an AI system later comes down to conditions like the ones in this lesson.

What you'll be able to do

  • Compare values with ==, !=, <, >, <= and >=
  • Run different code depending on a condition with if, elif and else
  • Combine conditions with and, or and not
  • Avoid the classic mistakes: = vs ==, indentation, and comparing floats

What it covers

  1. Comparisons give True or False
  2. if: run code only when something is true
  3. Combining conditions
  4. Classic mistakes
  5. Worked example: flag a campaign that needs attention
  6. Build a rule one case at a time
  7. A quick check before you run it

Comparisons give True or False

A comparison asks a yes-or-no question, like a light switch that's either on or off. The answer is a boolean: True or False.

OperatorAsksExampleResult
==equal?3 == 3True
!=not equal?"paused" != "active"True
< / >less / greater than?0.02 > 0.05False
<= / >=less / greater than or equal?5000 >= 5000True

Note the double equals. A single = stores a value. A double == compares two values.

spend = 1890
budget = 2000
print(spend > budget)
print(spend <= budget)
print("active" == "Active")    # text comparisons are case-sensitive
It runs right here in your browser, with nothing to install.

if: run code only when something is true

spend = 2150
budget = 2000

if spend > budget:
    print("Over budget!")
    print("Overspend:", spend - budget)

print("Check complete")

The pattern is: if, a condition, a colon, then the lines to run, indented by four spaces. Those indented lines are the block. Python runs the block only when the condition is True.

The print at the end isn't indented, so it isn't part of the block. It runs either way. Change spend to 1500 and run it again.

Indentation isn't decoration in Python. It's how Python knows which lines belong to the if.

else and elif

Think of a sorting machine at a post office. A letter goes down the first chute that fits, and never reaches the others.

else runs when the if condition is false. elif ("else if") adds more conditions in between. Python checks them top to bottom, and runs only the first block whose condition is true. Then it skips the rest.

Try it now

Watch which lines the highlight visits. The first condition is False, so Python moves to the elif. That one is True, so it runs and the else is skipped entirely. Try it again in your head with ctr = 0.01.

Quick check
What does this print?
score = 90
if score > 50:
    print("warm lead")
elif score > 80:
    print("hot lead")
else:
    print("cold lead")
  1. warm lead, then hot lead
  2. cold lead
  3. hot lead
  4. warm lead
Show the answer

warm lead

90 > 50 is True, so the first block prints warm lead and Python skips the rest, even though 90 > 80 is also True. Put the narrower condition (> 80) first.

Combining conditions

  • and is True only if both sides are true.
  • or is True if at least one side is true.
  • not flips True to False and back.
budget = 4500
country = "US"
employees = 40

if budget >= 3000 and country == "US":
    print("Route to sales")

if employees >= 500 or budget >= 10000:
    print("Enterprise account")
else:
    print("Not enterprise")

unsubscribed = False
if not unsubscribed:
    print("OK to email")

When a condition gets long, parentheses make it readable: if (budget >= 3000 and country == "US") or employees >= 500:.

Comparing text

== on strings is exact: capitals, spaces and punctuation all count. Data from forms and spreadsheets is messy, so tidy it first with the methods from the strings lesson. in checks whether one string appears inside another:

country = "  us "
subject = "Last chance: free shipping"

print(country == "US")
print(country.strip().upper() == "US")
print("free" in subject.lower())

Classic mistakes

Using = instead of ==. Python catches this one for you:

clicks = 100
if clicks = 100:
    print("Exactly 100")

Forgetting to indent. The block after a colon must be indented:

clicks = 100
if clicks > 50:
print("More than 50")

Comparing floats for exact equality. Remember that 0.1 + 0.2 is 0.30000000000000004. Compare rounded values, or check that the difference is tiny:

total = 0.1 + 0.2
print(total == 0.3)
print(round(total, 2) == 0.3)
print(abs(total - 0.3) < 0.000001)    # abs() gives the size of a number, ignoring its sign
Worked example

Worked example: flag a campaign that needs attention

Check a campaign's budget pacing (spend ÷ budget) and cost per acquisition, and print one recommendation.

name = "Retargeting - Display"
budget = 2000
spend = 1880
conversions = 88

pacing = spend / budget
cpa = spend / conversions

if pacing > 0.9 and cpa > 20:
    print(f"{name}: pause and review (spent {pacing:.0%}, CPA {cpa:.2f})")
elif pacing > 0.9:
    print(f"{name}: nearly out of budget")
else:
    print(f"{name}: on track")
In the lesson you can change this and run it.

The calculations come first, so the conditions read like the business rule: "nearly out of budget and expensive". The order of the branches matters. The combined, more specific condition goes first. If pacing > 0.9 alone came first, it would catch this campaign, and the stronger warning would never print. Change conversions to 120 (a CPA of about 15.67) and run it again to see the second branch.

Quick check
a = 5 and b = 0. Which condition is True?
  1. not a > 3
  2. a == 3
  3. a > 3 and b > 3
  4. a > 3 or b > 3
Show the answer

a > 3 or b > 3

or needs only one side to be true, and a > 3 is. With and, b > 3 being False makes the whole thing False.

Quick check
What does this print?
status = "Active "
if status == "active":
    print("running")
else:
    print("stopped")
  1. running
  2. stopped
  3. An error
  4. running, then stopped
Show the answer

stopped

"Active " has a capital A and a trailing space, so it isn't exactly "active". The comparison is False, so the else block prints stopped. Compare status.strip().lower() == "active" to get running.

Build a rule one case at a time

Real decisions have several cases, and the easy way to get them wrong is to write them all at once. Take a shipping rule: orders of $100 or more ship free, orders of $50 or more pay $5, and anything else pays $10.

Before you write any code, write the cases down as a small table, with the order value on the left and the answer on the right. Then turn the table into branches, starting with the strictest case.

order = 75

if order >= 100:
    shipping = 0
elif order >= 50:
    shipping = 5
else:
    shipping = 10

print(shipping)

Python checks the branches from top to bottom and runs the first one that's true. Then it skips the rest. So only one branch ever runs, even when several conditions are true. An order of 150 is above both 100 and 50, and it gets the first branch.

That's why order matters. Swap the first two conditions, and every order of 100 or more matches order >= 50 first. Free shipping can never happen, and Python won't warn you, because the code is perfectly legal. Put narrow conditions before broad ones.

Test the edges

Most bugs in conditions sit right on a boundary. Is an order of exactly $100 free? With >= it is. With > it isn't. The rule on your website and the rule in your code have to agree.

So when you test a condition, try a value on each side of every boundary, and the boundary itself: 49, 50, 51, 99, 100 and 101. Six quick checks catch more bugs than a hundred random ones. It's a habit professional testers rely on.

Text has its own edges. A customer who types Yes, yes or YES means the same thing, but none of those equals yes. Clean the text before you compare it: answer.strip().lower() == "yes".

Finally, watch your indentation. Python uses it to decide what belongs to each branch. A line indented under if only runs when the condition is true. The same line moved left always runs. When a program does something "even though the condition was false", this is the first place to look.

A quick check before you run it

Before running a new condition, say it out loud in plain English: "if the order is at least 100, shipping is free." If your sentence and your code don't match, the code is usually the one that's wrong. Reading >= as "at least", and > as "more than", catches many boundary mistakes before they happen.

Practice what you just read

  • 9 code examples you can edit and run
  • a practice exercise that checks your code
  • a 6-question quiz
  • 5 review cards for spaced repetition

Start this lesson

Try a quiz question

What does this print?

print(0.1 + 0.2 == 0.3)
  1. False
  2. True
  3. 0.3
  4. An error

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson