[Tutor] Guess Your Number Game

Rinzwind w.damen at gmail.com
Tue Jan 17 13:25:26 CET 2006


On 1/17/06, Jon Moore <jonathan.r.moore at gmail.com> wrote:
> Hi
>
> I hope someone can help me!
>
> I am currently learning Python using a book by Michael Dawson. In one of the
> exercises I have to right a program that will guess a number chosen by the
> user.
>
> It is partly working, however it does not seem to keep state of numbers that
> should have already been ruled out as too high or low.
>
> Any pointers would be very much appreciated!
>
> import random
>
> print "Welcome to 'Guess Your Number'!"
> print "\nThink of a number between 1 and 100."
> print "And I will try and guess it!\n"
> print "Valid inputs are: higher, lower and correct."
>
> raw_input("\n\nPress enter once you have thought of a number.")
>
>
> # set the initial values
> guess = random.randrange(100) + 1
> tries = 1
>
>
>
> # guessing loop
> response = ""
> while response != "correct":
>     print "Is it" ,guess, "?\n"
>     response = raw_input ("")
>     if response == "lower":
>         guess = random.randrange(1, guess)
>     elif response == "higher":
>         guess = random.randrange(guess, 100)
>
>
> # Error message for invalid inputs
>     else:
>         print "Invalid entry!"
>
>
>     tries += 1
>
>
> print "\nI guessed it!  The number was", guess
> print "And it only took me", tries, "tries!\n"
>
>
> raw_input("\n\nPress the enter key to exit.")
>
> --
> Best Regards
>
> Jon
>
> --
> Best Regards
>
> Jon Moore
>
sidenote:
Hello, 1 thing I spotted:

response = raw_input ("")
if response == "lower":
        guess = random.randrange(1, guess)
        tries += 1
elif response == "higher":
        guess = random.randrange(guess, 100)
         tries += 1
# Error message for invalid inputs
else:
        print "Invalid entry!"

I myself consider an invalid entry not as a valid try ;)

These 2 lines are wrong:

>         guess = random.randrange(1, guess)

>         guess = random.randrange(guess, 100)

The 1 and 100 are being reset and if the answer WAS lower and is NOW
higher you lost your 1st boundary. 1 and 100 should be the previous
answer.

Regarding your problem:
A test needs to be between the highest lowest answer and the lowest
highest answer you get.
You test between 1 and guess and guess and 100.
The 1 and 100 reset your boundary back to the original problem: it
needs to be between 1 and 100.

number = 40
random = 60
answer lower
next test you do is between 1 and guess.
new random = 20
answer = higher
but now you test between 20 and 100 and NOT between 20 and 60 (<-
lowest highest number).


More information about the Tutor mailing list