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.
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
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
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
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.
- 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. - Set
repeat_customer = Falseand check that nothing prints.
Every expert started right here.