diamondpy
diamondpy

Reputation: 23

Python data validation not working as intended

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)

Upvotes: 1

Views: 121

Answers (4)

diamondpy
diamondpy

Reputation: 23

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)

Upvotes: 1

Damini Suthar
Damini Suthar

Reputation: 1492

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)

Upvotes: 1

Carl_M
Carl_M

Reputation: 948

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)

Upvotes: 1

Aryman Deshwal
Aryman Deshwal

Reputation: 175

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)

Upvotes: 1

Related Questions