Chapter 6: Looping Structures
Learn how Python repeats instructions using for loops, while loops, range(), loop control statements, nested loops, and practical interactive examples.
print(i)
6.1 Chapter Overview
Looping structures allow a Python program to repeat instructions automatically. Instead of writing the same code many times, a loop can repeat the task for a specific number of times or while a condition remains true.
Loops are used in attendance systems, marks processing, menu-driven programs, billing systems, data analysis, automation scripts, games, and many real-world applications.
6.2 Chapter Objectives
- Understand the purpose of looping structures.
- Use for loops to repeat tasks for a fixed number of times.
- Use the range() function to generate number sequences.
- Use while loops to repeat tasks based on conditions.
- Apply loop control statements such as break and continue.
- Use nested loops for repeated patterns and grouped processing.
- Develop interactive Python applications using loops.
Learning Outcomes
- Write Python programs using for and while loops.
- Apply loops to process marks, totals, counters, and menus.
- Identify and prevent infinite loop errors.
- Create simple automation programs using repeated execution.
6.3 What is a Loop?
A loop is a programming structure that repeats a block of code. The repetition continues either for a fixed number of times or until a condition becomes false.
Fixed Repetition
Used when the number of repetitions is known. Example: print numbers from 1 to 10.
Condition-Based Repetition
Used when repetition depends on a condition. Example: repeat login until correct password is entered.
Automation
Loops help automate repeated work such as processing student records or calculating totals.
6.4 Why Loops are Important
Without loops, programmers must write repeated code manually. This makes programs longer, harder to maintain, and more likely to contain errors.
| Without Loop | With Loop |
|---|---|
| Repeated print statements must be written many times. | One print statement can be repeated automatically. |
| Program becomes long and difficult to update. | Program becomes shorter and easier to manage. |
| More chances of typing mistakes. | Less repeated code and better structure. |
6.5 The for Loop
A for loop is used when the programmer knows how many times a task should repeat. It is commonly used with lists, strings, and the range() function.
Syntax
for variable in sequence:
statement
Example: Print a Message 5 Times
for i in range(5):
print("Welcome to PDTC Python Programming")
Welcome to PDTC Python Programming
Welcome to PDTC Python Programming
Welcome to PDTC Python Programming
Welcome to PDTC Python Programming
Welcome to PDTC Python Programming
6.6 Understanding range()
The range() function generates a sequence of numbers. It is often used with for loops.
| Format | Meaning | Example Output |
|---|---|---|
| range(5) | Starts from 0 and stops before 5. | 0, 1, 2, 3, 4 |
| range(1, 6) | Starts from 1 and stops before 6. | 1, 2, 3, 4, 5 |
| range(2, 11, 2) | Starts from 2, stops before 11, increases by 2. | 2, 4, 6, 8, 10 |
Example
for number in range(1, 6):
print(number)
1
2
3
4
5
6.7 Looping Through a List
A for loop can repeat through each item in a list.
courses = ["Python", "AI", "Data Science", "Cyber Security"]
for course in courses:
print(course)
Python
AI
Data Science
Cyber Security
6.8 Calculating Total Marks with a for Loop
This example uses a loop to calculate total marks from a list.
marks = [80, 75, 90, 85]
total = 0
for mark in marks:
total = total + mark
print("Total Marks:", total)
Total Marks: 330
6.9 The while Loop
A while loop repeats a block of code as long as a condition is True. It is useful when the number of repetitions is not known in advance.
Syntax
while condition:
statement
Example: Print Numbers 1 to 5
number = 1
while number <= 5:
print(number)
number = number + 1
1
2
3
4
5
6.10 Infinite Loop
An infinite loop happens when the loop condition never becomes False. This causes the program to repeat forever.
Wrong Example
number = 1
while number <= 5:
print(number)
In this example, number is never increased, so the condition remains True forever.
Correct Example
number = 1
while number <= 5:
print(number)
number = number + 1
6.11 Loop Control Statements
Loop control statements change the normal flow of a loop.
| Statement | Purpose | Use Case |
|---|---|---|
| break | Stops the loop immediately. | Stop when correct password is entered. |
| continue | Skips the current loop cycle and moves to the next one. | Skip invalid data. |
| pass | Does nothing; used as a placeholder. | Keep empty block temporarily. |
Example using break
for number in range(1, 10):
if number == 5:
break
print(number)
1
2
3
4
Example using continue
for number in range(1, 6):
if number == 3:
continue
print(number)
1
2
4
5
6.12 Nested Loops
A nested loop means a loop inside another loop. Nested loops are commonly used for tables, patterns, grids, and repeated grouped data.
Example: Multiplication Table Pattern
for row in range(1, 4):
for column in range(1, 4):
print(row, column)
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
6.13 Interactive Example: Login Attempts
This example allows the user to enter a password until it is correct.
password = ""
while password != "pdtc123":
password = input("Enter password: ")
print("Login successful")
6.14 Interactive Example: Student Marks Entry
This program asks how many subject marks the user wants to enter, then calculates the total and average.
number_of_subjects = int(input("How many subjects? "))
total = 0
for i in range(number_of_subjects):
marks = float(input("Enter marks: "))
total = total + marks
average = total / number_of_subjects
print("Total Marks:", total)
print("Average Marks:", average)
How many subjects? 3
Enter marks: 80
Enter marks: 75
Enter marks: 85
Total Marks: 240.0
Average Marks: 80.0
6.15 Common Beginner Mistakes
| Mistake | Problem | Correction |
|---|---|---|
| Forgetting colon | for i in range(5) | for i in range(5): |
| Wrong indentation | Loop body not aligned properly. | Indent statements inside the loop. |
| Infinite while loop | Condition never becomes False. | Update loop variable inside the loop. |
| Wrong range ending | Expecting range(5) to print 1 to 5. | Use range(1, 6) to print 1 to 5. |
6.16 Hands-On Practice
Activity 1: Print Numbers
Create a Python program that prints numbers from 1 to 10 using a for loop.
Activity 2: Multiplication Table
Ask the user to enter a number and print its multiplication table from 1 to 12.
Activity 3: Total Marks Calculator
Ask the user how many subjects they have. Use a loop to input marks and calculate the total and average.
Mini Project: Menu-Driven Training System
Create a menu-driven Python program that repeatedly displays options such as: 1. Register Student, 2. View Course Fee, 3. Exit. The program should continue running until the user selects Exit.
6.17 Final Assessment Quiz
Answer the following questions. Correct Answer = +1 Mark Wrong Answer = -0.5 Mark
1. A loop is used to repeat a block of code.
2. A for loop is commonly used when the number of repetitions is known.
3. range(5) generates numbers from 1 to 5.
4. A while loop repeats while its condition is True.
5. An infinite loop happens when a loop condition never becomes False.
6. The break statement stops a loop immediately.
7. The continue statement skips the current loop cycle and moves to the next one.
8. A nested loop means one loop placed inside another loop.
9. Python does not require indentation inside a loop.
10. Loops can be used to calculate total and average marks from repeated user input.
Your Score: 0
Final Practical Assessment
Develop an interactive Python program named marks_loop_calculator.py. The program must ask how many subjects the student has, use a loop to collect marks, calculate total marks, calculate average marks, and display the final result clearly.
6.18 Chapter Summary
In this chapter, learners studied looping structures in Python. They learned how to repeat tasks using for loops and while loops, how to use range(), how to stop or skip loop cycles using break and continue, and how loops support automation in interactive Python applications.