Search code examples
pythonfor-loopwhile-loopexit

quit while loop inside for loop


I have the following logic in my code:

count=0

for x in lst:
    print('hello!')

    while True:
        rep=input('save this?y/n?')
        print(rep)

        if rep=="y":
            print('wow amazing')
            count=count+1
            break

        elif rep=="n":
            print('moving to next target')
            count=count+1
            break

            
        else:
            print('please enter either y/n')


print('DONE!')

I want to add a condition that if rep=="quit", the code will stop running (also stop the for loop not only the while loop). currently, break just stop the current while loop but not the whole for loop. how can I quit the whole for loop base don value inserted in the while loop?


Solution

  • exit_loop: variable helps to make the decision when to quit the outer loop

    count=0
    exit_loop = False
    for x in lst:
        print('hello!')
        while True:
            rep=input('save this?y/n?')
            print(rep)
            if rep=="y":
                print('wow amazing')
                count=count+1
                break
            elif rep=="n":
                print('moving to next target')
                count=count+1
                break
            elif rep=="quit":
                print("Quitting")
                exit_loop = True
                break    
            else:
                print('please enter either y/n')
        if exit_loop:
            break
    
    print('DONE!')