为什么我仍然可以输入1或2以外的数字

时间:2019-05-04 05:10:02

标签: python-3.x

我正在编写一个Python程序,允许用户输入1或2,不能输入其他数字。例如,如果输入0或3,则会出现错误消息。

下面是我的代码,它似乎允许用户输入其他任何数字并继续前进到另一行。

numApplicants = input("Enter number of applicants, valid values from 1 to 2: ")
sgCitizenship = input("At least one buyer has Singapore citizenship? Y/N: ")


if numApplicants == "1" or "2":
    print(sgCitizenship)
else:
    print("Invalid input! Please enter number of applicants, valid values from 1 to 2: ")

1 个答案:

答案 0 :(得分:0)

您写的是相同的:(numApplicants ==“ 1”)或(“ 2”)

“ 2”不是一个空字符串,表示它是True。

像这样使用它:

numApplicants = input("Enter number of applicants, valid values from 1 to 2: ")
sgCitizenship = input("At least one buyer has Singapore citizenship? Y/N: ")


if numApplicants == "1" or numApplicants == "2":
    print(sgCitizenship)
else:
    print("Invalid input! Please enter number of applicants, valid values from 1 to 2: ")

或者如果您需要检查更多的值,则最好使用“ in”运算符:

numApplicants = input("Enter number of applicants, valid values from 1 to 2: ")
sgCitizenship = input("At least one buyer has Singapore citizenship? Y/N: ")


if numApplicants in ["1","2"]:
    print(sgCitizenship)
else:
    print("Invalid input! Please enter number of applicants, valid values from 1 to 2: ")