Difference Between for And while Loop

Python Loop Guide: for vs while Loop Explained with Examples




1. πŸ€” Basic Difference

for loop is used when the number of iterations is known, while while loop is used when the number of iterations is unknown and depends on a condition.

Feature for loop while loop
Usage Used to iterate over a sequence Used to repeat while a condition is True
Iteration Count Known or fixed Unknown or based on condition
Risk of Infinite Loop Low High (if condition never becomes False)

2. πŸ” Syntax

for Loop Syntax


for item in sequence:
    # do something

while Loop Syntax


while condition:
    # do something

3. πŸ§ͺ Example: Print numbers from 1 to 5

Using for loop:


for i in range(1, 6):
    print(i)

Using while loop:


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

4. 🍎 Looping Through a List

Using for loop:


fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
    print(fruit)

Using while loop:


fruits = ['apple', 'banana', 'mango']
i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1

5. ⚠️ Infinite Loop Danger

Important: A while loop can run forever if the condition never becomes False.

Example of Infinite while loop:


i = 1
while i > 0:
    print(i)
    # i is never decreased or changed

Note: Always ensure the loop has an exit condition!


6. ✅ When to Use What?

  • Use for when iterating over a sequence like a list, tuple, or range.
  • Use while when looping based on a condition or waiting for an event.

7. 🧾 Summary Table

Aspect for loop while loop
Best for Known number of iterations Unknown number of iterations
Initialization Done by range() or sequence Manually before loop
Loop Control Automatic Manual (update variable inside loop)
Readability Cleaner for fixed loops Better for condition-based repetition

πŸ“Œ Final Tip

Use for loop when you know how many times to run.
Use while loop when you're not sure and the loop depends on some condition (like user input or sensor reading).


Hope this helps you understand Python loops better! πŸš€


πŸ“š Practice Questions:


πŸ“š Related Topics:


πŸ“Œ Bookmark this blog or follow for updates!

Python Logo

πŸ‘ Liked this post? Share it with friends or leave a comment below!

“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments