Back to Python
2026-02-269 min read

Loops or Iteration Statements (Python Programming)

Learn Loops or Iteration Statements (Python Programming) step by step with clear examples and exercises.

Why This Matters

Python loops are an essential part of programming that enable you to automate repetitive tasks, solve complex problems, and write more efficient code. In this guide, we will delve into the core concepts of Python's loop structures, providing worked examples, common mistakes, practice questions, and answers to frequently asked questions.

Why Loops Matter

  1. Efficiency: Loops help you write cleaner, more efficient code by allowing you to perform repetitive tasks without writing redundant code.
  2. Complex problem-solving: Loops enable you to break down complex problems into smaller, manageable parts that can be processed iteratively.
  3. Real-world applications: From data analysis and web development to artificial intelligence and game development, loops are used extensively in various fields of computer science.
  4. Debugging and testing: Loops help you test your code more effectively by allowing you to run specific sections multiple times until they produce the desired output.
  5. Readability: Loops can make your code easier to read and understand, as they group related statements together and reduce redundancy.

Prerequisites

Before diving into Python's loop structures, it is essential that you have a solid understanding of the following:

  1. Basic Python syntax and data types (e.g., variables, strings, lists)
  2. Control flow statements, such as if and elif
  3. Functions and their usage in Python
  4. Basic familiarity with the Python REPL (Read-Eval-Print Loop) for testing code snippets
  5. Understanding of list comprehensions and how they can be used to iterate over data
  6. Familiarity with Python's error handling, including exceptions and try/except blocks
  7. Understanding of common Python data structures like tuples, sets, and dictionaries
  8. Knowledge of Python modules, such as math and random, which can be used in combination with loops

Core Concept

Python provides several loop structures to iterate over data, including:

  1. for loops
  2. while loops
  3. The enumerate() function
  4. List comprehensions
  5. Generators

For Loops

The for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. Here's an example:

fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)

In this example, the for loop iterates over the fruits list and prints each item on a separate line.

Nested For Loops

Nested for loops allow you to iterate over multiple sequences simultaneously or perform nested iterations within a single sequence. Here's an example:

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for cell in row:
print(cell)

In this example, the outer for loop iterates over each row in the matrix, and the inner for loop iterates over each cell within that row.

While Loops

The while loop continues to execute as long as a specified condition is true. Here's an example:

i = 0
while i < 5:
print(i)
i += 1

In this example, the while loop prints the numbers from 0 to 4 (inclusive).

Infinite While Loops and Break Statements

It's essential to ensure that your while loop conditions are well-defined and will eventually become false, preventing an infinite loop. If you need to exit a while loop early, you can use the break statement:

i = 0
while True:
if i == 5:
break
print(i)
i += 1

In this example, the while loop will run indefinitely until the i variable reaches 5, at which point it will exit using the break statement.

Enumerate() Function

The built-in enumerate() function allows you to iterate over a sequence and access both the index and value of each item. Here's an example:

fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(i, fruit)

In this example, the enumerate() function returns a tuple containing the index and value of each item in the fruits list.

List Comprehensions

List comprehensions are a concise way to create lists based on existing data. Here's an example:

numbers = [1, 3, 4, 5, 6, 7, 8, 9]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers) # Output: [4, 6, 8]

In this example, the list comprehension creates a new list called even_numbers containing only the even numbers from the numbers list.

Nested List Comprehensions

Nested list comprehensions allow you to create multidimensional lists or perform nested iterations within a single list comprehension. Here's an example:

matrix = [
[i*j for j in range(1, 4)] for i in range(1, 4)
]
print(matrix)

In this example, the nested list comprehension creates a 2D matrix where each cell is the product of its row and column indices.

Generators

Generators are iterable objects that allow you to generate values on-the-fly without consuming memory for large datasets. Here's an example:

