🐍 Introduction

In Python, loops allow us to run a block of code multiple times. The two main types of loops are the for loop and the while loop. Both help us repeat tasks, but they are used in different situations. Knowing when to use each loop is important for writing clear and efficient Python programs.

🔄 What is a For Loop?

A for loop is used when we already know how many times we want to run a block of code, or when we want to go through each item in a sequence (like a list, tuple, string, or range).

Syntax:

for variable in sequence:
    # code block

Example:

for i in range(5):
    print("Iteration:", i)

Explanation in simple words:

♾️ What is a While Loop?

A while loop is used when we want to repeat code as long as a condition remains True.

Syntax:

while condition:
    # code block

Example:

count = 0
while count < 5:
    print("Iteration:", count)
    count += 1

Explanation:

⚖️ Key Differences Between For Loop and While Loop

1. Use Case

2. Control of Iterations

3. Risk of Infinite Loops

4. Readability

🧩 Example: Comparing Both Loops

For Loop Example

for num in range(1, 6):
    print("Number:", num)

While Loop Example

num = 1
while num <= 5:
    print("Number:", num)
    num += 1

Output of both loops:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Both produce the same result, but the way they achieve it is different.

📌 Summary

In Python, both for loops and while loops are used to repeat code, but they work differently. A for loop is best when you know the number of times you want to repeat or when you want to go through a sequence. A while loop is useful when you don’t know the number of repetitions in advance and the loop depends on a condition being true. In short: use a for loop for fixed repetitions or sequences, and a while loop for condition-based repetitions.