At 03:16 AM 3/27/2007, Alexander Kapshuk wrote:

I’m working on a program that has the user think of a number between 1 and 100 and then tries to guess that number.
 
I’m having trouble telling the computer to keep on looking for the correct number, each time narrowing down the search range.
 
Please see the code below.
 
import random
 
print "\tWelcome to 'Guess My Number 1.2'!"
print "\nThink of a number between 1 and 100."
print "The computer will try to guess it in as few attempts as possible.\n"
 
# set the initial values
user_number = int(raw_input("Think of a number between 1 and 100 and press Enter: "))
guess = random.randrange(50) + 1
answer = ""
tries = 1
 
# guessing loop
print guess
answer = raw_input("Is the above No '>', '<' or '=' as your No?: ")
while (answer != "="):
    if (answer == ">"):
        print (guess = random.randrange(100) + 51)
    elif (answer == "<"):
        print (guess = random.randrange(49) + 1)
    elif (answer == "="):
        print "Correct! The number was", user_number "And it only took you", tries " tries!\n"
    else:
        print "Keep on trying!"
 
    tries += 1
 
raw_input("\n\nPress the enter key to exit.")
 
 
 

Here are some hints.

You can use randrange, but maybe random.randint is easier to understand. >From the docs:

======================================
randint( a, b)
Return a random integer N such that a <= N <= b.
==========================================

You're not employing variables such as "a" and "b" (or "low" and "high") to "pinch down" on the user_number.

Also, you have errors in your print statements. Correcting these, here's your while loop:

=============================================
while (answer != "="):

    if (answer == ">"):

        print "guess =", (random.randrange(100) + 51)

    elif (answer == "<"):

        print "guess =", (random.randrange(49) + 1)

    elif (answer == "="):

        print "Correct! The number was", user_number, "And it only took you", tries, " tries!\n"

    else:

        print "Keep on trying!"


    tries += 1
=================================================

Now, the loop needs rewriting. If answer is "=", the loop isn't entered. If "<" or ">", the loop is endless.

Let's say the user gives the answer, ">".  Then the loop is endless, because answer remains ">", with no opportunity for the user to change it depending on the last guess.

I hope this helps you.

Dick Moores


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to