The else clause is only executed when your while condition becomes false. If you break out of the loop it won’t be executed.
The following loop will run the else code:
x = 0
while x < 5:
x += 1
print (x)
else:
print ('Else statement has run')
print ('End')
OUT:
x = 0
while x < 5:
x += 1
print (x)
else:
print ('Else statement has run')
print ('End')
OUT:
1
2
3
4
5
Else statement has run
End
The following loop with a break will not run the else code:
x = 0
while x < 5:
x += 1
print (x)
if x >3:
break
else:
print ('Else statement has run')
print ('End')
OUT:
1
2
3
4
End
One thought on “13. Python basics: else after while”