-3

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?

Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
Reut
  • 1,555
  • 4
  • 23
  • 55

2 Answers2

1

If you only want to exit both loops, you can simply just create a flag to do the check in both loops:

count = 0
should_break = 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 == "q":
            should_break = True
            break
            
        else:
            print('please enter either y/n')

    if should_break:
        break

print('DONE!')

If you're trying to exit your program completely, you may do the following:

if rep=='q':
    exit()
chepner
  • 497,756
  • 71
  • 530
  • 681
Kasper
  • 588
  • 3
  • 16
1

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!')
Shubham Vaishnav
  • 1,637
  • 6
  • 18