Python while Loop
The while
loop in Python is used to execute a block of code as long as a condition is True
.
Syntax
while condition:
# code block
- The loop will continue to run as long as the condition is true.
- The condition is checked before each iteration.
Example 1: Basic while
Loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Important: Infinite Loop
Be careful! If the condition never becomes False
, the loop will run forever.
# WARNING: Infinite loop unless you stop it manually
while True:
print("This will run forever")
Use break
to stop such loops when needed.
Example 2: Loop Until User Input
password = ""
while password != "admin123":
password = input("Enter password: ")
print("Access granted!")
Example 3: Countdown
num = 5
while num > 0:
print(num)
num -= 1
Output:
5
4
3
2
1
Example 4: while
with else
An optional else
block runs after the loop ends normally (not by break
).
i = 1
while i <= 3:
print(i)
i += 1
else:
print("Loop finished!")
Output:
1
2
3
Loop finished!
Loop Control Statements in while
1. break
– Exit the loop early
i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
Output:
1
2
2. continue
– Skip current iteration
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
3. pass – Do nothing
Used as a placeholder where code will be added later.
i = 0
while i < 3:
pass # do nothing
i += 1
Real-world Use Case: Menu System
choice = ""
while choice != "q":
print("1. Say Hello\nq. Quit")
choice = input("Choose an option: ")
if choice == "1":
print("Hello!")
Summary Table
Keyword | Description |
---|---|
while | Repeats code as long as condition is true |
break | Stops the loop immediately |
continue | Skips to the next iteration |
else | Runs after loop ends (if no break) |
pass | Placeholder with no action |
Exercise
Task: Use a while
loop to print even numbers from 2 to 10.
num = 2
while num <= 10:
print(num)
num += 2
Output:
2
4
6
8
10