[Tutor] Most pythonic input validation
Emile van Sebille
emile at fenx.com
Thu Oct 15 21:45:17 CEST 2009
On 10/15/2009 7:36 AM Wayne Werner said...
> Is that the most pythonic way of validating? Is there a better way?
Pythonic in part having been addressed, I've some further comments to
your valid_choice code... -- Emile
def valid_choice(choice, min, max):
# don't use min and max -- they shadow built in functions
# try least/most minimum/maximum minval/maxval etc...
try:
choice = int(choice)
min = int(min)
max = int(max)
except ValueError:
r = False
# the next line is indeterminant if the above fails
# as your min/max/choice variables may not be ints
# IIRC, the comparisons may even fail and raise errors
# in some versions of python
if max < choice or min > choice:
r = False
else:
r = True
if not r:
print "Choice is not valid, please try again"
return r
More information about the Tutor
mailing list