【问题标题】:I cant pick a choice after looping循环后我无法选择
【发布时间】:2022-07-11 22:35:50
【问题描述】:
def print_menu():
    print('1. American')
    print('2. Asian')
    print('3. Indian')
    print('4. Mexican')
    print('5. French')
    print('6. Italian')
    print('7. Seafood')
    print('8. Pizza')
print_menu()
menu = input('\nChoose where you want to eat from-->')
if menu == "1":
    def american_menu():
        print('1. Dempsey Burger Pub')
        print('2. Redrock Canyon Grill-Wichita')
        print("3. Cheddar's Scratch Kitchen")
        print("4. Neighbors| Restaurant & Bar")
        print("5. The Kitchen")
        print("6. Firebirds Wood Fired Grill")
        print("7. Chicken and Pickle")
    american_menu()
    american = input("\nChoose which American Restaurant--> ")
    if american == "1":
        print("\nCall Dempsey Burger Pub")
        

    while True:
        go_back = input("Will you like to try another menu option?: ")
        if go_back == "Yes":
            print_menu()
        else:
            print("We'll continue with your current choice")
        break

所以我尝试循环播放它,以便它再次从美食中选择并继续前往您想吃的地方,但到目前为止,它只是询问 go_back,在我说是之后......它会再次重复 go_back 任何帮助将不胜感激。谢谢。我希望它循环回到选择,选择我选择的选择和子选择,而不是仅仅选择选择而不做任何事情。再次感谢

注意:这是一项任务,我被卡住了,而且我有一个选择列表,但由于站点原因无法发布。

【问题讨论】:

  • print_menu() 是做什么的?如果这回到同一个函数的开头,你将重新进入同一个循环的另一个版本,你将不得不两次跳出它(每次加一个"yes") 真正地走出来。
  • 所以打印菜单是我制作的美食列表,现在,代码是,如果有人不喜欢他们所做的选择,他们可以返回美食菜单并从中进行选择'我会问他们想在什么地方吃饭,但出于某种原因,它只要求提供美食而不是餐厅
  • 这并没有澄清任何事情,因为我无法从该描述中判断您共享的代码是否是print_menu 的一部分。也许你应该分享整个代码?
  • def print_menu(): xxxx print_menu() menu=input('选择你想吃的地方') if menu=="1": def american_menu() american_menu() american=input(选择哪家美式餐厅)如果美国==1 从这里插入,而这里是新的堆栈所以不知道如何正确共享代码
  • 请编辑您的原始问题,而不是在 cmets 中发布代码,因为 cmets 不保留格式。

标签: python python-3.x


【解决方案1】:

print_menu 编写一个while 循环并将continue 更改为break


def print_menu():
    while True:
    #Use 2 while loops if you want. But the loop you are using is not needed  

while True:
    go_back = input("Will you like to try another menu option?: ")
    if go_back == "Yes":
        print_menu()
        break
    else:
        print("We'll continue with your current choice")
        break

第二个选项:


def print_menu():
    while True:
    #Just use "while" here instead of the second one

go_back = input("Will you like to try another menu option?: ")
if go_back == "Yes":
    print_menu()
else:
   print("We'll continue with your current choice")

【讨论】:

  • 非常感谢,但我刚刚发布了代码,以便您了解我在说什么
【解决方案2】:

您根本不需要使用while True 循环。它可能会导致无限循环问题。在用户在 print_menu() 中选择了他的菜单后,您可以通过调用新函数 check_if_wants_to_order_again 来避免它。

def print_menu():
  print('1. American')
  print('2. Asian')
  print('3. Indian')
  print('4. Mexican')
  print('5. French')
  print('6. Italian')
  print('7. Seafood')
  print('8. Pizza')
  menu = input('\nChoose where you want to eat from-->')
  if menu == "1":
    american_menu()
  check_if_wants_to_order_again()

def american_menu():
  print('1. Dempsey Burger Pub')
  print('2. Redrock Canyon Grill-Wichita')
  print("3. Cheddar's Scratch Kitchen")
  print("4. Neighbors| Restaurant & Bar")
  print("5. The Kitchen")
  print("6. Firebirds Wood Fired Grill")
  print("7. Chicken and Pickle")
  american = input("\nChoose which American Restaurant--> ")
  if american == "1":
      print("\nCall Dempsey Burger Pub")

def check_if_wants_to_order_again():
  go_back = input("Will you like to try another menu option? Enter \"Yes\" or \"No\":")
  if go_back == "Yes":
    print_menu()
  else:
    print("We'll continue with your current choice")

