While Loop in Python
-
This lesson teaches how the while loop works in Python and how to execute code repeatedly based on a condition.
What is a while Loop?
The while loop in Python is used to repeat a block of code as long as a given condition is True.
👉 The loop continues until the condition becomes False.
Why Use a while Loop?
We use a while loop when:
The number of repetitions is not known in advance
Repetition depends on a condition
Continuous checking is required
Programs involve user input, validation, or retry logic
Syntax of while Loop
Basic Syntax
while condition:
statement(s)
🔹 Syntax Explanation
Flow of Execution (while Loop)
Condition is checked
If True → loop body executes
Variable is updated
Condition is checked again
Loop ends when condition becomes False
Printing Numbers Using while Loop
This program prints numbers from 1 to 5 using a while loop.
count = 1
while count <= 5:
print(count)
count += 1
Infinite Loop
If the condition never becomes False, the loop runs forever.
while True:
print("Hello")
Always update the condition variable.
What is else in while Loop?
The else block in a while loop executes:
✅ When the loop ends normally
❌ Not executed if the loop stops using break
👉 Same rule as for-else.
Syntax of while-else
while condition:
statement(s)
else:
statement(s)
Using else with while Loop (No break)
This program shows that the else block executes when the loop completes normally.
num = 1
while num <= 3:
print(num)
num += 1
else:
print("Loop finished successfully")
Using else with while Loop and break
This program demonstrates that the else block is skipped when break is used.
num = 1
while num <= 5:
if num == 3:
break
print(num)
num += 1
else:
print("Loop completed")
Where while-else is Used?
Retry mechanisms
Login systems
Search operations
Validation logic