我在python3中有这段代码,用于检查输入时的错误,但我需要确定输入是否为整数,如果不是,则打印错误消息。
有人能帮我找出while循环中的代码吗?谢谢
price = 110;
ttt = 1;
while price < 0 or price > 100:
price = input('Please enter your marks for Maths:');
ttt =ttt +1;
if ttt >= 2:
print( 'This is an invalid entry, Please enter a number between 0 and 100')发布于 2012-12-28 06:51:26
使用int()函数将其转换为整数。这将在无法执行转换时引发ValueError:
try:
price = int(price)
except ValueError as e:
print 'invalid entry:', e发布于 2012-12-28 07:22:25
您可能想要这样的代码,它既可以捕获价格是否为整数,也可以捕获价格是否在0到100之间,如果满足这些条件,则中断循环。
while True:
price = raw_input('Please enter your marks for Maths:')
try:
price = int(price)
if price < 0 or price > 100:
raise ValueError
break
except ValueError:
print "Please enter a whole number from 0 to 100"
print "The mark entered was", price或者,由于您具有可管理的少量可能值,因此您还可以执行以下操作:
valid_marks = [str(n) for n in range(101)]
price = None
while price is None:
price = raw_input('Please enter your marks for Maths:')
if not price in valid_marks:
price = None
print "Please enter a whole number from 0 to 100"发布于 2012-12-28 06:50:55
首先,使用raw_input而不是input。
此外,将ttt检查放在输入之前,以便正确显示错误:
price = 110;
ttt = 1;
while price < 0 or price > 100:
if ttt >= 2:
print 'This is an invalid entry, Please enter a number between 0 and 100';
price = raw_input('Please enter your marks for Maths:');
ttt = ttt +1;https://stackoverflow.com/questions/14062266
复制相似问题