Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

if, elif and else: making decisions

So far every line runs every time. An if statement runs some lines only when a condition is true, which is how a program starts reacting to a ticket.

Example
ticket = "I was charged twice for one order"

if "charged" in ticket:
    print("billing")
else:
    print("other")

The condition after if is anything that gives True or False. The colon starts a block, and the indented lines under it are the block.

Indentation is not decoration in Python. Four spaces is how Python knows which lines belong to the if and which to the else.

More than two choices

Example
ticket = "My parcel has not arrived".lower()

if "charged" in ticket or "refund" in ticket:
    category = "billing"
elif "parcel" in ticket or "arrived" in ticket:
    category = "shipping"
else:
    category = "other"

print(category)

Python checks the conditions from the top and runs the first block whose condition is true. The rest are skipped, even if they would also be true. else catches everything left.

or is true when either side is. and needs both. not flips True and False.

Comparing values

Example
priority = 4
repeat_customer = True

print(priority == 4)
print(priority != 4)
print(priority >= 3)

if priority >= 4 and repeat_customer:
    print("send to a person")

== asks whether two values are equal. != is not equal, and <, >, <=, >= compare sizes.

One = where two belong

Example
priority = 4
if priority = 4:
    print("urgent")

One = stores a value and two compare. Mixing them up is common enough that Python suggests the fix in the message.

Try it yourself
  • Add a branch that sets category to "account" when the ticket mentions a password.
  • Change the ticket to "I want a REFUND" without .lower() and see which branch runs.
  • Set repeat_customer = False and check that nothing prints.

Every expert started right here.