Both loops repeat a block of code. But they do it differently, and choosing the wrong one wastes lines of code — or worse, crashes your program. This guide explains the difference clearly, with every program type that appears across Class 9 to 12 practicals.
What You’ll Learn
- What a loop is and why Python has two kinds
- The exact difference between
forandwhile— with the one-line rule - All common loop patterns for CBSE practical programs
break,continue, andrange()explained with examples
The One-Line Rule
Use for when you know exactly how many times to repeat. Use while when you repeat until a condition changes.
That is the entire decision. Everything below is application of this rule.
Part 1 — The for Loop
A for loop repeats a block of code for each item in a sequence — a list, a string, a range of numbers, or any iterable.
Syntax
python
for variable in sequence:
# code to repeat
The variable takes each value from the sequence one at a time. The loop runs once for each value.
With range()
range() is the most common companion to for loops. It generates a sequence of numbers without storing them all in memory.
python
# Program to print first 10 natural numbers using for loop
for i in range(1, 11): # 1 to 10 (stops before 11)
print(i, end=" ")
print() # new line after all numbers
Expected Output:
1 2 3 4 5 6 7 8 9 10
range() patterns:
| Call | Generates | Use Case |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Loop n times |
range(1, 6) | 1, 2, 3, 4, 5 | Loop from 1 to n |
range(1, 11, 2) | 1, 3, 5, 7, 9 | Step size of 2 (odd numbers) |
range(10, 0, -1) | 10, 9, 8 … 1 | Count down |
Common CBSE For Loop Programs
python
# Program to print first 10 even numbers
print("First 10 even numbers:")
for i in range(2, 21, 2): # start=2, stop=21, step=2
print(i, end=" ")
print()
Output: 2 4 6 8 10 12 14 16 18 20
python
# Program to find the sum of first 10 natural numbers
total = 0
for i in range(1, 11):
total += i # same as: total = total + i
print("Sum of first 10 natural numbers:", total)
Output: Sum of first 10 natural numbers: 55
python
# Program to find the sum of all numbers stored in a list
numbers = [12, 45, 7, 23, 56, 89, 34]
total = 0
for num in numbers:
total += num
print("Sum of list:", total)
print("Verified with sum():", sum(numbers)) # built-in check
Output:
Sum of list: 266
Verified with sum(): 266
Iterating Over a String
python
# Program to count vowels in a word using for loop
word = "Artificial"
vowels = "aeiouAEIOU"
count = 0
for char in word:
if char in vowels:
count += 1
print(f"Vowels in '{word}':", count)
Output: Vowels in 'Artificial': 5
Part 2 — The while Loop
A while loop repeats a block of code as long as a condition is True. It keeps checking the condition at the start of every iteration. When the condition becomes False, the loop stops.
Syntax
python
while condition:
# code to repeat
# must eventually make condition False
⚠️ Critical rule: Something inside the loop must change the condition — otherwise the loop runs forever (an infinite loop) and freezes your program. Always include an update statement like n += 1 or count -= 1.
Basic While Loop
python
# Program to print first 10 natural numbers using while loop
n = 1
while n <= 10:
print(n, end=" ")
n += 1 # without this line → infinite loop
print()
Output: 1 2 3 4 5 6 7 8 9 10
Common CBSE While Loop Programs
python
# Program to print odd numbers from 1 to n
n = int(input("Enter value of n: "))
i = 1
while i <= n:
if i % 2 != 0:
print(i, end=" ")
i += 1
print()
Output (if n = 15): 1 3 5 7 9 11 13 15
python
# Program to find factorial of a number using while loop
number = int(input("Enter a positive integer: "))
factorial = 1
n = number
while n > 0:
factorial *= n # same as: factorial = factorial * n
n -= 1
print(f"Factorial of {number} is: {factorial}")
Output (if user enters 5): Factorial of 5 is: 120
python
# Program to check if a person can vote (using while for repeated input)
while True:
age = int(input("Enter age: "))
if age < 0:
print("Invalid age. Try again.")
elif age >= 18:
print("You are eligible to vote.")
break
else:
print("You are not yet eligible to vote.")
break
This pattern — while True with a break — is used when you want to keep accepting input until the user provides a valid value.
Part 3 — For vs While: Same Task, Both Ways
Seeing the same program written both ways makes the difference concrete.
Print numbers 1 to 5
python
# Using for loop
for i in range(1, 6):
print(i, end=" ")
# Using while loop
i = 1
while i <= 5:
print(i, end=" ")
i += 1
Both produce: 1 2 3 4 5
The for version is shorter and cleaner when you know the count. The while version requires you to initialise i before the loop and increment it inside — three lines of work instead of one.
Part 4 — break and continue
break — Exit the Loop Early
python
# Program to find the first number divisible by 7 in a list
numbers = [12, 15, 21, 34, 49, 63, 77]
for num in numbers:
if num % 7 == 0:
print("First number divisible by 7:", num)
break # stop as soon as we find it
Output: First number divisible by 7: 21
continue — Skip This Iteration
python
# Program to print all numbers from 1 to 10 except multiples of 3
for i in range(1, 11):
if i % 3 == 0:
continue # skip this i, go to next iteration
print(i, end=" ")
print()
Output: 1 2 4 5 7 8 10
Part 5 — Nested Loops
A loop inside another loop. The inner loop completes all its iterations for every single iteration of the outer loop.
python
# Program to print a multiplication table using nested loops
for i in range(1, 4): # outer loop: rows
for j in range(1, 6): # inner loop: columns
print(f"{i*j:4}", end="")
print() # new line after each row
Expected Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Nested loops are commonly used in Class 11 and 12 for processing 2D arrays (matrices) row by row.
For vs While — Comparison Table
| Feature | for loop | while loop |
|---|---|---|
| Best for | Known number of repetitions | Unknown number — repeats until condition |
| Requires initialisation? | No | Yes — set counter before loop |
| Requires update statement? | No | Yes — must change condition inside loop |
| Works with sequences? | ✅ Directly | ✅ With index variable |
| Risk of infinite loop? | Very low | High if update statement is missing |
| CBSE example | Print first 10 natural numbers | Check voting eligibility with retry |
Quick Revision Box
| Concept | Explanation |
|---|---|
for i in range(n) | Repeats n times; i goes 0, 1, 2 … n-1 |
for i in range(a, b) | Repeats from a to b-1 |
for i in range(a, b, s) | Step size s; can be negative for countdown |
for x in list | Iterates directly over list elements |
while condition | Repeats while condition is True |
break | Exits the loop immediately |
continue | Skips remaining code in current iteration, goes to next |
| Infinite loop | while True without a break — freezes program |
| Nested loop | A loop inside another loop |
Practice Questions
Q1 (2 marks): Write a Python program to print odd numbers from 1 to 15 using a for loop.
Model Answer:
python
for i in range(1, 16, 2):
print(i, end=" ")
Output: 1 3 5 7 9 11 13 15
Q2 (MCQ): What is the output of the following code?
python
for i in range(2, 10, 3):
print(i, end=" ")
a) 2 5 8 11 b) 2 5 8 c) 2 3 4 5 6 7 8 9 d) 2 4 6 8
Answer: b) 2 5 8 — range(2, 10, 3) starts at 2, adds 3 each time: 2, 5, 8. The next would be 11 but that is ≥ 10, so the loop stops.
Frequently Asked Questions
Q1: Can I use a for loop to do everything a while loop does? Technically yes — but it creates unnecessarily complex code. When the number of repetitions is unknown (e.g., keep asking for valid input, keep reading sensor data until a threshold), while is cleaner and more readable. Use the right tool for the job.
Q2: What happens if I forget n += 1 inside a while loop? The condition never becomes False, so the loop runs forever — this is called an infinite loop. In Jupyter Notebook, the cell shows [*] permanently and the kernel freezes. Fix: press the ■ Stop button in the toolbar, then add the missing update statement.
Q3: Is for or while more common in CBSE AI practical programs? for loops dominate in CBSE practical programs because most tasks involve a known count — print first N numbers, iterate over a list, repeat for each element in an array. while appears in programs that check conditions — voting eligibility checks, input validation, and occasionally in Class 11 algorithm demonstrations like binary search.