我有问题!我试图迭代一个列表,检查它是否在里面,如果它在里面进行下一步,如果不是,重复输入,直到用户输入该列表中的一个元素
接下来,我会提供我的代码,请将其中一些列表用于其他目的!我正在使用的是FoodAvaiable。
DictFood = {"pasta":["spaghetti"], "meat":["beef of deer", "sasuage"], "vegetables":["chips", "letucce"], "condiment":["sugar", "salt"], "fruit":["apple", "orange"], "sweet":["chocolate"], "drink":["beer", "water"]}
TypeFood = ["pasta", "fruit", "meat", "vegetables", "condiment", "sweet", "drink"]
DictValue = {"orange":1, "spaghetti":12, "salt":0.2, "chocolate":2, "beef of deer":1, "beer":0.3, "water":0.5, "fish":3, "chips":2, "sugar":0.2, "bread":2, "apple":1, "letucce":1, "sasuage":3}
FoodAvaiable = ["orange", "spaghetti", "salt", "chocolate", "beef of deer", "beer", "water", "fish", "chips", "sugar", "bread", "apple", "letucce", "sasuage"]
x = True
def food_type():
global user_option_f
print("What do you want to buy?")
print(FoodAvaiable)
user_option_f = input()
while x == True:
if user_option_f == FoodAvaiable[0]: #here I have my doubt!! I've tried using "or" to add "FoodAvaibale[1]" and so on, and I got a infinite loop, I've tried "range(len(FoodAvaiable))" didn't worked too
x == False
print("You choose {}!".format(user_option_f))
elif user_option_f != FoodAvaiable:
print("You choose an element which is not avaiable! Please select one of the list")
print(FoodAvaiable)
print("Choose one avaiable")
input()
return user_option_f
food_type()
如何让我的user_input_f遍历列表中的元素,检查它是否在内部。
很抱歉,如果之前有人询问,我搜索了很多没有找到任何可以帮助我的事情。先谢谢
答案 0 :(得分:0)
你可以使用嵌套的for循环来做到这一点,但正确的方法就是使用'in'运算符。
while True:
user_input = input('Food: ')
if user_input in FoodAvailable:
return user_input
else:
print('Choose one of {}'.format(', '.join(FoodAvailable)))
答案 1 :(得分:0)
我在一些答案的帮助下设法修复代码(感谢@UnoriginalNick和@StephenRauch)
DictFood = {"pasta":["spaghetti"], "meat":["beef of deer", "sasuage"], "vegetables":["chips", "letucce"], "condiment":["sugar", "salt"], "fruit":["apple", "orange"], "sweet":["chocolate"], "drink":["beer", "water"]}
TypeFood = ["pasta", "fruit", "meat", "vegetables", "condiment", "sweet", "drink"]
DictValue = {"orange":1, "spaghetti":12, "salt":0.2, "chocolate":2, "beef of deer":1, "beer":0.3, "water":0.5, "fish":3, "chips":2, "sugar":0.2, "bread":2, "apple":1, "letucce":1, "sasuage":3}
FoodAvaiable = ["orange", "spaghetti", "salt", "chocolate", "beef of deer", "beer", "water", "fish", "chips", "sugar", "bread", "apple", "letucce", "sasuage"]
def food_type():
x = True
global user_option_f
print("What do you want to buy?")
print(FoodAvaiable)
while x == True:
user_option_f = input()
if user_option_f in FoodAvaiable:
x = False
print("You choose {}!".format(user_option_f))
elif user_option_f not in FoodAvaiable:
print("You choose an element which is not avaiable! Please select one of the list")
print(FoodAvaiable)
print("Choose one avaiable")
input()
return user_option_f
food_type()
获取定义之外的输入给了我一个错误,所以我最终在def中编写它并对elif进行一些调整,也许我应该使用else而不是,但是因为这样看似稳定,我'保持它