Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔁 Unit 2 – Flow of Control & Functions  ·  Lesson 16

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.

🔁
for loopRepeat for each item of a sequence or a fixed number of times.
⏳
while loopRepeat as long as a condition remains True.
Two kinds of loops

The for loop

Syntax
for variable in sequence:
    body   # runs once for every item
Python
for i in range(5):
    print('Hello', i)
Hello 0 Hello 1 Hello 2 Hello 3 Hello 4
i takes →01st1234last
range(5) gives 0 to 4 — five values, so the body runs five times

range() function

range(start, stop, step) generates numbers from start up to but not including stop, jumping by step. Defaults: start = 0, step = 1.

Python
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
[0, 1, 2, 3, 4, 5] [2, 3, 4, 5, 6, 7, 8] [1, 5, 9, 13, 17] [10, 8, 6, 4, 2] []
range(1, 20, 4) →105192133174
Start at 1, add 4 each time, stop before 20

Looping over strings and lists

A for loop can go directly over the items of any sequence.

Python
for ch in 'INDIA':
    print(ch, end=' ')
print()
for fruit in ['mango', 'kiwi', 'apple']:
    print(fruit.upper())
I N D I A MANGO KIWI APPLE
Python
n = int(input('Table of: '))
for i in range(1, 11):
    print(n, 'x', i, '=', n * i)
Table of: 7 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70

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.

Python
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)
Multiples of 3 up to 20: 6 | Sum: 63
Python
n = int(input('Enter N: '))
fact = 1
for i in range(1, n + 1):
    fact *= i
print(n, '! =', fact)
Enter N: 6 6 ! = 720

The while loop

Syntax
initialise
while condition:
    body
    update   # change something so the condition can become False
Starti = 1i <= 5 ?YesNoPrint "Loop over"Print "Round", ii = i + 1Stop
How the while loop below runs
Python
i = 1
while i <= 5:
    print('Round', i)
    i += 1               # without this the loop never ends
print('Loop over, i =', i)
Round 1 Round 2 Round 3 Round 4 Round 5 Loop over, i = 6

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:

Python
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')
Enter a number: 12321 Digits: 5 | Sum: 9 | Reverse: 12321 Palindrome
tempd = temp % 10srevtemp // 10
123211111232
12322312123
1233612312
122812321
119123210
Trace table for n = 12321

More solved programs

Fibonacci series (first 10 terms)

Python
n = 10
a, b = 0, 1
for i in range(n):
    print(a, end=' ')
    a, b = b, a + b
print()
0 1 1 2 3 5 8 13 21 34

Repeat until correct (a while loop with input)

Python
password = ''
while password != 'cbse2026':
    password = input('Password: ')
print('Welcome!')
Password: hello Password: cbse2025 Password: cbse2026 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
Choose the right loop

Summary & practice

  • for x in sequence; range(start, stop, step) stops before stop.
  • while condition needs initialisation and update.
  • Counter: count += 1; accumulator: total += x.
  • n % 10 = last digit, n // 10 = remove last digit.
✅ Practice

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)

Frequently Asked Questions

What does range(1, 10, 2) produce?
The numbers 1, 3, 5, 7, 9. It starts at 1, stops before 10 and increases by 2 each time.
When should I use while instead of for?
Use for when you know how many times to repeat or are going through a sequence. Use while when you repeat until a condition changes, like asking for a password until it is correct or processing digits until the number becomes 0.
What is an infinite loop?
A loop whose condition never becomes False, for example while i <= 5 when i is never increased. Press Ctrl + C to stop it.
← Class 11 Computer Science
🔗

Share this topic with a friend

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

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

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

Next topicbreak, continue & Nested Loops Your progress: 16 / 29 (55%) · Lesson 17 / 29 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