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

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

P6.2 Python range() Function for Counting Loops

Why. Sometimes you need numbers, not a list: days 1 to 30, months 1 to 12.

What. range(stop) gives 0 up to stop-1. range(start, stop) gives start up to stop-1. range(start, stop, step) jumps by step.

How.

Count with range

  1. Decide the first and last number.
  2. Add 1 to the last number (stop is not included).
  3. Use it in a for loop.

Worked example A — Count 1 to 5.

Step 1 — What we do. We print day numbers for a 5-day training.

Step 2 — Type and run this code.

for day in range(1, 6):
    print("Day", day)

Step 3 — Output you should see.

Day 1
Day 2
Day 3
Day 4
Day 5

Step 4 — What it means. range(1, 6) gives 1, 2, 3, 4, 5. The 6 is not included.

Worked example B — Grow savings each year.

Step 1 — What we do. A customer in Paris saves €1,000 at 5% interest for 3 years.

Step 2 — Type and run this code.

amount = 1000
for year in range(1, 4):
    amount = amount * 1.05
    print(f"Year {year}: €{amount:,.2f}")

Step 3 — Output you should see.

Year 1: €1,050.00
Year 2: €1,102.50
Year 3: €1,157.62

Step 4 — What it means. Each loop adds 5% to the new amount. This is compound interest, done by a loop.

Ravindra Bagale's Tip

Remember: the stop number is never included. range(1, 13) gives months 1 to 12.