Dallium
Dallium

Reputation: 111

Can Python evaluate a while loop after executing the code?

Other languages allow you to something like

Do

loop body

While conditions

This guarantees the loop runs at least once, and allows you to have user input determine the conditions inside the loop without having to initialize them first. Does Python support this type of loop?

Edit: I'm not looking for a work around. I went with

quitstr = self._search_loop()
while quitstr != 'y':
    quitstr = self._search_loop()

I am only asking whether or not Python supports post-execution loop evaluation

Upvotes: 1

Views: 1763

Answers (2)

E. Ducateme
E. Ducateme

Reputation: 4248

An option for this situation is to set the while loop to True and do the condition checking at the end:

should_break = False

while True:
    # do the loop body

    # AND potentially do something that impacts the 
    # value of should_break

    if X > Y:
        should_break = True

    if should_break == True:
        break                # This breaks out of the while loop

As long as should_break remains False, this code will:

  1. Run at least once
  2. Continue to run

But once the X > Y condition becomes True, the while loop will end.

Upvotes: 1

nguyen thanh chinh
nguyen thanh chinh

Reputation: 161

I am not sure what you are trying to do.But You can implement a do-while loop like this:

while True:
  loop body
  if break_condition:
    break

or

loop body
while not break_condition:
    loop body

Upvotes: 3

Related Questions