Issue
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
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 Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.