Home > Back-end >  Python data validation not working as intended
Python data validation not working as intended

Time:02-28

Python 3.8.12

The intended goal of this code is to allow the user to select a "beef", "chicken", "tofu", or "none" sandwich. If the user does not enter one of those options, it will prompt them again to select a sandwich. If they do enter one of these options, then it will continue on with the code.

It is not working properly. It will not accept any input, valid or not. All input causes the program to prompt the user again, rather then moving on with the program if it is valid.

sandwich_choice = input("Select sandwich: ")
while sandwich_choice != "chicken" or sandwich_choice != "beef" or sandwich_choice != "tofu" or sandwich_choice != "none":
    sandwich_choice = input("\x1b[30;41m[!]\x1b[0mSelect sandwich: ")
else:
    pass
print("Sandwich selection is", sandwich_choice)

CodePudding user response:

With modified logic:

sandwich_choice = input("Select sandwich: ")
while sandwich_choice not in ('chicken', 'beef', 'tofu', 'none'):
    sandwich_choice = input("\x1b[30;41m[!]\x1b[0mSelect sandwich: ")
else:
    pass
print("Sandwich selection is", sandwich_choice)

CodePudding user response:

A better way would be:

sandwich_choice = ""
while True:
   sandwich_choice = input("blah blah blah")
   if sandwich_choice == "beef" or sandwich_choice == "chicken" or sandwich_choice == "tofu" or sandwich_choice == "none":
       break
print("Sandwich selection is",sandwich_choice)

CodePudding user response:

You can try with

 sandwich_choice = input("Select sandwich: ")
    list_sandwich = ['chicken', 'beef', 'tofu', 'none']
    while sandwich_choice not in list_sandwich:
        sandwich_choice = input("\x1b[30;41m[!]\x1b[0mSelect sandwich: ")
    else:
        pass
    print("Sandwich selection is", sandwich_choice)

CodePudding user response:

Based on Carl_M's implementation

sandwich_choice = input("Select sandwich: ")
while sandwich_choice not in ('chicken', 'beef', 'tofu', 'none'):
        sandwich_choice = input("\x1b[30;41m[!]\x1b[0mSelect sandwich: ")
else:
        print("Sandwich selection is", sandwich_choice)
  • Related