How to use try .. except or if ... else to check user input?

I want to limit user input so that the provided submits Nto N >0or N < 100.

Should I use if... elseor try... except? Could you give examples of both approaches?

+5
source share
3 answers

I would 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 this helps.

+9
source

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

+5
source

- /else.

, , if/else .

+1

All Articles