Introduction to Loops and Iteration
Chapter 4: Loops and Iteration in Python
Welcome to Chapter 4! In the previous chapter, you learned how to make decisions in your code using conditional statements. Now, we will explore one of the most powerful concepts in programming: loops. Loops allow you to repeat a block of code multiple times, which is essential for automating repetitive tasks, processing collections of data, and building efficient programs.
What is a Loop?
A loop is a programming structure that repeats a set of instructions until a specific condition is met. Instead of writing the same code over and over, you can use a loop to do it for you. Think of it like a washing machine cycle: it repeats the same steps (wash, rinse, spin) until the timer ends.
Why Do We Need Loops?
Imagine you want to print numbers from 1 to 100. Without loops, you would have to write 100 print() statements. With a loop, you can do it in just a few lines. Loops are crucial for:
- Processing lists, files, or database records.
- Repeating actions until a user gives the correct input.
- Building games, simulations, and data analysis tools.
Types of Loops in Python
Python has two main types of loops: for loops and while loops. We will cover both in this chapter.
1. The for Loop
The for loop is used to iterate over a sequence (like a list, string, or range). It executes a block of code for each item in the sequence.
Basic Syntax:
for variable in sequence:
# code to execute for each item
Example 1: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Using range()
The range() function generates a sequence of numbers. It is very useful when you want to repeat an action a specific number of times.
for i in range(5):
print("Iteration number:", i)
Output:
Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
range(5) generates numbers from 0 to 4 (not 1 to 5). If you want to start from 1, use range(1, 6).
2. The while Loop
The while loop repeats a block of code as long as a condition is True. It is ideal when you don't know in advance how many times you need to repeat.
Basic Syntax:
while condition:
# code to execute while condition is True
Example 3: Counting down
count = 5
while count > 0:
print("Countdown:", count)
count = count - 1
print("Blast off!")
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!
while loop will eventually become False. Otherwise, you will create an infinite loop that never stops.
Common Loop Patterns
Here are some patterns you will use frequently:
- Accumulating a sum:
total = 0; for num in numbers: total += num - Finding an item:
for item in list: if item == target: print("Found") - User input validation:
while True: answer = input("Enter yes/no: "); if answer in ["yes","no"]: break
Breaking and Continuing
Python provides two special statements to control loops:
break: Exits the loop immediately.continue: Skips the rest of the current iteration and moves to the next one.
Example 4: Using break
for number in range(10):
if number == 5:
break
print(number)
Output:
0
1
2
3
4
Example 5: Using continue
for number in range(5):
if number == 2:
continue
print(number)
Output:
0
1
3
4
Common Mistakes and How to Avoid Them
- Infinite while loop: Forgetting to update the condition variable. Always ensure the condition will become
False. - Off-by-one errors: Forgetting that
range(n)goes from 0 to n-1. Userange(1, n+1)if you need 1 to n. - Modifying a list while iterating: This can cause unexpected behavior. Instead, iterate over a copy of the list.
Practical Code Example: Sum of User Inputs
Let's build a small program that asks the user for numbers and calculates the total. The loop stops when the user enters '0'.
total = 0
while True:
user_input = input("Enter a number (0 to stop): ")
if user_input == '0':
break
try:
number = float(user_input)
total += number
except ValueError:
print("Invalid input. Please enter a number.")
print("Total sum:", total)
Explanation:
- We use a
while Trueloop to keep asking for input. - If the user enters '0', we
breakout of the loop. - We use a
try-exceptblock to handle non-numeric input gracefully. - Finally, we print the total sum.
Practice Task
Write a Python program that does the following:
- Ask the user to enter 5 numbers (use a
forloop withrange(5)). - Store each number in a list.
- After collecting all numbers, use another loop to calculate and print the average of the numbers.
- If the user enters something that is not a number, print an error message and ask again for that specific input.
Hint: You can use a while loop inside the for loop to keep asking until a valid number is entered.
Once you complete this task, you will have a solid understanding of how loops work in Python. In the next chapter, we will learn about functions, which will help you organize your code into reusable blocks.
Loading ratings...