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

if, elif and else

An if statement is a block of code that runs only when its condition is true, with elif and else for the other cases.

Last updated: 30 Sep, 2026 · Python 3.14

So far every line has run every time. An if lets the program react to what a ticket says, using the in check from Strings.

Syntax:

python
if condition:
    ...            # runs when condition is True
elif other_condition:
    ...
else:
    ...            # runs when nothing above was True

Choosing between two branches

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 how Python reads the structure. Four spaces tell it which lines belong to the if and which to the else.

Adding more choices with elif

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.

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

= vs ==

===
DoesStores a value under a nameAsks whether two values are equal
Gives backNothingTrue or False
Examplepriority = 4priority == 4

Where if statements show up in AI code

  • Routing a ticket to billing, shipping or a person.
  • Checking a model's reply before acting on it, and doing something else when it is wrong.
Watch out. The order of if and elif is a decision. A ticket that says "refund for a parcel" matches both checks, and only the first one runs.
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.
  • In the comparing example, set repeat_customer = False. The three comparisons still print, and send to a person no longer does.

Little by little, you're building something great.