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

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.

Examplethe tickets from lesson 6
tickets = [
    "I was charged twice for one order",
    "My parcel has not arrived",
    "How do I change my password?",
]
Example
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

Example
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

Example
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

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

Try it yourself
  • Count the tickets that contain "parcel" as well.
  • Change start=1 to start=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.