DEV Community

Ridwan Ahmed Arman
Ridwan Ahmed Arman

Posted on

Revise Python in 15 days for ML (2025) : Day 4 (Loop)

Welcome to Day 4 of our Python journey! If you missed Day 3 where we explored operators and conditionals, make sure to check it out first!

🔁 What Are Loops?

Loops are like having a super-efficient assistant who can repeat the same task multiple times without getting tired. Instead of writing the same code over and over, we can wrap it in a loop and let Python handle the repetition!

Today we'll master two powerful loop types:

  • 🔢 For loops - when you know exactly how many times you want to repeat something
  • ⏱️ While loops - when you want to keep going until a condition changes

🔢 For Loops: The Counting Champion

Image description

A for loop works like this:

  1. Specify what you want to iterate through
  2. For each item, execute the indented code block
  3. Move to the next item and repeat until you've gone through everything

💫 Magic of Iteration: Three Ways to Use For Loops

1️⃣ Iterating Through Each Character

name = "Ridwan"
for i in name:
    print(i, 'i')
Enter fullscreen mode Exit fullscreen mode

Output:

R i
i i
d i
w i
a i
n i
Enter fullscreen mode Exit fullscreen mode

What's happening?

  • Python takes each character from "Ridwan" one by one
  • It temporarily stores each character in the variable i
  • Then it runs the indented code (printing the character and 'i')
  • It automatically moves to the next character

2️⃣ Using Range and Indexing

name = "Rid wan"
for i in range(len(name)):
    print(name[i], 'i')
Enter fullscreen mode Exit fullscreen mode

Output:

R i
i i
d i
  i
w i
a i
n i
Enter fullscreen mode Exit fullscreen mode

What's happening?

  • range(len(name)) creates a sequence: 0, 1, 2, 3, 4, 5, 6
  • Each number is stored in i during each loop iteration
  • We use i as an index to access each character with name[i]

💡 Pro Tip: This approach gives you the index position, which can be really useful when you need to know where you are in the sequence!

3️⃣ Processing List Items

L = [1, 2, 3, 4, 5]
sum = 0
for i in L:
    sum += i
    print(i, sum)
print('sum is = ', sum)
Enter fullscreen mode Exit fullscreen mode

Output:

1 1
2 3
3 6
4 10
5 15
sum is = 15
Enter fullscreen mode Exit fullscreen mode

What's happening?

  • Python takes each number from the list one by one
  • It temporarily stores each number in the variable i
  • It adds i to our running total sum
  • It prints both the current number and the running total

⏱️ While Loops: The Patient Guardian

Image description

While loops work differently:

  1. Check if a condition is True
  2. If True, execute the code block
  3. Check the condition again
  4. Keep repeating until the condition becomes False
name = "Rid wan"
i = 0
while i < len(name):
    print(name[i], 'i')
    i += 1
Enter fullscreen mode Exit fullscreen mode

Output:

R i
i i
d i
  i
w i
a i
n i
Enter fullscreen mode Exit fullscreen mode

What's happening?

  • We start with i = 0
  • The loop checks if i < len(name) (which is 7)
  • If True, it prints the character at position i
  • Then it increases i by 1 with i += 1
  • This process repeats until i reaches 7, at which point the condition is False

🎭 For Loops vs While Loops: The Key Differences

Feature For Loop While Loop
Best Used When You know exactly how many iterations you need You don't know in advance how many iterations you need
Counter Managed automatically You must initialize and update yourself
Typical Use Cases Iterating through collections Validating user input, processing until a condition is met
Risk Less prone to infinite loops Can create infinite loops if condition never becomes False

⚠️ Warning! Always make sure your while loop condition will eventually become False, or your program will run forever!

🌀 Nested Loops: Loops Inside Loops

Nested loops are like wheels within wheels - an inner loop runs completely for each iteration of the outer loop.

🧩 Basic Nested Loop

for i in range(1, 5):
    for j in range(1, 5):
        print(i, j)
    print()
Enter fullscreen mode Exit fullscreen mode

Output:

1 1
1 2
1 3
1 4

2 1
2 2
2 3
2 4

3 1
3 2
3 3
3 4

4 1
4 2
4 3
4 4
Enter fullscreen mode Exit fullscreen mode

What's happening?

  • The outer loop runs 4 times (i = 1, 2, 3, 4)
  • For each value of i, the inner loop runs 4 times (j = 1, 2, 3, 4)
  • That's a total of 16 print statements!
  • The empty print() adds a blank line after each inner loop completes

🧮 Practical Example: Multiplication Table

for i in range(1, 5):
    for j in range(1, 5):
        print(i, '*', j, '=', i*j)
    print()
Enter fullscreen mode Exit fullscreen mode

Output:

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12

4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
Enter fullscreen mode Exit fullscreen mode

Visualization of nested loops:

Outer loop (i=1) → Inner loop (j=1,2,3,4) → Print blank line
Outer loop (i=2) → Inner loop (j=1,2,3,4) → Print blank line
Outer loop (i=3) → Inner loop (j=1,2,3,4) → Print blank line
Outer loop (i=4) → Inner loop (j=1,2,3,4) → Print blank line
Enter fullscreen mode Exit fullscreen mode

🛠️ Practical Loop Applications

For loops are great for:

  • Processing each item in a list, tuple, string, or dictionary
  • Executing code a specific number of times
  • Iterating with precise control over the sequence

While loops excel at:

  • Processing user input until it's valid
  • Reading file data until end-of-file
  • Running games until the player quits
  • Implementing algorithms that run until convergence

🧠 Loop Selection Guide

Choose a for loop when:

  • You can count the iterations in advance
  • You're working with a collection (list, string, etc.)
  • You need automatic iteration

Choose a while loop when:

  • The number of iterations depends on user input
  • You need to check a condition before each iteration
  • You might need to skip iterations or break early based on conditions

🚀 Challenge Yourself!

Try these exercises to cement your understanding:

  1. Create a program that uses a for loop to find all even numbers between 1 and 20
  2. Write a while loop that asks for names until the user enters "quit"
  3. Build a nested loop to create a simple pattern of asterisks forming a triangle

🔗 Resources

🔮 Coming Up Next...

Tomorrow we'll dive into Python data structures - the fundamental building blocks for organizing and storing your data efficiently!


← Day 3: Operators & Conditionals | Day 4: Mastering Loops | [Day 5: Data Structures →]


Which loop do you find more useful in your coding projects? Share your thoughts in the comments below! 💬

Top comments (0)