On 05/08/2014 06:00 AM, Kevin Johnson wrote:
Hi,

Total beginner to python and am working my way through Michael Dawsons 'Absolute beginner' book. Just got stuck on the last bit of the challenges from chapter 3. Essentially need to create a game where the user picks a number between 1 and 100 and the computer has to guess, program should indicate to the computer if the guess need to be higher or lower, it should also count the number of attempts and call a halt to the game if a set number of attempts is reached.

The highlighted bit is where I think I'm going wrong but I just can't think how to make the computer remember the previously closest highest and lowest guesses, not sure if you have all read Micheal Dawsons book but I've not covered a whole lot by chapter 3 and so any hints/solutions need to be pretty basic as I don't want to get ahead of myself.

Thanks,
Kevin

#numbers game again but...
#user picks number between 1 and 100
#and computer guesses

import random

user_number = int(input("Pick a number between 1 and 100: "))
computer_guess = random.randint(1, 100)
guesses = 1

while computer_guess != user_number:
    print("The computers guess is", computer_guess)
    if computer_guess > user_number:
        print("Lower...")
    else:
        print("Higher...")
    if guesses == 10:
        print("You lose computer!")
        break
    if computer_guess > user_number:
        computer_guess = random.randrange(1, (computer_guess-1))
    else:
        computer_guess = random.randint((computer_guess + 1), 100)
    guesses += 1
    if computer_guess == user_number:
        print("Well done you guessed the number was", user_number)
        print("It took you", guesses, "tries")

input("Press the enter key to exit.")

This is a classic game.

The first issue I see is the while exit condition. I prefer to use:

max_guess = 7 
# I believe this game can be won in 7 guesses if the correct strategy is used.
guess = 0
initial_guess = random.randrange(1, 100)
while guess < max_guess:
    do stuff
    guess += 1

Also, I would model how you would play this game efficiently against a person. Then write the "do stuff" to replicate that. Hint: you do not need to generate random guesses within the while loop.
-- 
Jay Lozier
jsloz...@gmail.com

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to