通过输入错误的输入来阻止用户破坏代码

时间:2016-01-11 12:29:52

标签: python

如何通过输入错误的功能来阻止用户破坏代码?例如:

category = raw_input("Please choose the number of the category you which to play with!")

if category == 1:
    print "Thankyou for choosing",category,".The game will commence shortly!"

if category == 2:
    print "Thankyou for choosing",category,".The game will commence shortly!"

if category == 3:
    print "Thankyou for choosing",category,".The game will commence shortly!"

else:
    print "Incorrect input choose again!"

这样可行但是当我在代码中输入正确的输入时,它仍然会出现'输入错误输入再次选择!'我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

函数raw_input返回一个字符串,并将其与int进行比较。这就是为什么你总是得到else语句的if条款。在比较之前,您应该像int一样投射:

category = int(raw_input("Please choose the number of the category you which to play with!"))