Else loop in Python
Else Loop :
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.
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.
- 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 :
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.
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.