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.
The for loop
A for loop takes items one by one from a sequence (string, list, tuple, range) and runs its body for each.
for city in ['Delhi', 'Mumbai', 'Chennai']:
print('Weather report for', city)
for ch in 'DATA':
print(ch, end='-')
print()range()
range(start, stop, step) produces numbers from start up to stop − 1, increasing by step. Only stop is compulsory.
print(list(range(5))) print(list(range(3, 8))) print(list(range(0, 50, 10))) print(list(range(5, 0, -1)))
Totals, averages and counts
The two most useful loop patterns in IP: an accumulator (total += value) and a counter (count += 1).
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)Loops with input
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)Nested loops
A loop inside another loop: for each round of the outer loop, the inner loop runs completely.
for i in range(1, 4):
for j in range(1, 4):
print(i, 'x', j, '=', i * j, end=' ')
print()Patterns and text charts
for i in range(1, 6):
print('#' * i)
for i in range(4, 0, -1):
print(str(i) * i)The same idea makes a quick "bar chart" in text — a preview of the charts you will draw with Matplotlib in Class XII:
sales = {'Mon': 12, 'Tue': 7, 'Wed': 15, 'Thu': 4}
for day in sales:
print(f'{day} {"█" * sales[day]} {sales[day]}')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.
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)
breakfor marks in [45, -3, 88, 120, 67]:
if marks < 0 or marks > 100:
continue # skip invalid entries
print('Valid marks:', marks)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.
whilerepeats on a condition;breakexits;continueskips.
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).
