[Tutor] Most pythonic input validation

Alan Gauld alan.gauld at btinternet.com
Fri Oct 16 14:41:38 CEST 2009

"Robert Johansson" <robert.johansson at math.umu.se> wrote

> What if a valid user input has to be an integer between 10 and 20?
> Would it be pythonic to add a test like:
> If prompt in range(10,21):
>  ...
> else:
>   ... raise an error

Yes and it could be a ValueError in this case.

You could also test using conditions which, for a wide range,
would be more efficient

if minVal < choice < maxVal:
    raise ValueError("Choice (%d) should be between %d and %d" % (choice, 
minVal, maxVal) )

> If I understand the error handling correctly you can add your own user
> defined error, but is that really what you should do in that case?

In this case I'd just use ValueError although I would add a string message
to state the valid range, as shown above.

But it is a trivial task to create a custom Exception class:

class RangeError(Exception): pass

and then

raise RangeError("Choice (%d) should be between %d and %d" % (choice, 
minVal, maxVal) )


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list