Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Unit 2 – Python Programming  ·  Lesson 07

for Loop, range() & Nested Loops

Why repeat?

Data work is full of repetition: add the marks of 40 students, check the temperature of 365 days, print a bill line for each item. A loop repeats a block of statements, so the same code handles 4 items or 4 lakh items.

Starttotal = 0more items ?YesNoPrint totaltake next itemtotal = total + itemStop
The idea of a loop

The for loop

A for loop takes items one by one from a sequence (string, list, tuple, range) and runs its body for each.

Python
for city in ['Delhi', 'Mumbai', 'Chennai']:
    print('Weather report for', city)
for ch in 'DATA':
    print(ch, end='-')
print()
Weather report for Delhi Weather report for Mumbai Weather report for Chennai D-A-T-A-

range()

range(start, stop, step) produces numbers from start up to stop − 1, increasing by step. Only stop is compulsory.

Python
print(list(range(5)))
print(list(range(3, 8)))
print(list(range(0, 50, 10)))
print(list(range(5, 0, -1)))
[0, 1, 2, 3, 4] [3, 4, 5, 6, 7] [0, 10, 20, 30, 40] [5, 4, 3, 2, 1]
range(0, 50, 10) →00101202303404
Starts at 0, jumps by 10, stops before 50

Totals, averages and counts

The two most useful loop patterns in IP: an accumulator (total += value) and a counter (count += 1).

Python
temps = [31.5, 33.0, 29.8, 35.2, 34.1, 30.6, 32.4]   # one week
total = 0
hot_days = 0
for t in temps:
    total += t
    if t > 33:
        hot_days += 1
print('Average temperature:', round(total / len(temps), 2))
print('Days above 33 °C:', hot_days)
Average temperature: 32.37 Days above 33 °C: 2
Temperatures of the week28333843°CMonTueWedThuFriSatSun31.53329.835.234.130.632.4
Two days are above 33 °C

Loops with input

Python
n = int(input('How many students? '))
total = 0
for i in range(1, n + 1):
    m = int(input('Marks of student ' + str(i) + ': '))
    total += m
print('Class average =', total / n)
How many students? 3 Marks of student 1: 78 Marks of student 2: 92 Marks of student 3: 64 Class average = 78.0

Nested loops

A loop inside another loop: for each round of the outer loop, the inner loop runs completely.

Python
for i in range(1, 4):
    for j in range(1, 4):
        print(i, 'x', j, '=', i * j, end='   ')
    print()
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9

Patterns and text charts

Python
for i in range(1, 6):
    print('#' * i)
for i in range(4, 0, -1):
    print(str(i) * i)
# ## ### #### ##### 4444 333 22 1

The same idea makes a quick "bar chart" in text — a preview of the charts you will draw with Matplotlib in Class XII:

Python
sales = {'Mon': 12, 'Tue': 7, 'Wed': 15, 'Thu': 4}
for day in sales:
    print(f'{day} {"█" * sales[day]} {sales[day]}')
Mon ████████████ 12 Tue ███████ 7 Wed ███████████████ 15 Thu ████ 4

while, break and continue

A while loop repeats as long as a condition is True. break leaves a loop early; continue skips to the next round.

Python
n = 5
i = 1
while i <= n:
    print(i * i, end=' ')
    i += 1
print()
for x in range(1, 20):
    if x % 7 == 0:
        print('First multiple of 7:', x)
        break
1 4 9 16 25 First multiple of 7: 7
Python
for marks in [45, -3, 88, 120, 67]:
    if marks < 0 or marks > 100:
        continue                  # skip invalid entries
    print('Valid marks:', marks)
Valid marks: 45 Valid marks: 88 Valid marks: 67

Summary & practice

  • for item in sequence: repeats for each item; range(start, stop, step) excludes stop.
  • Accumulator and counter patterns give totals, averages and counts.
  • Nested loops: inner loop completes for each outer round.
  • while repeats on a condition; break exits; continue skips.
✅ Practice

1) Print the squares of numbers from 1 to 10. 2) Input the prices of 5 items and print the total and the costliest price. 3) Print this pattern: 1 / 1 2 / 1 2 3 / 1 2 3 4. 4) Count how many numbers between 1 and 100 are divisible by both 3 and 5.

Answer 4: 6 (15, 30, 45, 60, 75, 90).

Frequently Asked Questions

What does range(3, 8) produce?
The numbers 3, 4, 5, 6 and 7. The stop value 8 is not included.
How many times does a nested loop body run?
Outer repetitions × inner repetitions. Two loops of 3 each run the inner body 9 times.
What is the use of continue?
It skips the rest of the current iteration and goes to the next one, for example to ignore invalid data while processing a list.
← Class 11 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicLists in Python Your progress: 7 / 20 (35%) · Lesson 8 / 20 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free