6.4 While else loop
6.4a While loop paired with else block
In Python, a while
loop can be paired with an else
block. The else
block is executed when the while
loop condition becomes false. However, if the loop is terminated by a break
statement, the else
block will not be executed. This feature can be useful for certain scenarios where you want to perform some action only if the loop wasn't terminated prematurely.
6.4b When to use while-else
-
Searching with a Condition - When you are searching for an item or a condition within a loop, and you need to handle the case where the item or condition is not found.
-
Completion Without Interruption - When you need to ensure that a block of code runs only if the loop completes normally, without interruption by break.
6.4c How to use while loop with else block
Syntax:
while condition:
# Code to execute while the condition is true
else:
# Code to execute when the condition becomes false (and not terminated by break)
Example 6.4.1 - Consider a scenario where you are searching for an item in a list. If the item is found, you exit the loop early using break. If the loop completes without finding the item, you execute the else block.
items = [1, 2, 3, 4, 5]
search_item = 3
index = 0
while index < len(items):
if items[index] == search_item:
print(f"Item {search_item} found at index {index}")
break
index += 1
else:
print(f"Item {search_item} not found in the list")
Example 6.4.1 - Output
Item 3 found at index 2
Example 6.4.1 - Explanation
- If
search_item
is found in the list, the loop will terminate withbreak
, and theelse
block will not be executed. - If
search_item
is not found in the list, theelse
block will be executed, indicating that the item was not found.
Exercise 6.4.1 - Write a Python program that asks the user to enter a positive number. If the user enters a negative number, the program should keep asking the user to enter a positive number. Once the user enters a positive number, print "Thank you!" and exit the loop. Use a while loop paired with an else block to accomplish this.
Exercise 6.4.1 - Model Answer - Make sure to work out the exercise before checking the model answer.