Python while else nothing a while statement may have an optional else clause. With the While else statement block of code execute only once when the condition no longer is true.
while condition: # code block to run else: # else clause code block
else clause is only executed when your
while condition becomes false. If you
break out of the loop, or if an exception is raised, it won’t be executed.
Example while else in Python
Simple example code Print a message once the condition is false.
i = 1 while i < 6: print(i) i += 1 else: print("Else block")
If you’re looping through a list looking for a value:
values = [2, 3, 5, 7, 11, 13, 17, 25] for value in values: if value == 5: print ("Found it!") break else: print("Nowhere to be found. :-(")
Output: Found it!
Do comment if you have any doubts or suggestions on this Pytoh while loop topic
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.