Nikolaij
Nikolaij

Reputation: 321

Exception handling with if-clauses fails

If the input is different from y or n and exception should be called. I thought that is a very simple task, but it fails. If the input is not y or n nothing is done at all. What am I missing here?

rep = str(input('type Y or N: '))
try:
    if rep.lower() == 'y':
        print('Y was typed')
    if rep.lower() == 'n':
        print('N was typed')
except:
    print ('Neither N nor Y was typed')

Upvotes: 1

Views: 51

Answers (3)

quamrana
quamrana

Reputation: 39374

You don't need try/except in this case since no exceptions are raised:

rep = input('type Y or N: ')
rep_lower = rep.lower()
if rep_lower == 'y':
    print('Y was typed')
elif rep_lower == 'n':
    print('N was typed')
else:
    print ('Neither N nor Y was typed')

Upvotes: 1

ProfKache
ProfKache

Reputation: 73

I have 2 comments on the code:

  1. First of all there was no need to use str() to explicitly cast the input variable because by default the input() function returns a string, that means even if you input e.g rep = 1 the value will be a string, which leads me to second point below.

  2. No exception will be generated from your code as it was mentioned by someone above because whatever input you insert will be regarded as a string. Having said that, there was no need of even having a try...catch block, that means only normal "if...elif...else" ladder will work.

Upvotes: 1

costaparas
costaparas

Reputation: 5237

Your code is not going to raise an exception that you can catch in this case. Instead of using the try-except, use an if-elif-else:

rep = str(input('type Y or N: '))
if rep.lower() == 'y':
    print('Y was typed')
elif rep.lower() == 'n':
    print('N was typed')
else:
    print('Neither N nor Y was typed')

This code simply checks the rep against two different cases (the if branch and elif branch). If neither are True, then the code goes into the else branch.

Read more about how such if statements work in this documentation.

Upvotes: 1

Related Questions