3 回答
TA贡献2036条经验 获得超8个赞
如果问题不在您的列表中,它将遍历列表,然后在尝试访问列表中不存在的元素时抛出超出范围的索引。
你能用字典吗?
questions = {
"hello": "world",
"yellow": "I pref red",
"horse": "I pref dog"
}
quest = str(input('Which your question: '))
while (quest != '@'):
if quest in questions:
print(questions[quest])
else:
print("invalid input")
quest = str(input('Which your question: '))
建议阅读一些关于字典的文档:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
https://realpython.com/python-dicts/
TA贡献1784条经验 获得超9个赞
如果答案不在列表中,则counter==x(指的是不存在的元素)。
通常,不应使用并行列表,因为它们难以操作和维护。更好的解决方案是使用字典:
qAndA = {"hello" : "world", "yellow" : "I pref red",
"horse": "I pref dog"}
if quest in qAndA:
print(qAndA[quest]) # Otherwise, repeat
TA贡献1853条经验 获得超9个赞
您可以使用字典结构:
questions = {
"hello": "world",
"yellow": "I pref red",
"horse": "I pref dog"
}
quest = ""
while quest != '@':
quest = str(input('Which your question: '))
answer = questions.get(quest, "I have no answer")
print(answer)
添加回答
举报