for & while Loops with range()
Why loops?
To print "Hello" 100 times we should not write 100 print statements. A loop repeats a block of code many times. Repeating is called iteration, and each repetition is one iteration. Python has two loops: for and while.
The for loop
for variable in sequence:
body # runs once for every itemfor i in range(5):
print('Hello', i)range() function
range(start, stop, step) generates numbers from start up to but not including stop, jumping by step. Defaults: start = 0, step = 1.
print(list(range(6))) # stop only print(list(range(2, 9))) # start, stop print(list(range(1, 20, 4))) # start, stop, step print(list(range(10, 0, -2))) # counting down print(list(range(5, 5))) # empty
Looping over strings and lists
A for loop can go directly over the items of any sequence.
for ch in 'INDIA':
print(ch, end=' ')
print()
for fruit in ['mango', 'kiwi', 'apple']:
print(fruit.upper())n = int(input('Table of: '))
for i in range(1, 11):
print(n, 'x', i, '=', n * i)Counters and accumulators
Two patterns appear in almost every loop program. A counter counts how many times something happens (count += 1). An accumulator collects a running total (total += n). Both must be initialised before the loop.
total = 0 # accumulator
count = 0 # counter
for n in range(1, 21):
if n % 3 == 0:
total += n
count += 1
print('Multiples of 3 up to 20:', count, '| Sum:', total)n = int(input('Enter N: '))
fact = 1
for i in range(1, n + 1):
fact *= i
print(n, '! =', fact)The while loop
initialise
while condition:
body
update # change something so the condition can become Falsei = 1
while i <= 5:
print('Round', i)
i += 1 # without this the loop never ends
print('Loop over, i =', i)The loop ends when the condition becomes False; notice i is 6 after the loop.
Digit programs with while
The % 10 / // 10 trick takes a number apart digit by digit. One program gives digit count, digit sum, reverse and palindrome check:
n = int(input('Enter a number: '))
digits, s, rev = 0, 0, 0
temp = n
while temp > 0:
d = temp % 10 # last digit
s += d
rev = rev * 10 + d
digits += 1
temp //= 10 # remove last digit
print('Digits:', digits, '| Sum:', s, '| Reverse:', rev)
print('Palindrome' if rev == n else 'Not a palindrome')| temp | d = temp % 10 | s | rev | temp // 10 |
|---|---|---|---|---|
| 12321 | 1 | 1 | 1 | 1232 |
| 1232 | 2 | 3 | 12 | 123 |
| 123 | 3 | 6 | 123 | 12 |
| 12 | 2 | 8 | 1232 | 1 |
| 1 | 1 | 9 | 12321 | 0 |
More solved programs
Fibonacci series (first 10 terms)
n = 10
a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a + b
print()Repeat until correct (a while loop with input)
password = ''
while password != 'cbse2026':
password = input('Password: ')
print('Welcome!')for vs while
for
- Number of repetitions known
- Goes over range() or a sequence
- Loop variable updates automatically
- Example: print table, sum of list
while
- Repeat until a condition changes
- You must update the variable yourself
- Risk of infinite loop
- Example: digits of a number, menu, password
Summary & practice
for x in sequence;range(start, stop, step)stops before stop.while conditionneeds initialisation and update.- Counter:
count += 1; accumulator:total += x. n % 10= last digit,n // 10= remove last digit.
1) How many times does for i in range(3, 30, 3) run? 2) Print all even numbers from 50 down to 40. 3) Find the sum of the series 1 + 1/2 + 1/3 + … + 1/n. 4) Check whether a number is an Armstrong number (153 = 1³ + 5³ + 3³).
Answers: 1) 9 times (3, 6, …, 27). 2) for i in range(50, 39, -2): print(i)
