You can use an else
on a while
loop which will hit if the loop runs normally. If the loop is terminated prematurely though (using break
or return
), the code in the else
won't execute. This construct can also be used with a for
loop.
>>> while True:
... break
... else:
... print("hits")
...
>>> a = True
>>> while a:
... a = False
... else:
... print("hits")
...
hits
#looping