1

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

5
  • 3
    Python does not have a do-while loop. Commented Apr 30, 2017 at 0:53
  • @RemyJ Somebody failed early in my coding education (probably me). I had always thought "do while" loops and "while" loops were synonymous. Commented Apr 30, 2017 at 4:39
  • They​ are similar, what sets them apart it the position of the condition. In the while loop the test is done before entering the loop, that means that your instructions within the loop might never gets executed. Where as in the do-while loop the instructions will get executed at least once. Commented Apr 30, 2017 at 20:08
  • 1
    To correct the failure in your coding education I suggest that you take a look at do-while, while and while-True. ;-) Commented Apr 30, 2017 at 20:08
  • The last link will give you an alternative to the do-while loop and why it is not present in Python (check the references in the bottom of the page for that). Commented Apr 30, 2017 at 20:09

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.