简体   繁体   中英

How to break loop with ENTER input

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM