Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples.
What is Python While-Else Loop?
In Python, the while loop is used for iteration. It executes a block of code repeatedly until the condition becomes false and when we add an "else" statement just after the while loop it becomes a "While-Else Loop". This else statement is executed only when the while loops are executed completely and the condition becomes false. If we break the while loop using the "break" statement then the else statement will not be executed.
Python While Else Syntax
while(Condition):
# Code to execute while the condition is true
else: # Code to execute after the loop ends naturally
Example:
In this example, a 'while' loop iterates through numbers from 1 to 5, continuously adding each number to the 'sum_result'. The 'else' block, executed when the loop condition becomes false, prints the message "Loop completed. Sum =" followed by the final sum of the numbers, which is 15.
Python3
# Initialize variablesnum=1sum_result=0# While loop to calculate the sumwhilenum<=5:sum_result+=numnum+=1else:print("Loop completed. Sum =",sum_result)
Output
Loop completed. Sum = 15
Flowchart of Python While LoopFlow Chart of While-Else Loop
Working of While-Else Loop
While Loop: This part works like any standard while loop. The code inside this block will continue to execute as long as the condition is True.
Else Clause: Once the false condition encounters in 'while' loop, control passes to the block of code inside the else. If the loop is terminated with break, the else block is not executed.
Infinite While-Else Loop in Python
In this example, we are understanding how we can write infinite Python While-else loops.
Python3
age=30# the test condition is always True whileage>19:print('Infinite Loop')else:print("Not a infinite loop")
Control Statements in Python with Examples
Loop control statement changes the execution from their normal sequence and we can use them with Python While-else. Below are some of the ways by which we can use Python while else more effectively in Python:
Python While Else with a Break Statement
In the below code, we have created a list of numbers, after that we have written a while-else loop to search the target in the list 'numbers'. The while loop is iterated over the list and check if the target is present in the list or not using if condition and in this example the target is not present so the while loop run completely using break statement and hence executed the else block.
Python3
numbers=[1,3,5,7,9]target=2i=0# While to search target in numberswhilei<len(numbers):# Check the numberifnumbers[i]==target:print("Found the number!")breaki=i+1# Else condition run when while loop run completelyelse:print("Number not found.")
Output
Number not found.
Nested While-Else loop in Python
In this example, a 'while' loop iterates through a list of numbers, and for each non-prime number, it finds the first composite number by checking divisibility, breaking out of the loop when found; if no composites are found, the 'else' block of the outer loop executes, printing a message.
Python3
nums=[3,5,7,4,11,13]i=0whilei<len(nums):ifnums[i]>1:divisor=2whiledivisor<nums[i]:ifnums[i]%divisor==0:print(f"The first composite number in the list is: {nums[i]}")breakdivisor+=1else:# The else part of the while loop; executed if the number is primei=i+1continue# Breaks the for loop if a composite number is foundbreakelse:# The else part of the for loop; executed if no composite numbers are foundprint("No composite numbers found in the list.")
Output
The first composite number in the list is: 4
Python While Else with Continue Statement
In this example, we have used continue statement in while-else loop. The below program print a table of 2 and inside the while loop we have write a condition which checks if the counter is even or not if the counter is even if statement is executed and hence "continue" is also executed and rest of the code inside the while loop is skipped. In the output, we can see that is continue statement will not affect the execution of else statement.
Python3
# Example of while else with continue statementcounter=1num=2while(counter<=10):if(counter%2==0):counter+=1# Skip the rest of the loop body and go to the next iterationcontinueprint(f"{num} * {counter} = {num*counter}")counter+=1else:print("Inside the else block")print("Outside the loop.")
In this example, a 'while' loop is employed to search for the target value (5) within the first 10 integers. If the target value is found, it prints a corresponding message and breaks out of the loop; otherwise, the loop completes without finding the target using pass statement. The code outside the loop then executes, printing "Loop completed." to indicate the end of the process.
Python3
counter=0target=5# While loop to search for the target valuewhilecounter<10:ifcounter==target:print(f"Target value {target} found!")breakcounter+=1else:pass# Rest of the code outside the loopprint("Loop completed.")
Output
Target value 5 found!
Loop completed.
Python While Else With a User Input
In this example, we are using Python while else loop while taking the user input and demonstrating the right input.
Python3
# Example: Using while else with user inputmax_attempts=3attempts=0whileattempts<max_attempts:user_input=input("Enter a valid number: ")ifuser_input.isdigit():print(f"Valid input: {user_input}")breakelse:print("Invalid input. Please enter a numeric value.")attempts+=1else:print(f"Exceeded maximum attempts ({max_attempts}). Exiting program.")