The while
loop in Python is used to execute a block of code as long as a specified condition is true. This type of loop is particularly useful when the number of iterations is not known before the loop starts. Below are various examples showcasing the use of while
loops in different scenarios.
Basic while
Loop
Example:
1 2 3 4 |
x = 0 while x < 5: print(x) x += 1 |
This loop prints numbers from 0 to 4. The condition x < 5
is checked before each iteration, and the loop continues as long as the condition is true.
The break
Statement
You can stop the loop even if the while condition is true by using the break
statement.
Example:
1 2 3 4 5 6 |
x = 0 while x < 10: print(x) if x == 5: break x += 1 |
This loop will terminate when x
is equal to 5.
The continue
Statement
The continue
statement can be used to skip the current iteration and proceed to the next iteration of the loop.
Example:
1 2 3 4 5 6 |
x = 0 while x < 10: x += 1 if x % 2 == 0: continue print(x) |
This loop prints only odd numbers between 1 and 10 because continue
skips the print(x)
statement for even numbers.
The else
Clause
A while
loop can have an optional else
block which is executed when the loop condition becomes false.
Example:
1 2 3 4 5 6 |
x = 0 while x < 5: print(x) x += 1 else: print("Loop finished") |
This loop prints numbers from 0 to 4, followed by “Loop finished”.
Infinite Loops
A loop becomes infinite if its condition never becomes false. Infinite loops are often used intentionally and must be carefully controlled with break
statements.
Example:
1 2 3 4 |
while True: user_input = input("Enter 'exit' to stop: ") if user_input == "exit": break |
This loop will repeatedly ask the user for input until they type “exit”.
Nested while
Loops
You can nest while
loops inside another while
loop.
Example:
1 2 3 4 5 6 7 |
x = 0 while x < 3: y = 0 while y < 3: print(f"({x}, {y})") y += 1 x += 1 |
This example prints a grid of coordinate pairs from (0, 0) to (2, 2).
Combining while
Loops with for
Loops
while
and for
loops can be combined for more complex control flows.
Example:
1 2 3 4 5 |
x = 0 while x < 3: for y in range(3): print(f"({x}, {y})") x += 1 |
Similar to the previous example, this prints coordinate pairs but uses a for
loop for the inner iteration.
Understanding and effectively using while
loops enhances your ability to write programs that require conditional and repeated execution. By mastering while
loops along with for
loops, you can handle a wide range of programming scenarios in Python.