Home > OS >  How to break loop with ENTER input
How to break loop with ENTER input

Time:12-01

I want to break this loop when I press ENTER then display the list but it doesn't recognize '' since it has to be a string

list = []
while True:
    try:
        num = int(input('Enter integers:'))
        list.append(num)
    except ValueError:
        print('Not an integer, try again')
        continue
    if num == '':
        list.sort()
        print(list)
        break

I also want to display "x is not an integer, try again." but I keep getting an error when I try

print(num   'is not and integer, try again.')

CodePudding user response:

You're converting it to int too early, perform the check and then convert it:

list = []
while True:
    num = input('Enter integers:')
    if num == '':
        list.sort()
        print(list)
        break
    try:
        list.append(int(num))
    except ValueError:
        print('Not an integer, try again')

CodePudding user response:

If you press enter, num will be the empty string ''.

int('') raises a ValueError which makes the loop continue and skip your breaking condidtion.

edit: rearrange your code like in Pedro's answer.

  • Related