[英]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我想在按 ENTER 时打破这个循环,然后显示列表,但它不能识别 '' 因为它必须是一个字符串
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."我还想显示“x 不是 integer,再试一次。” 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:您将其转换为int
为时过早,执行检查然后将其转换:
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 ''
.如果按回车, num
将是空字符串''
。
int('')
raises a ValueError
which makes the loop continue
and skip your breaking condidtion. int('')
引发一个ValueError
,它使循环continue
并跳过您的中断条件。
edit: rearrange your code like in Pedro's answer.编辑:重新排列你的代码,就像佩德罗的回答一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.