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:
if condition:
... # runs when condition is True
elif other_condition:
...
else:
... # runs when nothing above was TrueChoosing between two branches
ticket = "I was charged twice for one order"
if "charged" in ticket:
print("billing")
else:
print("other")billing
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
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)shipping
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
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")True False True send to a person
== asks whether two values are equal. != is not equal, and <, >, <=, >= compare sizes.
Writing one = where two belong
priority = 4
if priority = 4:
print("urgent") File "main.py", line 2
if priority = 4:
^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?One = stores a value and two compare. Mixing them up is common enough that Python suggests the fix in the message.
= vs ==
= | == | |
|---|---|---|
| Does | Stores a value under a name | Asks whether two values are equal |
| Gives back | Nothing | True or False |
| Example | priority = 4 | priority == 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.
if and elif is a decision. A ticket that says "refund for a parcel" matches both checks, and only the first one runs.Related
- Previous: Numbers and type conversion
- Next: Lists
- Reference: if Statements in the Python tutorial
- Add a branch that sets
categoryto"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, andsend to a personno longer does.
Little by little, you're building something great.