IG

IG Math Space

Mathematics Teaching and Research

📚 Classroom Space · Teaching Note

Loops in Python

Module III — Flow Control (b) · A comprehensive classroom teaching note on for loops, while loops, range(), infinite loops and loop else clauses.

👨‍🏫 Gafoor I 🏛️ NAM College Kallikkandy 📐 Department of Mathematics 📘 Taming Python by Programming

📋 Contents

  1. Learning Objectives
  2. Introduction to Loops
  3. The for Loop
  4. The while Loop
  5. Infinite Loops
  6. Loop else Clause
  7. Comparison: for vs while
  8. Common Mistakes
  9. Classroom Activities
  10. Review Questions
  11. Summary
01 Learning Objectives

By the end of this class session, students will be able to:

  • Understand the concept and necessity of loops in programming.
  • Use for loops to iterate over sequences and range().
  • Use while loops for condition-based repetition.
  • Differentiate between for and while loops and choose the appropriate one.
  • Recognize and avoid infinite loops.
  • Understand the loop else clause and when it executes.
  • Solve practical problems using loops (factorial, prime, Fibonacci, sum of digits).
02 Introduction to Loops

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)
1 2 3 ... 100

Types of Loops in Python

Loop TypeWhen to Use
for loopWhen the number of iterations is known or you are iterating over a sequence
while loopWhen the number of iterations is unknown and depends on a condition
💡 Note: Nested loops and control statements (break, continue, pass) are covered in the next two parts of this series.
03 The for Loop

3.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

  1. Python picks the first item from the sequence and assigns it to the variable.
  2. The indented block executes.
  3. Python picks the next item, and so on.
  4. When the sequence is exhausted, the loop ends.

Conceptual Flowchart — for Loop

Start Sequence Exhausted? Yes End No Get Next Item Process Item 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.

SyntaxGenerates
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)
1 2 3 4 5

Example 2: Print each character of a string

word = "Python"
for ch in word:
    print(ch)
P y t h o n

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)
Enter N: 5 Sum of first 5 natural numbers is: 15

Example 4: Multiplication table

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(num, "x", i, "=", num * i)
Enter a number: 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

Example 5: Iterate over a list

fruits = ["apple", "banana", "cherry", "mango"]
for fruit in fruits:
    print("I like", fruit)
I like apple I like banana I like cherry I like mango

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)
Enter a number: 5 Factorial of 5 is 120

Example 7: Print even numbers from 1 to 20

for i in range(2, 21, 2):
    print(i)
2 4 6 8 10 12 14 16 18 20

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.")
1 2 3 4 Loop completed successfully.
04 The while Loop

4.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

  1. Evaluate the condition.
  2. If True, execute the block.
  3. Go back to step 1.
  4. If False, exit the loop.

Conceptual Flowchart — while Loop

Start Condition True? No End Yes Execute Loop Body Loop Manual update in body!

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
0 1 2 3 4

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)
Enter a number: 1234 Sum of digits of 1234 is 10

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)
Enter a number: 1234 Reverse of 1234 is 4321

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.")
Enter a number: 17 17 is a prime number. Enter a number: 18 18 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)
Enter a number (0 to stop): 10 Enter a number (0 to stop): 20 Enter a number (0 to stop): 5 Enter a number (0 to stop): 0 Total sum is: 35

Example 14: while loop with else

n = 0
while n < 3:
    print(n)
    n += 1
else:
    print("While loop ended normally.")
0 1 2 While loop ended normally.
05 Infinite Loops

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!")
This will run forever! This will run forever! This will run forever! ... (continues indefinitely — press Ctrl+C to stop)

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)
Enter command (quit to exit): hello You entered: hello Enter command (quit to exit): python You entered: python Enter command (quit to exit): quit
Tip: The while True: with break pattern is very common for menu-driven programs and games.
06 Loop else Clause

Both 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.")
Enter number to search: 30 30 found! Enter number to search: 99 99 not found.

Example 16: while-else with break

n = 0
while n < 5:
    print(n)
    n += 1
else:
    print("Loop ended normally (no break).")
0 1 2 3 4 Loop ended normally (no break).
07 Comparison: for vs while
Featurefor Loopwhile Loop
Best forIterating over a sequenceRepeating while a condition is True
Number of iterationsUsually knownUsually unknown
InitializationAutomatic via sequenceManual (before the loop)
UpdateAutomaticManual (inside the loop)
Risk of infinite loopLowHigh (if condition never becomes False)
Common useLists, strings, range()Menus, sentinel values, condition-based repetition
08 Common Mistakes to Avoid
MistakeCorrection
Forgetting to update the loop variable in whileAlways update inside the loop
Using = instead of == in conditionUse == for comparison
Incorrect indentationIndent the loop body consistently
Infinite loopEnsure condition eventually becomes False
Modifying a list while iteratingIterate over a copy if needed
Off-by-one errors in range()Remember range(a, b) excludes b
09 Classroom Activities

🔍 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 for loop.
  • Prints the sum of all odd numbers from 1 to N using a while loop.
10 Review Questions
  1. What is a loop? Why are loops used in programming?
  2. Differentiate between for and while loops with suitable examples.
  3. Explain the range() function with all three forms.
  4. What is an infinite loop? How can you avoid it?
  5. When does the else clause of a loop execute?
  6. Write a Python program to print the multiplication table of a number using a for loop.
  7. Write a Python program to check whether a number is prime using a while loop.
  8. Write a Python program to find the sum of digits of a number using a while loop.
  9. Write a Python program to print the reverse of a number using a while loop.
  10. Explain the difference between for-else and while-else with examples.
11 Summary
🔁
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).
⚠️
Infinite LoopsOccur when the condition never becomes False. Avoid unless intentional with a break.
🔚
Loop elseExecutes only if the loop completes without hitting break. Useful for search operations.
🧭
Choosing a LoopUse for for known iterations / sequences; while for unknown iterations / conditions.
G

Gafoor I

Assistant Professor  |  Department of Mathematics  |  NAM College Kallikkandy

Teaching Note · Module III (b) · Loops in Python · Academic Year 2025–26