Open In App

Using Else Conditional Statement With For loop in Python

Last Updated : 13 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 by a break statement.

Else block is executed in below Python 3.x program: 

Python




for i in range(1, 4):
    print(i)
else# Executed because no break in for
    print("No Break")


Output : 

1
2
3
No Break

Else block is NOT executed in Python 3.x or below: 

Python




for i in range(1, 4):
    print(i)
    break
else: # Not executed as there is a break
    print("No Break")


Output : 

1

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 the third iteration of the loop and hence the else present after the for loop is ignored. In the case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.

Python




# Python 3.x program to check if an array consists 
# of even number
def contains_even_number(l):
    for ele in l:
        if ele % 2 == 0:
            print ("list contains an even number")
            break
  
    # This else executes only if break is NEVER
    # reached and loop terminated after all iterations.
    else:     
        print ("list does not contain an even number")
  
# Driver code
print ("For List 1:")
contains_even_number([1, 9, 8])
print (" \nFor List 2:")
contains_even_number([1, 3, 5])


Output: 

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 the following program. 

Python




count = 0
while (count < 1):    
    count = count+1
    print(count)
    break
else:
    print("No Break")




Previous Article
Next Article

Similar Reads

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 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
Loop Through a List using While Loop in Python
In Python, the while loop is a versatile construct that allows you to repeatedly execute a block of code as long as a specified condition is true. When it comes to looping through a list, the while loop can be a handy alternative to the more commonly used for loop. In this article, we'll explore four simple examples of how to loop through a list us
3 min read
Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
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
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 While Else
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. Wha
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
Article Tags :
Practice Tags :