如何在 Python 中跳出 while 循环?

问题描述 投票:0回答:1
def main():
  dmn_options = ["lenovo", "rasbberrypi", "Exit"]
  while True:
    display_menu(dmn_options)
    user_choice = select_single_l(dmn_options);print(user_choice)
    
  
def display_menu(options):
  print("Select an option:")
  for index, option in enumerate(options, start=1):
    print(f"{index}. {option}")

def select_single_l(options):
  choice=None
  while True:
    try:
      i = int(input("Enter the number of your choice: "))
      if 1 <= i <= len(options) - 1:
        choice=options[i - 1]
        print(f"You selected {choice}.")
        break
      elif i == len(options):
        print("Exiting the menu.")
        break
      else:
        print("Invalid choice. Please enter a valid number.")
    except ValueError:
      print("Invalid input. Please enter a number.")
    break
  return choice

我尝试过 chatGPT 但无济于事。我告诉代码要破坏,但它没有破坏 - 这令人沮丧。当用户选择

Exit
时,它意味着停止选择 - 模仿 Bash 的 select 语句。请帮忙。

python python-3.x while-loop break
1个回答
0
投票

select_single_l
返回用户输入,并使用它在
main
中做出重大决定。

def main():
  dmn_options = ["lenovo", "rasbberrypi", "Exit"]
  while True:
    display_menu(dmn_options)
    user_choice = select_single_l(dmn_options)
    print(user_choice)
    if user_choice == dmn_options[-1]:
        break
def select_single_l(options):
  while True:
    try:
        choice = int(input("Enter the number of your choice: "))
        if 1 <= choice <= len(options):
            return options[choice - 1]
        print("Invalid choice. Please enter a valid number.")
    except ValueError:
        print("Invalid input. Please enter a number.")
© www.soinside.com 2019 - 2024. All rights reserved.