Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop menu choice validation in python?

I am trying to make a loop to validate my menu choices to be integers, but receiving this error when inputting lettersline 138, in <module> option = int(input("Enter your option:")) ValueError: invalid literal for int() with base 10: 'test' . Sorry if code is a mess only been doing python for 2 weeks approx so still learning.
Ideally I would like the validation to also limit the choice to the 1-6 range for the choices.
P.S. I know it’s wrong, but I just don’t know what.
This is my code:

    print('=============================')
    print('= Inventory Management Menu =')
    print('=============================')
    print('(1) Add New Item to Inventory')
    print('(2) Remove Item from Inventory')
    print('(3) Update Inventory')
    print('(4) Display Inventory')
    print('(5) Search for Item')
    print('(6) Quit')

#Selecting menu option
menu()
option = int(input("Enter your option:"))
while option !=0:
    if option == 1:
        addInventory()
    elif option == 2:
        removeInventory()
    elif option == 3:
        updateInventory()
    elif option == 4:
        printInventory()
    elif option == 5:
        searchItem()
    elif option == 6:
        answer = input("Are you sure you want to quit? Y/N: ")
        if answer == 'Y':
            exit()
        else:
            menu()
            option = (input("Enter your option:"))
    else:
        if option.isdigit():
            pass
        else:
            print("Enter a valid option: ")
    menu()
    option = int(input("Enter your option:"))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try this:

option = input("Enter your option:")

while not option.isdigit():
   option = input("Enter a valid option:")

option = int(option)

Also you can check if the number is in a certain range:

option = input("Enter your option:")

while not option.isdigit() or int(option) < 1 or int(option) > 6:
    option = input("Enter a valid option:")

option = int(option)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading