gpt4 book ai didi

python - 如何根据 Python 中的特定用户输入循环条件语句?

转载 作者:太空宇宙 更新时间:2023-11-03 12:59:09 25 4
gpt4 key购买 nike

例如,在这个示例代码中,

greeting = input("What's your favorite cheese?")
if greeting == "cheddar":
print("Mine too!")

elif greeting == "bleu cheese":
print("Gross!")

elif greeting == "parmesan":
print("Delicious!")

else:
cheese = input("That's not a cheese, try again!")
cheese == greeting

如果我输入“Mozzarella”作为“问候语”,我希望它提示我“那不是奶酪”,并且让我重新输入“问候语”的值,直到切达干酪、蓝纹奶酪或帕尔马干酪出现输入,如果这有意义的话。我有一个更大的程序,我正在为涉及多个相互嵌套的条件语句的类工作,并且对于每个“组”语句,我希望能够在用户输入无效条目时打印错误消息并允许他们无需重新启动程序即可重试。

最佳答案

尝试以下操作

greeting = input("What's your favorite cheese?") #Get input
while greeting not in ['cheddar', 'blue cheese', 'parmesan']: #Check to see if the input is not a cheese
greeting = input("That's not a cheese, try again!")
else: #If it is a cheese, proceed
if greeting == "cheddar":
print("Mine too!")

elif greeting == "bleu cheese":
print("Gross!")

elif greeting == "parmesan":
print("Delicious!")

else:
cheese = input("That's not a cheese, try again!")

What's your favorite cheese? peanut butter
That's not a cheese, try again! ketchup
That's not a cheese, try again! parmesan
Delicious!

关于python - 如何根据 Python 中的特定用户输入循环条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972790/

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