for loops: doing the same thing for each item
Sorting a list of tickets means doing the same step for each one. A for loop runs a block once for every item, with a name that holds the current item.
tickets = [
"I was charged twice for one order",
"My parcel has not arrived",
"How do I change my password?",
]for ticket in tickets:
print("-", ticket)Read it as: for each item in tickets, call it ticket and run the indented lines. The name after for is yours to choose; a singular of the list's name is the usual habit.
Counting as you go
billing = 0
for ticket in tickets:
if "charged" in ticket or "refund" in ticket:
billing += 1
print("Billing tickets:", billing)billing += 1 is short for billing = billing + 1. The counter starts before the loop, grows inside it, and is printed after it, which is where the indentation of the last line matters.
Numbering the items
for number, ticket in enumerate(tickets, start=1):
print(f"{number}. {ticket}")enumerate hands the loop two things each time, a count and the item, and the loop names both.
Repeating a set number of times
for attempt in range(3):
print("attempt", attempt)range(3) gives 0, 1 and 2. You will use exactly this in lesson 28, to try a model call again when it fails.
- Count the tickets that contain
"parcel"as well. - Change
start=1tostart=100. - Move
print("Billing tickets:", billing)inside the loop by indenting it, and compare the output.
You understood something today that you didn't yesterday.