Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use try .. except or if ...else to validate user input? [closed]

Tags:

python

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?

like image 936
kn3l Avatar asked Apr 05 '11 20:04

kn3l


Video Answer


2 Answers

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.

like image 132
zindel Avatar answered Oct 20 '22 19:10

zindel


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).

like image 31
Steve Howard Avatar answered Oct 20 '22 18:10

Steve Howard