Home > Back-end >  Repeat a for loop after user input?
Repeat a for loop after user input?

Time:01-03

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related