# Need help improving number guessing game

Scott David Daniels Scott.Daniels at Acm.Org
Tue Dec 16 22:59:24 CET 2008

```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:

> ...
>
> def yesno(s):
>    s = s.strip().lower()
>    if not s in ("y", "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

> 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.Daniels at Acm.Org

```