Python while Loop
What is a while loop in Python?
A while loop in Python is a control flow statement used to repeatedly execute a block of code as long as a given condition is True.
It is useful when:
- The number of iterations is not known in advance
- You want to loop based on a condition
Syntax of while Loop in Python:
while condition:
# code block to execute repeatedly
- The loop continues as long as the condition is True
- Once the condition becomes False, the loop stops
Example 1: Basic while Loop
count = 1
while count <= 5:
print("Count is:", count)
count += 1
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
Explanation:
- The loop runs as long as count <= 5
- count is incremented in each iteration
Example 2: while Loop with else
x = 3
while x > 0:
print("x =", x)
x -= 1
else:
print("Loop completed.")
Output:
x = 3 x = 2 x = 1 Loop completed.
Explanation:
The else block runs after the while condition becomes False
Example 3: Infinite while Loop
while True:
print("This will run forever")
break # Stops after first iteration
Output:
This will run forever
Explanation:
Use break to avoid an infinite loop when using while True
Real-World Example: Password Prompt
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access Granted")
Explanation:
The loop keeps asking for a password until the correct one is entered
Useful Keywords with while Loop
Keyword | Description |
---|---|
break | Exits the loop immediately |
continue | Skips current iteration, goes to next |
else | Runs after loop ends (if not broken) |
Common Mistakes to Avoid
- Forgetting to update the loop variable - leads to infinite loop
- Always ensure the condition can become False
- Don't forget indentation in Python