我向用户询问字典中的一组问题:
questions = {
"strong": "Do ye like yer drinks strong? ",
"salty": "Do ye like it with a salty tang? ",
"bitter": "Are ye a lubber who likes it bitter? ",
"sweet": "Would ye like a bit of sweetness with yer poison? ",
"fruity": "Are ye one for a fruity finish? "
}
这些键与另一个词典相关联:
ingredients = {
"strong": ["glug of rum", "slug of whiskey", "splash of gin"],
"salty": ["olive on a stick", "salt-dusted rim", "rasher of bacon"],
"bitter": ["shake of bitters", "splash of tonic", "twist of lemon peel"],
"sweet": ["sugar cube", "spoonful of honey", "splash of cola"],
"fruity": ["slice of orange", "dash of cassis", "cherry on top"]
}
我通过为每个问题设置的“简单”if / elif问他们问题,并将他们的答案分配给新词典:
beverage = {}
def drink():
"""Find out user preferences and assign to new dictionary"""
if raw_input(questions["strong"]).lower() == "yes":
beverage["strong"] = ingredients["strong"]
elif raw_input(questions["strong"]).lower() == "no":
return False
if raw_input(questions["salty"]).lower() == "yes":
beverage["salty"] = ingredients["salty"]
elif raw_input(questions["salty"]).lower() == "no":
return False
...
drink()
最后打印饮料:
print beverage
如果用户说“是”则一切正常。
但是,如果用户回答“否”,则再次询问第一个问题(可能是因为我的if / elif结构使用raw_input()),然后只是跳过完成脚本的所有其他问题。
如何构建它以便如果用户对第一个问题说“不”,那么它会询问下一个问题而不是每个问题两次?
打印输出:
Do ye like yer drinks strong? yes
Do ye like it with a salty tang? no
Do ye like it with a salty tang? yes
Are ye a lubber who likes it bitter? no
Are ye a lubber who likes it bitter? yes
Would ye like a bit of sweetness with yer poison? no
Would ye like a bit of sweetness with yer poison? yes
Are ye one for a fruity finish? no
Are ye one for a fruity finish? yes
Yer cocktail is a made of a
['glug of rum']
答案 0 :(得分:3)
出现此问题是因为您在每个if..elif
案例中都获得了新的输入字符串。相反,您需要将输入分配给变量并使用if..elif
检查。
问两次问题:
if raw_input(questions["strong"]).lower() == "yes":
beverage["strong"] = ingredients["strong"]
elif raw_input(questions["strong"]).lower() == "no":
return False
问一次问题:
answer = raw_input(questions["strong"]).lower()
if answer == "yes":
beverage["strong"] = ingredients["strong"]
elif answer == "no":
return False