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

Gavin O'Leary goleary1 at hwemail.com
Tue Nov 17 13:58:37 EST 2015


Hello all,

I have been trying to write a program that has the user think of a number between 1 and 1000, and the computer will guess the number in 10 or less tries. It isn’t working there. Here is my code.

import sys

high = 1000
low = 0


print "Think of a number between 1 and 1000 but don't tell me!"

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"


while True:
    guess = (high + low) / 2
    ask(guess)
    if ask(guess == 1):
        guess = (high + guess) / 2
    elif ask(guess == -1):
        guess = (high - guess) / 2
    else:
        sys.exit(0)

Can somebody help me please?

—Gavin O'Leary





More information about the Tutor mailing list