Bruno Desthuilliers wrote:
.... The generic version of your above code could be:
def safeinput(prompt, convert):
while True:
x = input(prompt)
try:
x = convert(x)
except ValueError, e:
print("Bad input : %s" % e)
else:
return x
Or (I think more straightforwardly):
def safeinput(prompt, convert):
while True:
text = input(prompt)
try:
return convert(text)
except ValueError as e:
print("Bad input ({0!r}): {1}".format(text, e))
...
def yesno(s):
s = s.strip().lower()
if not s in ("y", "n"):
raise ValueError("please answer with 'y' or 'n'")
# we return a boolean
return s == 'y'
def yesno(s):
s = s.strip().lower()
if s in ("y", "n"):
return s == 'y' # return a boolean
raise ValueError("please answer with 'y' or 'n'")
def int_in_range(x, mini, maxi):
x = int(x)
if not mini <= x <= maxi:
raise ValueError("%s is not in range (%s, %s)" % (x, mini, maxi))
return x
def int_in_range(x, below, above):
x = int(x) # may cause ValueError on its own
if below < x < above:
return x
raise ValueError("{0} is not between {1} and {2}".format(
x, mini, maxi))
These changes are mostly:
(1) Negated tests are harder yo read
(2) raise and return change the flow of control, so
if ...:
<raise or return>
else:
...
is "fat" (more trouble to read).
(3) Adopting to the new 3.0 string formatting.
--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list