gpt4 book ai didi

Python:如果/Elif 两次问单个问题而不是回答后继续?

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:07 25 4
gpt4 key购买 nike

我问用户一组字典中的问题:

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

如果用户说"is",一切正常。

但是,如果用户回答“否”,则会再次询问第一个问题(可能是因为我的 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']

最佳答案

出现此问题是因为您在每个 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

关于Python:如果/Elif 两次问单个问题而不是回答后继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com