8

我在 python 3 中有这段代码,用于检查输入错误,但我需要确定输入是否为整数,如果不是则打印错误消息。

谁能帮我找出我的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')
4

4 回答 4

9

使用该int()函数转换为整数。这将在无法进行转换时引发 ValueError :

try:
    price = int(price)
except ValueError as e:
    print 'invalid entry:', e
于 2012-12-27T22:51:25.660 回答
3

你可能想要这样的东西,它会捕获价格是否为整数以及是否在 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-27T23:22:25.350 回答
2

首先,使用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;
于 2012-12-27T22:50:54.787 回答
0

我会说最简单的事情是做而不是做

price=int(price)

price=int(110)
于 2019-10-20T11:52:47.583 回答