Python数据验证未按预期工作



Python 3.8.12

该代码的预期目标是允许用户选择";牛肉"鸡肉"豆腐";,或";none";三明治如果用户没有输入其中一个选项,它将再次提示他们选择三明治。如果他们确实输入了其中一个选项,那么它将继续使用代码。

它工作不正常。它将不接受任何输入,无论是否有效。所有输入都会导致程序再次提示用户,而不是在程序有效的情况下继续执行程序。

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)

具有修改的逻辑:

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)

更好的方法是:

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)

您可以尝试使用

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)

基于Carl_M的实现

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)

相关内容

  • 没有找到相关文章

最新更新