[Tutor] Guess the number

Alan Gauld alan.gauld at btinternet.com
Thu May 7 10:39:44 CEST 2015


On 07/05/15 05:09, Ikaia Leleiwi wrote:

> number might be.  If the guess is lower then the inputted number then the
> user inputs the word 'higher' to indicate the computer needs to guess a
> higher number.  If the guess is higher than the inputted number then the
> user inputs the word 'lower' to indicate the computer needs to guess a
> lower number.

Note that your code does not do that. It ignores the
'higher' or 'lower' input from the user.

> number = int(input("Pick an integer between 1-100 "))
> guess = random.randint(1,100)
>
> while guess != number:
>
>      if guess < number:

This if condition should be controlled by the user. So before you get 
here you need to print the guess and ask for input.
The if condition then becomes

if next_guess.lower() == 'higher':

or similar

>          print("The computer guesses: ",guess)
>          input("higher or lower ")
>          guess = random.randint(guess,100)
>
>      elif guess > number:

same here, the test should be

elif next_guess.lower() == 'lower':

>          print("The computer guesses: ",guess)
>          input("higher or lower ")
>          guess = random.randint(1,guess)
>
>      else:
>          print("Congradulations Computer!! You guessed that the number was
> ",number)

> I can't figure out how to narrow down the random integer range as the
> computer guesses closer and closer to the actual value of the number chosen
> in the beginning.

You could try storing the max and min values of guess so that the limits 
become

randint(guess,hiGuess)

and

randint(loGuess,guess)

And set hiGuess and loGuess when you get an instruction to
go up or down
loGuess = 1
hiGuess = 100
guess = random(loGuess,hiGuess)
number = ...
while:
    ....
    if next_guess == 'higher':
       if guess > loGuess: loGuess = guess
    elif next_guess ==  'lower':
       if guess < hiGuess: hiGuess = guess
    else:...
    guess = randint(loGuess,hiGuess)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list