[Tutor] Simple guessing game - need help with the math

Greg Markham greg.markham at gmail.com
Wed Aug 13 01:25:10 CEST 2014


Hello again,

I'm working on one of the more advanced (at this stage of my learning
process), albeit optional, assignments.  The objective is to write a
program that tries to guess your number from 1 to 100.  After each guess,
you tell it if it's (h)igher, (l)ower or (c)orrect, and eventually it'll
logically zero in on the correct value.  In addition, it should count the
number of tries required to come to the correct guess.

I've worked through a few hiccups so far, but I've come to a standstill.
 Here follows my code:

import os

print ("\nShall we play a game?\n\n")
print ("Think of a number, 1 to 100, and I will attempt to guess what it
is.\n")

input("Press [Enter] when ready.\n")

guess = 50
change = 50
answer = ""
tries = 1

while answer == "h" or "l" or "c":
    print ("My guess is: ", guess, "\n")
    answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ")
    answer = answer.lower()
    if answer == "h":
        guess = round(int(guess + (change/2)))
        change = change/2
        tries += 1
    elif answer == "l":
        guess = round(int(guess - (guess/2)))
        tries += 1
    elif answer == "c":
        print ("/n/nYay!  I win.  Shall we play again?\n\n")
        os.system('cls' if os.name == 'nt' else 'clear')
    else:
        print ("Invalid response.  Please try again.\n")


Something about the math in the code here isn't quite right.  If you were
to enter "h" (for 'higher') each time, it would first guess 50, then 75,
then 87, then 93, then 96, and finally would stop progressing at the number
97.  I suspect it's a side-effect of the way the round function works, but
I don't know how to get around it.

Any help would be greatly appreciated.

Thanks in advance,

Greg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140812/94e044a4/attachment.html>


More information about the Tutor mailing list