0

My problem here is that if the user inputs a value that is not an integer, it throws a ValueError: invalid literal for int() with base 10:'example' i want to handle this exception if the user inputs a string or float based value and return print("Sorry thats not right, try again") and replay the function. how can this be accomplished? I fear it is because the input function is posed as an argument inside the configselect() function that this might not be possible?

choice = [1, 2, 3]


def configselect(choice):
    if choice == 1:
        print("you chose 962")
    elif choice == 2:
        print("you chose Audience")
    elif choice == 3:
        print("you chose mAP")
    else:
        print('Thats not a valid Number. Please try Again.')


configselect(int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? ")))
3

2 Answers 2

1

You should use try...except ValueError, as a ValueError is raised when integer cannot convert something to an integer

choice = [1, 2, 3]


def configselect(choice):
    if choice == 1:
        print("you chose 962")
    elif choice == 2:
        print("you chose Audience")
    elif choice == 3:
        print("you chose mAP")
    
while True:
    try:
        val=int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? "))
        if val in choice:
            configselect(val)
            break
        else:
            print("Please select either 1,2 or 3")
    except ValueError:
        print('Thats not a valid Number. Please try Again.')

Sign up to request clarification or add additional context in comments.

1 Comment

this is exactly what i was looking for, thank you so much, earlier i had tried the try/except inside of the function and my issue was that the value was hitting the exception before it ever made it to the try/except. cheers
0

If you want to catch the exception, you need to add a try-except block:

try:
    configselect(int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? ")))
except ValueError:
    print("Sorry, that's not right, try again")

If you want to prompt for input continuously until the user enters something acceptable, you need to wrap this in a loop:

while True:
    try:
        configselect(int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? ")))
    except ValueError:
        print("Sorry, that's not right, try again")
    else:
        break

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.