pythonpython-3.xwhile-loopbreak

How do i break out of this while loop in Python?


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

I've tried chatGPT but to no avail. I tell the code to break but it does not break - it is frustrating. When the user select Exit it is meant to stop selecting - mimicking Bash's select statement. Please help.


Solution

  • Your issue stems from you not exiting your main() while loop

    def main():
      dmn_options = ["lenovo", "rasbberrypi", "Exit"]
      while True:
        display_menu(dmn_options)
        user_choice = select_single_l(dmn_options);print(user_choice)
    

    Here is an example doing so without altering your original code too much.

    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 == None:
          break
        
      
    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