Home > front end >  Python: execute on last iteration of while loop
Python: execute on last iteration of while loop

Time:02-25

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?

CodePudding user response:

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

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

CodePudding user response:

What is the problem just to do this? The action will be executed immediately after the loop.

for i in range(10):
    while(...):
       do something
    do something not in while loop

If this does not satisfy your needs, could you clarify your question?

  • Related