[Tutor] Most pythonic input validation
Robert Johansson
robert.johansson at math.umu.se
Fri Oct 16 15:44:46 CEST 2009
> What if a valid user input has to be an integer between 10 and 20? I mean,
> it could be that you are doing something that only makes sense for that
> input. Would it be pythonic to add a test like:
>
> If prompt in range(10,21):
Better to write
if 10 <= prompt <= 20:
> ...
> else:
> ... raise an error
>
> 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?
It depend on the context. You could raise ValueError (it's OK to raise
built-in exception types if they apply) or your own exception type or
just handle the error.
Kent
Thanks Kent,
If I wanted prompt to be an integer, is my check with range still bad?
Is this the way to define my own error and to use it:
class MyValueError(Exception):
define initialization and printing
try:
if test ok:
...
else:
raise MyValueError
except MyValueError:
...
More information about the Tutor
mailing list