Mastering Python Loops: For, While & Nested Loops Explained

Arnav SinghArnav Singh
6 min read

What will you learn?

ConceptSummary
For LoopRepeats a block of code a specific number of times using a sequence.
While LoopContinues running a block of code as long as a condition remains true.
Nested LoopsA loop inside another loop, useful for working with grids or tables.
Break and ContinueKeywords that alter the flow of loops. break exits, continue skips.
Use of Loops in PracticeLoops help automate repetitive tasks, e.g., iterating through lists.

Introduction: The Power of Loops in Python

When programming, you'll often need to repeat tasks multiple times, like processing every item in a list or generating numbers. Loops make these tasks much easier. Instead of writing repetitive code, loops allow you to automate this repetition with a few lines.

There are two main types of loops in Python: for loops and while loops. Both let you repeat blocks of code, but each is suited for different situations. In this article, you'll learn how to use them, explore nested loops, and master the art of repetition in programming.


The For Loop: Automating Repetition

The for loop allows you to iterate over a sequence (like a list or range) and execute a block of code for each item in that sequence.

Syntax of a for Loop

Here's the basic syntax of a for loop in Python:

for item in sequence:
    # code to execute for each item
  • item: Represents the current item in the sequence.

  • sequence: Could be a list, tuple, string, or a range of numbers.

Example: Python for Loop

Let's look at a simple example:

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

Explanation:

  • This loop goes through each fruit in the list fruits and prints it out. So the output will be:

      apple
      banana
      cherry
    

Flowchart of a for Loop

Here’s a simple flowchart to show how a for loop works:

Start
  ↓
Initialize variable
  ↓
Is there a next item in the sequence?
  ├── Yes → Execute code → Go to next item
  └── No → Exit loop
  ↓
End

The loop continues until every item in the sequence has been processed.

Common Uses of for Loops

  1. Iterating Over Lists: As shown in the fruit example.

  2. Iterating Over Ranges:

for i in range(5):
    print(i)

This will print numbers from 0 to 4.


The While Loop: Repeat Until a Condition is Met

The while loop keeps repeating a block of code as long as a condition is true. It's useful when you don’t know in advance how many times the loop will run.

Syntax of a while Loop

while condition:
    # code to run repeatedly
  • condition: The loop continues running as long as this condition is true.

Example: Python while Loop

x = 1
while x < 5:
    print(x)
    x += 1

Explanation:

  • The loop starts with x = 1 and continues until x is no longer less than 5. Each time, x increases by 1. Output:

      1
      2
      3
      4
    

Flowchart of a while Loop

Here's a flowchart that demonstrates how a while loop works:

Start
  ↓
Check condition
  ↓
Is the condition true?
  ├── Yes → Execute code → Recheck condition
  └── No → Exit loop
  ↓
End

Nested Loops: Looping Inside Loops

You can place one loop inside another loop. These are called nested loops. Nested loops are often used when you need to work with grids, tables, or matrices.

Example: Nested for Loops

for i in range(3):
    for j in range(2):
        print(f"i: {i}, j: {j}")

Explanation:

  • The outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2 times. The output will be:

      i: 0, j: 0
      i: 0, j: 1
      i: 1, j: 0
      i: 1, j: 1
      i: 2, j: 0
      i: 2, j: 1
    

Example: Nested while Loops

x = 0
while x < 3:
    y = 0
    while y < 2:
        print(f"x: {x}, y: {y}")
        y += 1
    x += 1

This will produce the same output as the nested for loop example. Nested loops are incredibly useful for multi-level structures like tables, matrices, or combinations of data.


Break and Continue: Controlling Loop Flow

In both for and while loops, you can control how the loop behaves using two important keywords: break and continue.

break Statement

  • The break statement exits the loop completely, even if the condition or sequence hasn’t finished.
for i in range(10):
    if i == 5:
        break
    print(i)

Explanation:

  • This loop will print numbers from 0 to 4. Once i reaches 5, the break statement will exit the loop.

continue Statement

  • The continue statement skips the current iteration and moves to the next one.
for i in range(5):
    if i == 3:
        continue
    print(i)

Explanation:

  • The loop will print numbers from 0 to 4, except for 3, which is skipped due to the continue statement.

When to Use Each Loop

  • Use a for loop when you know the number of iterations in advance (e.g., iterating through a list or a range).

  • Use a while loop when you don’t know how many iterations are required, and the condition controls the loop.


Let’s Practice

  1. Practice Problem 1: Write a for loop that prints the square of each number in a list.

     numbers = [1, 2, 3, 4, 5]
     for num in numbers:
         print(num ** 2)
    
  2. Practice Problem 2: Write a while loop that counts down from 10 to 1.

     x = 10
     while x > 0:
         print(x)
         x -= 1
    
  3. Challenge: Create a nested loop that prints the multiplication table from 1 to 5.

     for i in range(1, 6):
         for j in range(1, 6):
             print(f"{i} * {j} = {i * j}")
    

Test Your Knowledge

  1. What is the difference between a for loop and a while loop in Python?

  2. When would you use a nested loop? Provide an example.

  3. What happens if you forget to increment a counter in a while loop?

  4. Explain the purpose of the break and continue statements.

  5. Write a loop that prints all odd numbers from 1 to 10 using a for loop.


Key Takeaways from this article

ConceptSummary
For LoopUse when you know the number of iterations.
While LoopUse when the number of iterations depends on a condition.
Nested LoopsUseful for multi-level structures, like grids or tables.
BreakExits the loop early.
ContinueSkips the current iteration and moves to the next one.

Conclusion

Loops are essential for automating repetitive tasks in Python. Mastering the use of for loops, while loops, and nested loops will greatly improve your coding efficiency. Practice writing different types of loops, and soon, you'll be able to tackle complex tasks with ease.


10
Subscribe to my newsletter

Read articles from Arnav Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arnav Singh
Arnav Singh

A 16 y/o trying to get into a college :<