In Python, the while...else
construct is a control structure that combines the while
loop with an optional else
block. The else
block is executed when the loop’s condition becomes false and the loop completes all its iterations without being prematurely terminated by a break
statement. This can be useful for performing actions after the loop has finished its normal execution.
Here’s the general syntax of a while
loop with an else
clause:
while condition:
# Code to be executed while the condition is true
# This code will be repeatedly executed until the condition becomes false
else:
# Code to be executed when the condition becomes false
# This code is executed after the loop completes if it finishes normally
Here’s a breakdown of how the while...else
construct works:
- The
while
loop checks the specified condition. If the condition is true, the loop’s body is executed, and the process continues. - If the condition becomes false, the loop exits, and the control flows to the
else
block (if present). This block is executed only if the loop completes its iterations normally (i.e., without encountering abreak
statement). - If the loop is terminated by a
break
statement, theelse
block is skipped.
Here’s an example to illustrate the usage of while
with else
:
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
else:
print("Loop is finished")
In this example, the while
loop runs as long as count
is less than 5. Each iteration prints the value of count
and increments it. Once count
reaches 5, the loop’s condition becomes false, and the else
block is executed, printing “Loop is finished.”
Note: if you use a break
statement to exit the loop prematurely, the else
block will not be executed.
count = 0
while count < 5:
if count == 3:
break
print(f"Count is {count}")
count += 1
else:
print("Loop is finished")
In this example, the loop will break when count
becomes 3. As a result, the else
block will not be executed, and the output will only show the counts up to 2.
While else in the Python example
Here are a few more examples of using the while
loop with the else
clause in Python:
Printing numbers from 1 to 10 using a while
loop:
num = 1
while num <= 10:
print(num)
num += 1
else:
print("Loop completed")
Finding the factorial of a number using a while
loop:
num = int(input("Enter a number: "))
factorial = 1
while num > 0:
factorial *= num
num -= 1
else:
print(f"The factorial is {factorial}")
Searching for an element in a list using a while
loop:
numbers = [10, 20, 30, 40, 50]
search_value = int(input("Enter a number to search: "))
index = 0
while index < len(numbers):
if numbers[index] == search_value:
print(f"Found {search_value} at index {index}")
break
index += 1
else:
print(f"{search_value} not found in the list")
Summing numbers entered by the user until a negative number is encountered:
total = 0
while True:
num = int(input("Enter a number (negative to quit): "))
if num < 0:
break
total += num
else:
print(f"Sum of numbers: {total}")
Find whether a number is prime:
num = int(input("Enter a number: "))
is_prime = True
if num <= 1:
is_prime = False
else:
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
is_prime = False
break
divisor += 1
else:
print(f"{num} is prime")
if not is_prime:
print(f"{num} is not prime")
Output:
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.