While else loop in Python
In this lesson, you will learn about the While Else loop in Python with examples and how to use it in your python programs.
While Else in Python
In the while else loop, the ‘else’ is a conditional statement. Here, it is used to run a block of code when the while condition becomes false.
Syntax:
while expression: statement(s) else: statement(s)
Let us understand the concept of while else with the help a simple program.
Simple program using while loop with conditional statement else in python
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1226′,’_blank’)”]
a = 57 while a < 60: print(a) a += 1 else: print("Value of a has exceeded 60 ")
When you run this program, the while loop iterates through the given condition. It prints the values from 57-59 and when the iteration reaches the value 60, the while condition becomes false. So the else condition is executed which returns the string “Value of a has exceeded 60”.
Output:
57 58 59 Value of a has exceeded 60