0

I am writing a program where I want to be able to handle the exceptions of the user inputting an invalid character. The users options are "y" or "n", but if the user enters for example "t" then I want to print "invalid input". I can do this easily using an if/else statement but how can I do it using exception handling?

1
  • 3
    What's the need for try except block here? Commented Apr 13, 2015 at 5:43

4 Answers 4

3

I can do this easily using an if/else statement but how can I do it using exception handling?

No one would do this in real life:

try:
    assert c in ('n', 'y')
except AssertionError:
    print("Invalid Input")
Sign up to request clarification or add additional context in comments.

Comments

0

I seriously don't see the reason to do so.

ans = ''
while ans not in ['y', 'n']:
    ans = input('please enter y or n: ').lower()

Is a perfectly easy way to implement this. I guess you could try something like this:

while True:
    ans = input('please enter y or n: ').lower()
    try:
        assert(ans in ['y', 'n'])
        break
    except:
        print('invalid answer')

But why?

Comments

0

As others are saying this NOT a conventional case for using Exception handling.

However if it will help you understand how exception handling works then consider this code:

#!python

def validate_input(response):
    if response not in ('y', 'n'):
        raise ValueError, 'Invalid input'
    return True

some_input = None
while not some_input:
    some_input = raw_input('Please enter "y" or "n"')
    try:
        validate_input(some_input)
    except ValueError:
        print >> sys.stderr, "I'm not letting you out 'til you give a valid answer"
        some_input = False

This should work (though I haven't tested it). But it's a rather ungainly way to perform simple input validation.

(I could have used while True: and perform a break in an else: clause for my try: block ... but I think this way is a tiny bit more readable since the loop clearly will continue until some_input has any (Python) "non-false" value).

Comments

0

Without any further information, suppose that you have a function that you want to execute depending on the provided answer. The answers can then be stored in a dictionary as keys and these functions as values. The try/except is then very suitable. Example:

answer_functions = {
    'y': yes_function,
    'n': no_function
}

while True:

    answer = input('y/n? ')

    try:
        answer_function = answer_functions[answer]
    except KeyError:
        print('Invalid input.')
    else:
        answer_function()
        break

In the try-block you try to get the correct handler-function using the input as key. If the key isn't in the dictionary a KeyError is raised which you can catch with the except-clause. I like this approach in the case when there are many different options which need to be handled differently, since the resulting code is really clean.

2 Comments

It's possible, but 'very suitable'? I find this code far less intuitive than a simple loop around the input statement until the user entered either 'y' or 'n'.
In the case where you only have 'y' and 'n' this approach is rather overkill as is any try/except-based approach. But as I mentioned, I prefer this one in the case where many options need to be handled differently. Wrapped it in a while-loop now to provide the repeated question

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.