2.1 Overview
The while loops repeat a block of code as long as a condition is true. It's like saying "keep doing this until this condition is no longer true.". It's particularly useful when the number of iterations is not known beforehand.
Let's look at an example where we print numbers from 1 to 5 using a while loop. We will use an indexing variable i, which we initialize to 1 and increment in each iteration.
# Initialize the indexing variable i = 1 # Start the while loop with a condition while i <= 5: print(i) i += 1 # Increment the indexing variable |
In this example, the loop prints numbers from 1 to 5. It keeps running as long as the number is less than or equal to 5. After each print, the number is increased by 1.
Explanation:
- Initialize Indexing Variable: i is set to 1 before the loop starts.
- While Loop Condition: The loop continues as long as i is less than or equal to 5.
- Print Statement: Each iteration prints the current value of i.
- Increment: i is incremented by 1 after each iteration.
2.2 The break Statement
The break statement allows you to exit the loop immediately when a specified condition is met, regardless of the loop's condition.
Example: Exiting the Loop When a is 5
Let's look at an example where we print numbers from 1 to 9, but we want to exit the loop when a equals 2.
a = 1 while a < 10: print(a) if a == 5: break a += 1 |
Explanation:
- Initialize Indexing Variable: a is set to 1 before the loop starts.
- While Loop Condition: The loop continues as long as a is less than 10.
- Print Statement: Each iteration prints the current value of a.
- Break Condition: When a equals 5, the if condition becomes true and the break statement is executed.
- Increment: a is incremented by 1 after each iteration, except when the loop is broken.
2.3 The continue Statement
The continue statement skips the rest of the code in the current iteration and moves to the next iteration of the loop.
Example: Skipping an Iteration When a is 5
Let's look at an example where we print numbers from 1 to 10, but we want to skip printing the number 5.
a = 0 while a < 11: a += 1 if a == 5: continue print(a) |
Explanation:
- Initialize Indexing Variable: a is set to 0 before the loop starts.
- While Loop Condition: The loop continues as long as a is less than 11.
- Increment: a is incremented by 1 at the beginning of each iteration.
- Continue Condition: When a equals 5, the if condition becomes true, and the continue statement is executed. This skips the print statement for that iteration and proceeds to the next iteration.
- Print Statement: Prints the current value of a, except when a equals 5.
2.4 The else in while Loop
The else statement is used to run a block of code once the while loop condition becomes false. The code inside the else block will only execute after the loop has completed all iterations without being interrupted by a break statement.
Example:
Let's look at an example where we print numbers from 0 to 4 and then print a message once the loop condition is false.
x = 0 y = 5 while x < y: print(x) x += 1 else: print("x is no longer less than y") |
Explanation:
- Initialize Indexing Variables: x is set to 0 and y is set to 5 before the loop starts.
- While Loop Condition: The loop continues as long as x is less than y.
- Print Statement: Each iteration prints the current value of x.
- Increment: x is incremented by 1 after each iteration.
- Else Block: When the loop condition x < y becomes false, the else block is executed, printing "x is no longer less than y".
2.5 The infinite Loop
An infinite loop in Python is a loop that continues to run indefinitely because the terminating condition is never met. This can happen in a while loop if the loop's condition always remains true and there is no mechanism inside the loop to change it. Infinite loops can be useful in certain situations but are often unintended and can cause a program to become unresponsive.
Example 1
while True: print("This loop will run forever.") |
Explanation:
- The condition True is always true, so the loop never stops.
- The print statement will execute repeatedly without end.
Example 2
a = 0 |
Explanation:
- The loop condition a < 10 starts as true because a is initialized to 0.
- The value of a is never changed inside the loop, so the condition a < 10 remains true indefinitely.
- The loop will keep printing 0
2.6 Various Use Cases of While Loop
A while loop can terminate based on a string condition. In this case, the loop continues until it encounters an empty string, which causes the loop condition to evaluate to False.
Example
names = ["Monty", "", "Python"] i = 0 while names[i]: print(names[i]) i += 1 |
Explanation:
- The while loop iterates through the names list starting from the first element.
- The loop stops when it encounters an empty string (""), as empty strings evaluate to False.
- Only the first element, "Monty", is printed because the second element is an empty string, which causes the loop to terminate.