📋 Contents
By the end of this class session, students will be able to:
- Understand the concept and necessity of loops in programming.
- Use
forloops to iterate over sequences andrange(). - Use
whileloops for condition-based repetition. - Differentiate between
forandwhileloops and choose the appropriate one. - Recognize and avoid infinite loops.
- Understand the loop
elseclause and when it executes. - Solve practical problems using loops (factorial, prime, Fibonacci, sum of digits).
A loop is a programming construct that repeats a block of code multiple times. Loops are essential when you need to perform the same operation on multiple items or repeat an action until a condition is met.
Why do we need loops?
Without loops, if you wanted to print numbers 1 to 100, you would need 100 print() statements. With a loop, just 2 lines:
for i in range(1, 101):
print(i)
Types of Loops in Python
| Loop Type | When to Use |
|---|---|
for loop | When the number of iterations is known or you are iterating over a sequence |
while loop | When the number of iterations is unknown and depends on a condition |
break, continue, pass) are covered in the next two parts of this series.for Loop3.1 Definition
A for loop in Python iterates over a sequence (such as a list, tuple, string, dictionary, set, or range) and executes a block of code once for each item in the sequence.
3.2 Syntax
for variable in sequence:
statement(s)
- variable — takes the value of each item in the sequence, one at a time.
- sequence — any iterable object (list, tuple, string, range, etc.).
- The block is indented (usually 4 spaces).
3.3 How it Works
- Python picks the first item from the sequence and assigns it to the variable.
- The indented block executes.
- Python picks the next item, and so on.
- When the sequence is exhausted, the loop ends.
Conceptual Flowchart — for Loop
Fig 1. Flowchart of a for loop — iterate over each item until the sequence is exhausted.
3.4 The range() Function
The range() function is commonly used with for loops to generate a sequence of numbers.
| Syntax | Generates |
|---|---|
range(stop) | 0, 1, 2, ..., stop-1 |
range(start, stop) | start, start+1, ..., stop-1 |
range(start, stop, step) | start, start+step, ..., stop-1 |
range(5) # 0, 1, 2, 3, 4 range(1, 6) # 1, 2, 3, 4, 5 range(0, 10, 2) # 0, 2, 4, 6, 8 range(5, 0, -1) # 5, 4, 3, 2, 1
3.5 Example Programs — for Loop
Example 1: Print numbers 1 to 5
for i in range(1, 6):
print(i)
Example 2: Print each character of a string
word = "Python"
for ch in word:
print(ch)
Example 3: Sum of first N natural numbers
n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total = total + i
print("Sum of first", n, "natural numbers is:", total)
Example 4: Multiplication table
num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)
Example 5: Iterate over a list
fruits = ["apple", "banana", "cherry", "mango"]
for fruit in fruits:
print("I like", fruit)
Example 6: Factorial of a number
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n + 1):
fact = fact * i
print("Factorial of", n, "is", fact)
Example 7: Print even numbers from 1 to 20
for i in range(2, 21, 2):
print(i)
Example 8: for loop with else clause
The else block executes only if the loop completes normally (without hitting break).
for i in range(1, 5):
print(i)
else:
print("Loop completed successfully.")
while Loop4.1 Definition
A while loop repeats a block of code as long as a condition remains True. It is used when the number of iterations is not known in advance.
4.2 Syntax
while condition:
statement(s)
- The condition is checked before each iteration.
- If the condition is
True, the block executes. - If the condition is
False, the loop ends. - Important: The block must contain something that eventually makes the condition
False; otherwise, you get an infinite loop.
4.3 How it Works
- Evaluate the condition.
- If
True, execute the block. - Go back to step 1.
- If
False, exit the loop.
Conceptual Flowchart — while Loop
Fig 2. Flowchart of a while loop — condition checked before each iteration; body must update the variable.
4.4 Example Programs — while Loop
Example 9: Print numbers 0 to 4
n = 0
while n < 5:
print(n)
n += 1
Example 10: Sum of digits of a number
num = int(input("Enter a number: "))
temp = num
total = 0
while temp > 0:
digit = temp % 10
total = total + digit
temp = temp // 10
print("Sum of digits of", num, "is", total)
Example 11: Reverse a number
num = int(input("Enter a number: "))
temp = num
reverse = 0
while temp > 0:
digit = temp % 10
reverse = reverse * 10 + digit
temp = temp // 10
print("Reverse of", num, "is", reverse)
Example 12: Check whether a number is prime
num = int(input("Enter a number: "))
if num < 2:
print(num, "is not a prime number.")
else:
i = 2
is_prime = True
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
Example 13: Sentinel-controlled loop (sum until 0)
total = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total = total + num
num = int(input("Enter a number (0 to stop): "))
print("Total sum is:", total)
Example 14: while loop with else
n = 0
while n < 3:
print(n)
n += 1
else:
print("While loop ended normally.")
An infinite loop occurs when the condition of a while loop never becomes False.
Example: Infinite loop (do not run without break)
while True:
print("This will run forever!")
To stop it: Use Ctrl + C in the terminal, or include a break statement.
Useful infinite loop pattern with break
while True:
command = input("Enter command (quit to exit): ")
if command == "quit":
break
print("You entered:", command)
while True: with break pattern is very common for menu-driven programs and games.else ClauseBoth for and while loops can have an else block. The else block executes only if the loop completes normally (i.e., without hitting a break).
Syntax
for variable in sequence:
statement(s)
else:
statement(s) # executes if no break
Example 15: for-else with break
numbers = [10, 20, 30, 40, 50]
target = int(input("Enter number to search: "))
for num in numbers:
if num == target:
print(target, "found!")
break
else:
print(target, "not found.")
Example 16: while-else with break
n = 0
while n < 5:
print(n)
n += 1
else:
print("Loop ended normally (no break).")
for vs while| Feature | for Loop | while Loop |
|---|---|---|
| Best for | Iterating over a sequence | Repeating while a condition is True |
| Number of iterations | Usually known | Usually unknown |
| Initialization | Automatic via sequence | Manual (before the loop) |
| Update | Automatic | Manual (inside the loop) |
| Risk of infinite loop | Low | High (if condition never becomes False) |
| Common use | Lists, strings, range() | Menus, sentinel values, condition-based repetition |
| Mistake | Correction |
|---|---|
Forgetting to update the loop variable in while | Always update inside the loop |
Using = instead of == in condition | Use == for comparison |
| Incorrect indentation | Indent the loop body consistently |
| Infinite loop | Ensure condition eventually becomes False |
| Modifying a list while iterating | Iterate over a copy if needed |
Off-by-one errors in range() | Remember range(a, b) excludes b |
🔍 Activity 1 — Predict the Output
What will the following code print? Work it out on paper first, then verify.
for i in range(2, 8, 2):
print(i)
n = 5
while n > 0:
print(n)
n -= 2
🐛 Activity 2 — Debug the Code
Find and fix the error in the code below:
n = 5
while n > 0:
print(n)
print("Done")
Hint: What happens to n inside the loop?
✏️ Activity 3 — Write the Program
Write a Python program that:
- Accepts a number N from the user.
- Prints all even numbers from 1 to N using a
forloop. - Prints the sum of all odd numbers from 1 to N using a
whileloop.
- What is a loop? Why are loops used in programming?
- Differentiate between
forandwhileloops with suitable examples. - Explain the
range()function with all three forms. - What is an infinite loop? How can you avoid it?
- When does the
elseclause of a loop execute? - Write a Python program to print the multiplication table of a number using a
forloop. - Write a Python program to check whether a number is prime using a
whileloop. - Write a Python program to find the sum of digits of a number using a
whileloop. - Write a Python program to print the reverse of a number using a
whileloop. - Explain the difference between
for-elseandwhile-elsewith examples.
for LoopIterates over sequences; used when the number of iterations is known. Works with range(), lists, strings, tuples.while LoopRepeats while a condition is True; used when iterations are unknown. Must update the loop variable inside the body.range()Generates sequences: range(stop), range(start, stop), range(start, stop, step).break.elseExecutes only if the loop completes without hitting break. Useful for search operations.for for known iterations / sequences; while for unknown iterations / conditions.Gafoor I
Assistant Professor | Department of Mathematics | NAM College Kallikkandy
Teaching Note · Module III (b) · Loops in Python · Academic Year 2025–26