Python while Loops
🐍 Python while Loops
The while loop in Python is used to repeatedly execute a block of code as long as a condition is True.
1. Basic While Loop
✅ Output:
count += 1is required to increment the counter. Otherwise, the loop runs forever (infinite loop).
2. Infinite While Loop
Use
breakto exit the loop.
3. Using break Statement
break immediately stops the loop:
✅ Output:
4. Using continue Statement
continue skips the current iteration and moves to the next:
✅ Output:
5. Using else with While
Python allows else after while, executed if the loop ends normally (not by break):
✅ Output:
6. Practical Examples
6.1 Sum of Numbers Until User Enters 0
6.2 Password Validation
6.3 Multiplication Table
7. Infinite Loop Warning
Avoid infinite loops without a condition change or break statement:
8. Tips & Best Practices
Always ensure the loop condition will eventually be False.
Use
breakandcontinuewisely for control flow.Use
elseafter while for clean code when needed.
🧠 Practice Exercises
Print numbers from 10 to 1 in descending order using while.
Take input repeatedly until the user enters a negative number.
Find the factorial of a number using while loop.
Sum all even numbers from 1 to 50 using while.
Print all digits of a number entered by the user individually.
