I am writing a python program that allows users to enter 1 or 2, no other number. If they were to type 0 or 3 for example, there will be an error message.

Below is my code, it seems to allow users to enter any other numbers and continue to proceed to another line.

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 Answers

0
Miklos Horvath On

It is the same when you write: (numApplicants == "1") or ("2")

"2" is not an empty string, it means it is True.

Use it like this:

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: ")

or if you need to check more values maybe better to use the "in" operator:

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: ")