For else in python
In this tutorial, you will learn about the for else loop in python, its syntax and how to use it in your python program.
For else loop in python
The use of the ‘else’ condition in the ‘for’ statement executes a set of codes when the program jumps out of the loop.
Syntax:
for condition: statements else: statements
Now let’s use for else loop in a program.
Sample program using the for else program
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1295′,’_blank’)”]
for i in range(57, 60): print(i) else: print("Loop has ended")
When you execute the above code, it prints the values from 57-59 and once the loop is ended the code prints the statement “ Loop has ended”.
Output:
57 58 59 Loop has ended
Example-2
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1296′,’_blank’)”]
for i in range(5): print(i) else: print("Loop has ended")
Output:
0 1 2 3 4 Loop has ended
In this program, when you execute the code, it prints the numbers 0-4 and when the for loop is ended, it prints the statement in the else section “Loop has ended”.