Python while循环

mig*_*uel 6 python

我在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')
Run Code Online (Sandbox Code Playgroud)

Rol*_*ith 8

使用该int()函数转换为整数.当它无法进行转换时会引发ValueError:

try:
    price = int(price)
except ValueError as e:
    print 'invalid entry:', e
Run Code Online (Sandbox Code Playgroud)


Fog*_*zie 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;
Run Code Online (Sandbox Code Playgroud)