2

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

2 Answers 2

5

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Consider using another name for list.
2

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.

2 Comments

But this would also print 'Not an integer, try again'
@PedroMaia true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.