A while loop executes a block of code as long as a condition is True.
The loop continues running until the condition becomes False.
Syntax
while condition:
# code block
Simple While Loop
Example:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
How It Works
- Check the condition.
- If the condition is
True, execute the code block. - Return to the condition.
- Repeat until the condition becomes
False.
Example:
count = 1
while count <= 3:
print("Hello")
count += 1
Output:
Hello
Hello
Hello
The Increment Operator
Remember to update the loop variable, otherwise the loop will run forever.
Example:
i = 1
while i <= 5:
print(i)
i += 1
Infinite Loop
If the condition never becomes False, the loop runs forever.
Example:
i = 1
while i <= 5:
print(i)
This creates an infinite loop because i is never updated.
Break Statement
The break statement stops the loop immediately.
Example:
i = 1
while i <= 10:
print(i)
if i == 5:
break
i += 1
Output:
1
2
3
4
5
Continue Statement
The continue statement skips the current iteration and moves to the next one.
Example:
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
Else Statement
The else block executes when the loop finishes normally.
Example:
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Loop Finished")
Output:
1
2
3
Loop Finished
Using User Input
Example:
password = ""
while password != "admin":
password = input("Enter Password: ")
print("Access Granted")
Nested While Loop
A while loop can be placed inside another while loop.
Example:
i = 1
while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1
Output:
1 1
1 2
2 1
2 2
3 1
3 2
Practical Example
Print the first 5 even numbers.
Example:
num = 2
while num <= 10:
print(num)
num += 2
Output:
2
4
6
8
10
Summary
- A
whileloop repeats code while a condition isTrue. - The condition is checked before each iteration.
- Update the loop variable to avoid infinite loops.
- Use
breakto exit a loop. - Use
continueto skip an iteration. - Use
elseto execute code when the loop ends normally. whileloops are useful when the number of iterations is unknown.