Search code examples
if-statementwhile-looptry-catch

ALternatives to multiple while and if statements


The state of this. How else can I offer the user multiple levels of options and check that the user inputs the correct value at each level without having to use multiple while loops, try and if statements.

while True:
    try:
        user_choice = int(input("Enter an option 1 or 2"))
        if user_choice == 1 or 2:
            if user_choice = 1:
                while True:
                    try:
                        edit_choice = int(input("Would you like to edit (1) or delete (2)"))
                        if edit_choice == 1 or 2:
                            if edit_choice = 1:
                                \# code to offer more options and more while, try and if statements.
                                break
                            elif edit_choice = 2:
                                \# code to offer more options and more while, try and if statements.
                                break
                        else:
                            print("\\nPlease enter a valid option.")
                    except ValueError:
                        print("\\nPlease enter a number.")
                    break
            elif user_choice = 2:
                \# code to offer more options and more while, try and if statements.
                break
        else:
            print("\\nPlease enter a valid option.")
    except ValueError:
        print("\\nPlease enter a number.")

Solution

  • You rewrite it using recursive function calls instead of while loops like this:

    def enter_option():
        try:
            user_choice = int(input("Enter an option 1 or 2: "))
            if user_choice in [1, 2]:
                if user_choice == 1:
                    edit_or_delete()
                elif user_choice == 2:
                    edit_or_delete()
            else:
                print("\nPlease enter a valid option.")
                enter_option()
        except ValueError:
            print("\nPlease enter a number.")
            enter_option()
    
    
    def edit_or_delete():
        try:
            edit_choice = int(input("Would you like to edit (1) or delete (2): "))
            if edit_choice in [1, 2]:
                if edit_choice == 1:
                    enter_option() # code to offer more options
                elif edit_choice == 2:
                    enter_option() # code to offer more options
            else:
                print("\nPlease enter a valid option.")
                edit_or_delete()
        except ValueError:
            print("\nPlease enter a number.")
            edit_or_delete()
    
    
    enter_option()