Else Loop in Python

Else Loop in Python: 

Other programming languages like c/c++/java , it has some restriction for using else conditional statement, i.e. we can not use else statement without if statement.But in python we can use else statement without leading if-statement. 

use of else loop in python

Else Loop in Python

Python allows us to use else keyword with the for and while loops too. The else block appears after the body of the loop. The statements in the else block will be executed after all iterations are completed. 

Use : 

  • We can use else statement to check a loop has a break condition or not.
    • This type of condition is used when a loop has break statement and output depends on the fact that loop ends by itself or by using break statement

Code 1 :

Run

#else statement 
 
b=10 
for i in range(5,11):
    if(i==b):
        break 
    else:
        print("loop ends after completing it's iteration")
Output:
loop ends after completing it's iteration
loop ends after completing it's iteration
loop ends after completing it's iteration
loop ends after completing it's iteration
loop ends after completing it's iteration

In the above program Else loop will be executed if and only if for loops terminates by completing it’s all iterations.

Code 2:

Run
#else statement 
 
#to check does a word  contains 'X' in it
b='PrepInsta'             #here our word is PrepInsta
for i in range(len(b)):
    if(b[i]=='X'):
        break 
    else:
        print("No prepInsta does not conatins X")
Output:
No prepInsta does not conatins X

In the above program we can see that loop will terminates forcefully if an string contains character “X” in it. If Loop terminates due to if-statement inside the loop , the else statement outside the loop will not be excuted  and if loop terminates after completing all it’s iteration else statement will be executed.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription