-1

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: ")
  • 2
    Hint: See what `numApplicants == "1" or "2"` evaluates to on its own. It's not what you think it is. – Andrew Fan May 04 '19 at 05:12
  • 2
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Austin May 04 '19 at 05:19
  • I am sure there are similar questions, so it can be a duplication, but not a duplication of that link. That is a different queastion. –  May 04 '19 at 05:38

1 Answers1

0

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: ")
  • I followed your first example. It seems to allow me to enter other numbers other than 1 or 2 and proceeds to the next question. ONLY THEN it prints the error message. seems to have problems with the sequence – pythoncuriosity May 04 '19 at 07:23
  • Oh, do you want to avoid to type those numbers? If I remember well it is not possible with the input function. But I am sure there is a solution. I will check it later. –  May 04 '19 at 08:24