6
votes

I want to restrict user input so that a provided N obeys N >0 or N < 100.

Should I use if... else or try... except? Could you provide examples of both approaches?

4
I think you probably intended 'and', not 'or' in your condition. - ire_and_curses

4 Answers

12
votes

I'd suggest a combination:)

while True:
    value = raw_input('Value between 0 and 100:')
    try:
       value = int(value)
    except ValueError:
       print 'Valid number, please'
       continue
    if 0 <= value <= 100:
       break
    else:
       print 'Valid range, please: 0-100'

Hope it helps.

5
votes

if/else is probably more appropriate here, since any exceptions raised would be ones you threw yourself (and you'd still have to handle them).

1
votes

The simplest approach would be if/else.

But I'd probably do both a validator with if/else and thrown exception.

0
votes
# test value of N
try:
    N = int(N)
except ValueError:
    raise ValueError('N must be integer')
if N < 0 or N > 100:
    NError = ValueError('N must be between 0 and 100, inclusive.')
    raise NError