user3711671
user3711671

Reputation: 853

Python - what to do when you can't use the break statement?

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.

Upvotes: 0

Views: 2502

Answers (2)

sloth
sloth

Reputation: 101052

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')

Upvotes: 3

user2555451
user2555451

Reputation:

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')

Upvotes: 2

Related Questions