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.
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
#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.
Login/Signup to comment