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
forwhen iterating over a sequence like a list, tuple, or range. - Use
whilewhen 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:
- ➤ Python Arithmetic Operators
- ➤ Basic String Functions
- ➤ Advanced String Functions
- ➤ Basic List Functions
- ➤ Advanced List Functions : Part-1
- ➤ Advanced List Functions : Part-2
- ➤ Basic Tuple Functions
- ➤ Advanced Tuple Functions
- ➤ Basic Dictionary Functions
- ➤ Advanced Dictionary Functions
- ➤ Conditional Statements : if-elif-else
- ➤ Python 'for' Loop
- ➤ Python 'while' Loop
- ➤ Difference between 'for' loop and 'while' loop
- ➤ Introducing Python Functions
๐ Bookmark this blog or follow for updates!
๐ Liked this post? Share it with friends or leave a comment below!