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:
- ➤ 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!
πTrending Topics
π Connect With Us:
“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
Post a Comment