Alex
Alex

Reputation: 378

Python: execute on last iteration of while loop

My goal is to execute an operation on the last operation of while loop only. My while loop is nested in a for loop.

Currently I go for:

for i in range(10):
    indicator = False
    while(...):
       do something
       indicator = True  
    if indicator == True:
        do one operation
        indicator = False
    do something not in while loop

While it seems to work, it doesn't look elegant. Is there a more pythonic way?

Upvotes: 0

Views: 1065

Answers (1)

Kang San Lee
Kang San Lee

Reputation: 382

If you are not using break in while loop, you can use while ... else expression.

https://www.pythontutorial.net/python-basics/python-while-else/

Upvotes: 2

Related Questions