While Loops:
- Executes a block of statements repeatedly until a given condition is satisfied.
- When the condition becomes false, the line immediately after the loop in the program is executed.
- It is useful for scenarios where we don’t know in advance how many times we need to loop.
Basic Syntax:
while condition:
# Code to execute
Example:
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output: Count is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4
Infinite Loops:
- Be cautious with while loops, as they can lead to infinite loops if the condition never becomes False as in the below example
count = 0
while count < 5:
print("Count is:", count)
Output: Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 Count is: 0 .................... ....................
Break and Continue Statements:
- break: Exits the loop immediately.
- continue: Skips the rest of the current iteration and proceeds with the next iteration of the loop.
count = 0
while count < 10:
if count == 5:
break # Exit the loop
print(count)
count += 1
Output: 0 1 2 3 4
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue # Skip even numbers
print(count)
Output: 1 3 5 7 9 .................... ....................