0

How do you break out of the loop when you get in this situation (I'm still a beginner so I don't know everything even though this might be a "simple" problem)?

while True:
    s = input('Enter something : ')
    if len(s) > 3:
        print('too big')
        continue
    if s == 'quit':
        break
    print('something')

As you can see you can't break out of the loop because "quit" has more than 3 characters.

mort
  • 12,988
  • 14
  • 52
  • 97
user3711671
  • 823
  • 1
  • 6
  • 13

2 Answers2

3

You could use iter with a sentinel value and a for loop instead of while:

for s in iter(lambda: input('Enter something : '), 'quit'):
    if len(s) > 3:
        print('too big')
    else:
        print('something')
sloth
  • 99,095
  • 21
  • 171
  • 219
  • 1
    clever. A bit too clever for OP perhaps. While we're clever, you can change `lambda: input('Enter something : ')` to `partial(input,"Enter Something : ")`. – Benjamin Gruenbaum Jun 05 '14 at 14:55
  • 1
    I don't think it's particularly clever. It's idiomatic to use `for`/`iter` for a "until `x` becomes `y` do `z`"-kind of loop. – sloth Jun 05 '14 at 15:01
2

You should restructure your program like so, placing the second if-statement above the first:

while True:
    s = input('Enter something : ')
    if s == 'quit':  # Do this check first
        break
    elif len(s) > 3:  # Then see if the input is too long
        print('too big')
        continue
    print('something')
  • 1
    I think it might be preferable to change it to `while s != 'quit'` for a more understandable flow. Personally, I'd also break up the validity check outside and wrap `input` but that's less relevant here. – Benjamin Gruenbaum Jun 05 '14 at 14:52
  • 4
    @BenjaminGruenbaum I disagree - then you need to initialise `s` outside the loop. – jonrsharpe Jun 05 '14 at 14:54
  • Thank you, it works now but why does the order of if statements matter that much in this case? – user3711671 Jun 05 '14 at 17:46
  • In your old code, if the user entered `"quit"`, the second if-statement would never be executed because the condition of the first passed. Therefore, I put the second if-statement first so that it is executed immediately. Then, once we have confirmed that the user did not enter quit, we can check the length of the input and print the `"too big"` message if necessary. –  Jun 05 '14 at 17:52