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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With