print_menu()

【讨论】:

    【解决方案3】:

    当您 continue 循环时,您再次调用 print_menu(),但您没有做任何其他需要遵循 print_menu() 以提示用户做出其他选择的事情。

    试一试:

    # Define the menus as dictionaries.
    # The key is the number that the user will pick,
    # the value is the selected item.
    
    # Main menu -- pick a cuisine.
    main_menu = {
        "1": "American",
        "2": "Asian",
        "3": "Indian",
        "4": "Mexican",
        "5": "French",
        "6": "Italian",
        "7": "Seafood",
        "8": "Pizza",
    }
    
    # American restaurant menu.
    american_menu = {
        "1": "Dempsey Burger Pub",
        "2": "Redrock Canyon Grill-Wichita",
        "3": "Cheddar's Scratch Kitchen",
        "4": "Neighbors| Restaurant & Bar",
        "5": "The Kitchen",
        "6": "Firebirds Wood Fired Grill",
        "7": "Chicken and Pickle",
    }
    
    # This dict maps each cuisine name to the appropriate submenu.
    cuisine_menus = {
        "American": american_menu,
        # "Asian": asian_menu,
        # "French": french_menu,
        # ...
    }
    
    # This dict maps each restaurant name to its contact info.
    contact_info = {
        "Dempsey Burger Pub": (
            "(316) 425-3831",
            "https://www.dempseysburgerpub.com/"
        ),
        "Redrock Canyon Grill-Wichita": (
            "(316) 636-1844",
            "https://www.redrockcanyongrill.com/"
        ),
        # ...
    }
    
    def print_menu(menu):
        """Print a menu, e.g. '1. American'..."""
        for k, v in menu.items():
            print(f"{k}. {v}")
    
    def contact_restaurant(restaurant):
        """Contact a restaurant.  Raises KeyError if we don't have contact info."""
        phone, website = contact_info[restaurant]
        print(restaurant)
        print(f"Phone: {phone}")
        print(f"Website: {website}")
        # maybe do something with website to open a browser?  idk
    
    
    # Interactive loop.  Go through the menus in turn,
    # and repeat when done or when they enter something invalid.
    # Break the loop once they finish picking a restaurant.
    while True:
        # Main menu (pick a cuisine)
        print_menu(main_menu)
        pick = input('\nChoose where you want to eat from-->')
        # Error checking for invalid picks.
        if pick not in main_menu:
            print("Please select one of the listed options.")
            continue
        cuisine = main_menu[pick]
        if cuisine not in cuisine_menus:
            # This happens if they picked something that was in main_menu
            # but not in cuisine_menus yet because we haven't written that part.
            print("Oops!  Haven't implemented that one yet.")
            print(f"Try {', '.join(cuisine_menus)}")
            continue
    
        # Now we have a valid main menu pick that we can continue with.
        cuisine_menu = cuisine_menus[cuisine]
    
        # Print the menu and ask them to pick an item from that.
        print_menu(cuisine_menu)
        pick = input(f"\nChoose which {cuisine} Restaurant--> ")
        if pick not in cuisine_menu:
            print("Sorry, not an option.  Let's start over.")
            continue
    
        restaurant = cuisine_menu[pick]
        if restaurant not in contact_info:
            print(f"Oops, we don't have contact info for {restaurant}.")
            print("Let's start over...")
            continue
        
        print(f"\nCall {restaurant}")
    
        # Prompt them to start over.  If they don't, break the loop.
        pick = input("Will you like to try another menu option?: ")
        if pick != "Yes":
            print("We'll continue with your current choice")
            break
    
    # Now the user has picked a restaurant to contact,
    # so go ahead and contact them.
    contact_restaurant(restaurant)
    

    请注意,所有交互都发生在while True 循环内。每当该循环中有 continue 时,它都会在开始时返回到 print_menu(main_menu),然后从那里继续。

    【讨论】:

    • 非常感谢,但是为什么要加逗号?
    • 因为没有它们,代码就无法工作。 (尝试完全按照我写的代码运行我给你的代码,然后尝试删除一些逗号。)
    • 啊,我明白了。我得看看它,看看我如何调整我的运行方式。非常感谢。
    • 我尝试阅读和理解代码的过程,但它们有点令人困惑,有没有办法可以调整原始代码以便我理解?
    • 哪一部分没有意义?
    【解决方案4】:

    感谢所有为此做出贡献的人,我终于弄明白了。

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 2018-12-01
      • 1970-01-01
      相关资源
      最近更新 更多