🐍 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:
The for
loop automatically goes through each item in the sequence one by one.
In the example above, it starts from 0 and ends at 4 because range(5)
creates numbers from 0 to 4.
The loop stops when all items are finished.
♾️ 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:
Before each run, the loop checks the condition.
If the condition is True
, the block runs.
If the condition becomes False
, the loop stops.
In the example above, the loop runs until count
reaches 5, then it stops.
⚖️ Key Differences Between For Loop and While Loop
1. Use Case
For Loop: Use it when you know exactly how many times you want to repeat, or when you want to go through each item in a sequence.
While Loop: Use it when you don’t know the exact number of times in advance, and the repetition depends on a condition.
2. Control of Iterations
For Loop: The loop controls itself, usually using range()
or a sequence. You don’t need to manually change anything.
While Loop: You must update the condition inside the loop (like increasing a counter). If you forget, the loop will keep running forever.
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.