[Tutor] Guess my number game

Alan Gauld alan.gauld at btinternet.com
Sun Nov 20 17:00:00 CET 2011


On 20/11/11 15:29, myles broomes wrote:
 > ...I was told to have a go at writing up the actual code.

Well done, thats a good start.

> #guess my number games
> #the user thinks of a number between 1 and 100,
> #the computer then has to try and guess that number
>
> #welcome the player to the game and explain the rules
> print("\t\t\t Guess My Number")
> input("Welcome player to the 'Guess My Number' game. Think of a number between 1 and 100 and I will try to guess it. Press enter when you have thought of your number and are ready to begin.")

First thing is that you need to store the number that the user typed.
So you need a variable - lets call it userNumber - and an assignment. 
While we are at it lets convert the string version the user gave us to a 
number:

userNumber = int( input(....) )


> #import the random module
> import random

The comment is redundant since the code is obvious. Use comments to tell 
us *why* you are doing things not to tell us what you are doing - we can 
all read the code...

Its also conventional practice to put all imports at the top of the 
program. Its not necessary, but it saves people hunting for the imports 
if they are all together at the top.

> #set initial values
> tries = 1
> attempt = random.randint(1,100)
> guess = input("Is your number",attempt,"? (Enter 'yes' or 'no'.)")

The name guess is a bit misleading since its really the users response,
The Guess is actually what you have already named attempt.
Good naming makes a big difference to the readability of your code so 
it's worth really thinking about what the variables are doing and 
choosing descriptive names. Also the names should follow the function
of the variables, not their type.

> #guessing loop
> while guess == 'no':
> 	tries += 1
> 	incorrect = input("Was my guess too high or too low? (Type 'high' or 'low'.) ")
> 	if incorrect == 'high':
> 		*

Here you want to generate a new value for attempt but insterad of using 
1-100 you want it between 1-(attempt-1)


> 	if incorrect == 'low':

Here you want to generate a new value for attempt but instead of using 
1-100 you want it between (attempt+1) - 100

And you already know how to set attempt to a number between two values...

Then before you go back to the top of the loop you need to ask the user 
if the new attempt is ok and store that in guess.

Have a go at writing that...

> #tell the player how many tries it took and end the game
> print("Aha! I guessed it! And it only took",tries,"tries!")
> input("Press enter to exit.")

And that bit is fine. :-)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list