for Loop with else
'''
else statement in Loop:
We have learnt before that else clause is used with if-statement.
But Python allows the else keyword to be used with 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 the iterations are completed.
The program exits the loop after else block is executed.
'''
#Example:
for i in range(5):
print(i)
else:
print("Sorry no i")
#output = 0
1
2
3
4
#Sorry no i
for i in[]:
print(i)
else:
print("Sorry no i")
#output = Sorry no i
for i in range(6):
print(i)
if i == 4:
break
else:
print("Sorry no i")
# output =
# 0
# 1
# 2
# 3
# 4
#Here else-statement didn't execute because loop is completed after the if-statement.
i = 0
while i<7:
print(i)
i = i + 1
if i == 4:
break
else:
print("Sorry no i")
# output =
# 0
# 1
# 2
# 3
i = 0
while i<7:
print(i)
i = i + 1
else:
print("Sorry no i")
# output =
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# Sorry no i
#Here the loop didn't break or complete at i == 4, so the loop continued till else=statement.
for x in range(5):
print("iteration no {} in for loop.format(x+1)")
else:
print("else block in loop")
print("Out of loop")
#output =
# iteration no {} in for loop.format(x+1)
# iteration no {} in for loop.format(x+1)
# iteration no {} in for loop.format(x+1)
# iteration no {} in for loop.format(x+1)
# iteration no {} in for loop.format(x+1)
# else block in loop
# Out of loop
Comments
Post a Comment