【问题标题】:Ending a loop properly正确结束循环
【发布时间】:2019-05-05 07:58:35
【问题描述】:

我被困在我试图完成的这段代码上。我希望它打印“没有更多的食谱”,但它会打印两次“让我们选择不同的餐点”。

my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
        "recipe2":[["a","b","c"], "g", "h", "i"],
        "recipe3":[["a","b","c"], "j", "k", "l"],
        "recipe4":["x", "y", "z"]}

for k,v in bank.items():
    if my_choice in v:
        print(f"Your meal we have chosen for you is {k,v}")
        print("Do you like your meal? y/n")
        choice = input()
    if choice == "y":
        print("Enjoy your meal!")
        break
    elif choice == "n":
        print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
    else:
        print("Please select y or n to keep your meal or select a different recipe.")
        print(f"Your meal we have chosen for you is {k,v}")
        print("Do you like your meal? y/n")
        choice = input()

        if len(my_choice) in food_bank.items() > len(v):
            print("Sorry we have no more recipes")

【问题讨论】:

  • 谢谢我其实很喜欢这个解决方案。唯一的这个是一旦它没有找到 my_choice 的任何变体,它就会生成下一个替代配方,即 recipe4。在给出来自 my_choice 的替代食谱之前,我有什么方法可以打印“让我们尝试一些不同的东西”?
  • 我喜欢使用 lambda,我必须对其进行更多研究,我会尝试更多地了解它们,因为我觉得它们对未来的开发非常有用。感谢双方提供的两种解决方案,它为我提供了另一种看待事物的方式,并希望更多地学习 python!非常感谢您提供的任何帮助:)

标签: python python-3.x loops for-loop if-statement


【解决方案1】:

首先,if choice == "y"elif choice == "n" 语句应该在 if my_choice in v:

其次,当elif choice == "n" 时,您需要知道这是否是最后一个配方(即“recipe4”)。

my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
        "recipe2":[["a","b","c"], "g", "h", "i"],
        "recipe3":[["a","b","c"], "j", "k", "l"],
        "recipe4":["x", "y", "z"]}

for k,v in bank.items():
    if my_choice in v:
        print(f"Your meal we have chosen for you is {k,v}")
        print("Do you like your meal? y/n")
        choice = input()
        if choice == "y":
            print("Enjoy your meal!")
            break
        elif choice == "n":
            if "recipe4" != "recipe4":
                print("Lets find you a different meal") # this prints out twice when the alternate recipes run out.
            else:
                print("Sorry we have no more recipes")
        else:
            print("Please select y or n to keep your meal or select a different recipe.")
            print(f"Your meal we have chosen for you is {k,v}")
            print("Do you like your meal? y/n")
            choice = input()

【讨论】:

  • 看起来我需要知道配方的每个位置以及“银行”对象中哪个配方在哪个位置之后。理想情况下,“银行”将容纳 100 或 1000 种食谱,所以基本上我需要将下一个食谱放在与 my_choice 不匹配的列表中——这会告诉代码停止..正确吗?谢谢你的帮助:)
  • @SinclairAkoto 正确。所以最好使用while循环。
【解决方案2】:

如果你重复输入'n',那么一旦循环到达'recipe4',它不包含'my_choice'/'["a","b","c"],那么新的值就不是设置为“选择”。所以它从上次看到'n',并第二次打印不同的餐文本。

这是我对您的代码的建议。

my_choice = ["a","b","c"]
bank = {"recipe1":[["a","b","c"], "d", "e", "f"],
        "recipe2":[["a","b","c"], "g", "h", "i"],
        "recipe3":[["a","b","c"], "j", "k", "l"],
        "recipe4":["x", "y", "z"]}

# Create a list from your dictionary
bankList = list(bank.items())
# And then sort it according to whether 'my_choice' is in a given recipe
# This way, the later loop will go through the matching recipes first
bankList.sort(key=lambda recipe: my_choice in recipe[1], reverse=True)

choice = None
for k, v in bank.items():
    if choice == "n":
        print("Let's find you a different meal")
    print(f"The meal we have chosen for you is {k,v}")
    print("Do you like your meal? y/n")
    choice = input()

    # If the user did not enter 'y' or 'n', keep asking until they do
    while choice not in ["y", "n"]:
        print("Please select y or n to keep your meal or select a different recipe.")
        print(f"The meal we have chosen for you is {k,v}")
        print("Do you like your meal? y/n")
        choice = input()

    if choice == "y":
        print("Enjoy your meal!")
        break
else:
    # This code will only run if the loop completes without breaking
    # In other words, if all recipes are considered and the user never says 'y' to any of them
    print("Sorry, we have no more recipes")

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 2021-06-05
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2012-03-17
    • 2019-03-17
    • 2012-09-16
    相关资源
    最近更新 更多