python输入错误检查

时间:2012-09-16 00:15:10

标签: python input while-loop

你好,我试图让我的输入只允许整数,一旦超过10,就会显示错误,任何帮助都会受到赞赏。

square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
triangle_ct = input("Enter an integer from 1-5 the number of triangles to draw: ")

while square_count(input) > 10:
    print ("Error!")
    square_count=input() #the statement reappears

while triangle_count(input) > 10:
    print ("Error!")
    triangle_count=input() #the statement reappears

1 个答案:

答案 0 :(得分:3)

我首选的技巧是使用带有中断的while True循环:

while True:
    square_ct = input("Enter an integer from 1-5 the number of squares to draw: ")
    if square_ct <= 10: break
    print "Error"

# use square_ct as normal

或者,在Python 3上:

while True:
    square_ct = int(input("Enter an integer from 1-5 the number of squares to draw: "))
    if square_ct <= 10: break
    print("Error")

# use square_ct as normal