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 by a break statement.
Else block is executed in below Python 3.x program:
1 2 3 No Break
Else block is NOT executed in below Python 3.x program:
Such type of else is useful only if there is an if condition present inside the loop which somehow depends on the loop variable.
In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration. Therefore for the array [1, 9, 8] the if is executed in third iteration of the loop and hence the else present after the for loop is ignored. In case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.
For List 1: list contains an even number For List 2: list does not contain an even number
As an exercise, predict the output of following program.
This article is contributed by Harshit Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python Else Loop
- Python - Conditional String Append
- Conditional Decorators in Python
- Python - Conditional Prefix in List
- Conditional Inheritance in Python
- Python - Length Conditional Concatenation
- Python if else
- Try, Except, else and Finally in Python
- Conditional operation on Pandas DataFrame columns
- NLP | Storing Conditional Frequency Distribution in Redis
- Mahotas – Conditional Dilating Image
- Mahotas – Conditional Eroding Image
- Mahotas – Conditional Watershed of Image
- Python3 - if , if..else, Nested if, if-elif statements
- Print first m multiples of n without using any loop in Python
- Python | Using for loop in Flask
- How to write an empty function in Python - pass statement?
- Statement, Indentation and Comment in Python
- with statement in Python
- Python return statement
Improved By : tarun2207