Open In App

Python While Else

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 variables
num = 1
sum_result = 0
 
# While loop to calculate the sum
while num <= 5:
    sum_result += num
    num += 1
else:
    print("Loop completed. Sum =", sum_result)


Output

Loop completed. Sum = 15

Flowchart of Python While Loop
Screenshot-2024-01-29-145602

Flow 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
while age > 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 = 2
i=0
 
# While to search target in numbers
while i < len(numbers):
    # Check the number
    if numbers[i] == target:
        print("Found the number!")
        break
    i=i+1
     
# Else condition run when while loop run completely
else:
    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=0
 
while i < len(nums):
    if nums[i] > 1:
        divisor = 2
        while divisor < nums[i]:
            if nums[i] % divisor == 0:
                print(f"The first composite number in the list is: {nums[i]}")
                break
            divisor += 1
        else:
            # The else part of the while loop; executed if the number is prime
            i=i+1
            continue
        # Breaks the for loop if a composite number is found
        break 
else:
    # The else part of the for loop; executed if no composite numbers are found
    print("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 statement
 
counter = 1
num = 2
 
while(counter <= 10):
     
    if(counter%2 == 0):
        counter += 1
        # Skip the rest of the loop body and go to the next iteration
        continue 
     
    print(f"{num} * {counter} = {num*counter}")
     
    counter += 1
 
else:
    print("Inside the else block")
 
print("Outside the loop.")


Output

2 * 1 = 2
2 * 3 = 6
2 * 5 = 10
2 * 7 = 14
2 * 9 = 18
Inside the else block
Outside the loop.

Python While Else with a pass Statement

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 = 0
target = 5
 
# While loop to search for the target value
while counter < 10:
    if counter == target:
        print(f"Target value {target} found!")
        break
    counter += 1
else:
    pass
 
# Rest of the code outside the loop
print("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 input
 
max_attempts = 3
attempts = 0
 
while attempts < max_attempts:
    user_input = input("Enter a valid number: ")
     
    if user_input.isdigit():
        print(f"Valid input: {user_input}")
        break
    else:
        print("Invalid input. Please enter a numeric value.")
        attempts += 1
else:
    print(f"Exceeded maximum attempts ({max_attempts}). Exiting program.")


Output:

Enter a valid number: 4
Valid input: 4


Similar Reads

Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Python Else Loop
Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++ Code i=0 while i&lt;5: i+=1 print(&quot;i =&quot;
3 min read
Lambda with if but without else in Python
In Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value. Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we a
3 min read
How to use if, else &amp; elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else &amp; elif in Lambda Functions. Using if-else in lambda function The lambda function will return a value for every valida
2 min read
Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. Example: In this code, The system can not divide the number with zero so an ex
4 min read
Python List Comprehension Using If-Else
List comprehension in Python is a way to make the elements get added to the list more easily. We can use if-else with List Comprehension which makes the code smaller and more modular instead of using long if-else conditions making it very unstructured. In this article, we will see how we can use list comprehension with Python if-else. List Comprehe
3 min read
Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
6 min read
Python If Else on One Line
The if-elif-else statement is used in Python for decision-making i.e. the program will evaluate the test expression and execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions. This article will show how the traditional if...elif...else statement differs from If Elif i
3 min read
Avoiding elif and ELSE IF Ladder and Stairs Problem
This article focuses on discussing the elif and else if ladder and stairs problem and the solution for the same in the C and Python Programming languages. The ELIF and ELSE IF Ladder and Stairs ProblemThere are programmers who shy away from long sequences of IF, ELSE IF, ELSE IF, ELSE IF , etc. typically ending with a final ELSE clause. In language
6 min read
Python3 - if , if..else, Nested if, if-elif statements
There are situations in real life when we need to do some specific task and based on some specific conditions, we decide what we should do next. Similarly, there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditio
5 min read
Article Tags :
Practice Tags :