How to loop menu choice validation in python?

Question:

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:"))
Asked By: Nicole

||

Answers:

I think the problem does not come rather from your code but from the type of data you are entering, by putting int() you are telling the input that the type of data you are going to receive is integer / int, check again if you are entering it well

Answered By: x07ex

You can wrap your call to int() in a try-except block. This way if an error is thrown, you can handle it. Like this:

# ... code ...
option = 0
try:
    option = int(input("Enter your option:"))
except ValueError:
    print("That is not a valid integer")
# ... code ...
Answered By: Michael M.

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)
Answered By: itogaston
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.