0

Let me explain my question with an example.

Here I have a simple for loop:

for x in range(10)
    print(x)

output: 0 1 2 3 4 5 6 7 8 9

Now if I take user input like from a flask website or from the microphone for the person to say yes or no then I want it to start the for loop over again or break out of the for loop depending on the response. If the person says yes then redo the for loop again or if the person says no break out of the for loop and continue with the other code.

Question:

How to repeat a for loop after user input.

I am asking how to do this with a for loop and not a while loop because I want to put this inside of a while loop that does other things.

1
  • why not... put the for loop that you want to repeat until something happens... into a while loop? You know, the thing that you already know about, that you use for repeating code until something happens? You say you already "want to put this inside of a while loop"... so what are the conditions for that loop? How is that while loop not already solving the problem for you? Basically I don't understand how you actually have a question here. It seems like you already perfectly understand how it works. Commented Jan 2, 2022 at 21:21

2 Answers 2

1

Put your loop inside another loop:

while True:
    for x in range(10):
        print(x)
    if not input("Do it again? ").lower().startswith("y"):
        break

If the number of nested loops starts to get unwieldy (anything past about three levels deep starts to get hard to read IMO), put some of that logic inside a function:

def count_to_ten():
    for x in range(10):
        print(x)


while True:
    count_to_ten()
    if not input("Do it again? ").lower().startswith("y"):
        break
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't specified how to retrieve the input, so I've left that omitted from the following code snippet:

should_run_loop = True

while should_run_loop:
    for x in range(10)
        print(x)
    should_run_loop = # code to retrieve input

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.