def fibonacci(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b

fib_sequence = fibonacci(20)
for number in fib_sequence:
print(number)

In this example, the fibonacci() function is a generator that yields Fibonacci numbers up to (but not including) the specified value. The for loop then iterates over the generated sequence and prints each number.

Worked Example

Let's consider a problem where we need to find the sum of all even numbers in a list, as well as the sum of all odd numbers. Here's how you can solve it using Python loops:

numbers = [1, 3, 4, 5, 6, 7, 8, 9]
even_sum = 0
odd_sum = 0

for number in numbers:
if number % 2 == 0:
even_sum += number
else:
odd_sum += number

print(f"Sum of even numbers: {even_sum}")
print(f"Sum of odd numbers: {odd_sum}")

In this example, the for loop iterates over the numbers list. For each number, the if statement checks if it is even (i.e., number % 2 == 0). If the condition is true, the number is added to the even_sum variable; otherwise, it is added to the odd_sum variable.

Common Mistakes

  1. Not initializing loop variables: Remember to initialize any loop variables before using them in the loop condition or body.
  2. Infinite loops: Ensure that your loop conditions are well-defined and will eventually become false, preventing an infinite loop.
  3. Misunderstanding the order of operations: Be aware of the order in which Python evaluates expressions to avoid unexpected results.
  4. Not handling break or continue statements correctly: Understand when to use break to exit a loop early and continue to skip over a single iteration.
  5. Misusing enumerate(): Remember that enumerate() returns tuples containing both the index and value of each item in the sequence.
  6. Forgetting to update loop variables: In some cases, you may need to update loop variables within the body of your loop. Make sure to do so correctly.
  7. Using list comprehensions improperly: List comprehensions can be a powerful tool, but they should be used judiciously and not as a replacement for loops in all situations.
  8. Not handling exceptions when using generators: Generators are iterable objects, so you may encounter errors if you try to use them in places where an iterator is not expected (e.g., as function arguments).
  9. Misusing while loops with break and continue statements: Ensure that your break and continue statements are used correctly within while loops, especially when dealing with infinite or nested loops.
  10. Not understanding the difference between for and while loops: Understand the use cases for both for and while loops and choose the appropriate loop structure for each problem you encounter.

Subheadings under Common Mistakes:

  • Misusing break and continue statements in for loops
  • Misusing break and continue statements in while loops
  • Infinite loops due to improperly defined conditions
  • Using list comprehensions inappropriately
  • Handling exceptions with generators
  • Understanding the difference between for and while loops

Practice Questions

  1. Write a Python script that calculates the sum of all odd numbers in a given list.
  2. Implement a while loop to print the Fibonacci sequence up to the 10th term.
  3. Given a string, write a function that counts the number of vowels it contains using a for loop.
  4. Write a script that finds and prints all duplicate elements in a list.
  5. Implement a for loop to reverse the order of a given list.
  6. Write a Python program that uses a for loop to find the largest prime number in a given range (e.g., 1 to 100).
  7. Write a function using a while loop that calculates the factorial of a given number.
  8. Implement a list comprehension to create a new list containing only the odd numbers from another list.
  9. Write a Python script that uses a for loop and the built-in input() function to take user input until an empty string is entered.
  10. Write a program using a while loop that simulates rolling dice and calculates the frequency of each number rolled (e.g., 1-6).
  11. Write a Python script that uses a for loop and the built-in math module to calculate the sum of all prime numbers up to 100.
  12. Implement a generator function that generates Fibonacci numbers up to (but not including) a specified number.
  13. Write a Python script that uses a for loop and the built-in random module to generate a random list of integers within a given range and find the median value.
  14. Implement a function using a while loop that finds the smallest common multiple of two numbers.
  15. Write a Python script that uses a for loop and the built-in re module to find all occurrences of a specific pattern in a given string.

FAQ

  1. What is the difference between a for loop and a while loop in Python?
  • A for loop is used to iterate over a sequence (such as a list, tuple, or string), whereas a while loop continues to execute as long as a specified condition is true.
  1. How can I iterate over a dictionary using a for loop in Python?
  • You can use the built-in items(), keys(), or values() methods to access the items of a dictionary and iterate over them using a for loop.
  1. What is the purpose of the enumerate() function in Python?
  • The enumerate() function allows you to iterate over a sequence and access both the index and value of each item.
  1. How can I exit a for or while loop early in Python?
  • You can use the break statement to exit a loop early, and the continue statement to skip over a single iteration.
  1. What is list comprehension, and how does it differ from using a for loop?
  • List comprehensions are a concise way to create lists based on existing data. They can be more efficient than using for loops in some cases, but they should not be used as a replacement for loops in all situations.
  1. How do I handle exceptions when using a while loop in Python?
  • You can use the try and except statements to handle exceptions within a while loop, just like you would with any other block of code in Python.
  1. What is the best way to iterate over multiple lists simultaneously in Python?
  • You can use nested for loops or list comprehensions with multiple generators to iterate over multiple lists simultaneously.
  1. How do I create a generator function in Python?
  • To create a generator function, you should define a function that yields values instead of returning them as a
Loops or Iteration Statements (Python Programming) | Python | XQA Learn