In Python, both for and while loops are used to execute a block of code repeatedly, but they are designed for different situations. Understanding the difference between them helps to choose the most appropriate loop for a given problem.
For loop
for loop is used to iterate over the elements of an iterable, such as a list, tuple, string, dictionary, or range(). It automatically retrieves each element one by one, making it the preferred choice when iterating over a collection of data.
fruits = ["Apple", "Mango", "Orange"]
for fruit in fruits:
print(fruit)
Output
Apple Mango Orange
Explanation: for loop visits each element in fruits one at a time. During each iteration, the current element is assigned to fruit and printed.
Below is the flowchart of For loop:

While Loop
while loop repeatedly executes a block of code as long as a specified condition remains True. It is commonly used when the number of iterations is not known beforehand and the loop should continue until a condition changes.
count = 1
while count <= 3:
print(count)
count += 1
Output
1 2 3
Explanation: loop continues while count <= 3 is True. After each iteration, count is increased by 1. When count becomes 4, the condition becomes False and the loop stops.
Below is the flowchart of While loop:

The table below highlights the key differences between for and while loops.
| Feature | for Loop | while Loop |
|---|---|---|
| Purpose | Iterates over a sequence or iterable | Repeats while a condition is True |
| Number of Iterations | Usually known in advance | May or may not be known in advance |
| Condition | Controlled by the iterable | Controlled by a Boolean condition |
| Best Used When | Processing every element in a collection | Repeating until a condition changes |
| Counter Update | Handled automatically during iteration | Usually updated manually inside the loop |
| Common Use | Lists, tuples, strings, dictionaries, range() | Input validation, menu-driven programs, unknown repetitions |