Ravindra BagaleCourses & study guides मराठी Track your progress

Python for Loops and while Loops Explained with Examples (range, break, continue)

P6.1 How a for Loop Works in Python

Why. You have 500 invoices and must check each one. Writing 500 lines is impossible. A loop writes it once and repeats it.

What. for item in collection: takes each item one by one and runs the indented block for it.

How.

Write a for loop

  1. Write for, a name for one item, in, the list, and a colon.
  2. Indent the work to repeat.
  3. Use the item name inside the block.
1. Take the next item2. Run the indented block3. More items? Go back to 14. No more items → loop ends
One for loop, step by step (read from top to bottom)

Worked example A — Print each item.

Step 1 — What we do. A store in Kraków has three branches.

Step 2 — Type and run this code.

branches = ["Old Town", "Kazimierz", "Podgorze"]
for b in branches:
    print("Branch:", b)

Step 3 — Output you should see.

Branch: Old Town
Branch: Kazimierz
Branch: Podgorze

Step 4 — What it means. The block ran 3 times, once per branch. b holds the current item.

Worked example B — Add up with a loop.

Step 1 — What we do. We total daily sales manually to see how sum works inside.

Step 2 — Type and run this code.

sales = [1200, 950, 1430]
total = 0
for s in sales:
    total = total + s
print(total)

Step 3 — Output you should see.

3580

Step 4 — What it means. Start at 0, add each value. The result 3580 is the same as sum(sales).

Worked example C — Loop over a string.

Step 1 — What we do. We count the digits in a phone number field.

Step 2 — Type and run this code.

phone = "+44 20 7946 0958"
digits = 0
for ch in phone:
    if ch.isdigit():
        digits += 1
print(digits)

Step 3 — Output you should see.

12

Step 4 — What it means. A string is a sequence of characters, so a loop visits each one. += 1 is short for "add 1".

Python next to other languages — loop over a list. You do not need to learn these other languages. This only shows why Python is easier to read.

Language Code
Python for b in branches: print(b)
Java for (String b : branches) { System.out.println(b); }
JavaScript for (const b of branches) { console.log(b); }
Go for _, b := range branches { fmt.Println(b) }

Ravindra Bagale's Tip

Name the loop variable as the singular of the list: for order in orders, for city in cities. The code reads like English.