[Tutor] Guessing program with a twist isn't working

Alan Gauld alan.gauld at btinternet.com
Wed Nov 18 07:10:05 EST 2015


On 17/11/15 18:58, Gavin O'Leary wrote:

> def ask(x):
>      while True:
>          print "I guess %d" % x
>          answer = raw_input("Is that right, too high, or too low?: ")
>          if answer == 'right':
>              print "Lucky me!"
>              sys.exit(0)
>          elif answer == 'too low':
>              return 1
>          elif answer == 'too high':
>              return -1
>          else:
>              print "I don't understand"

This is OK, but notice that the function returns the result
for high and low but exits the entire program if you are
successful. It would be more consistent to return another
result (0 maybe?) for success.

> while True:
>      guess = (high + low) / 2
>      ask(guess)

Here you call the function but do not store
the result anywhere. You need something like:

result = ask(guess)

>      if ask(guess == 1):

And this is just plain wrong. What you are doing is passing a
boolean (truth) value into your function which will interpret
it as 1 or 0. Thats not what you want. Instead I suspect you
want something like:

if result == 1:
    ...
elif result == -1:
    ...

>          guess = (high + guess) / 2
>      elif ask(guess == -1):
>          guess = (high - guess) / 2
>      else:
>          sys.exit(0)

Notice that the last bit can never happen because your ask
function performs the sys.exit. This is why I suggested returning
zero for success.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list