简体   繁体   中英

Repeat a for loop after user input?

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.

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

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, put some of it 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM