Python Python Basics (2015) Number Game App Number Game Takeaways

Brett McGregor
PRO
Brett McGregor
Pro Student 1,903 Points

Here is my solution to opposite number game. I used a sort of binary search rather than generating random numbers.

import random
import math

def game():
    #set number range
    lower = 1
    upper = 100
    # track number of attempts
    attempts = 0

    #Introduction message describing the game
    print("Hi. I am your computer.\nThink of a number between {} and {}.\n\
I will make a guess.\nThen please tell me if my guess is high or low.\
\nOkay, I will make a guess:".format(lower, upper))

    while True:

        #Computer guesses a number, it is printed
        guess = math.floor(((upper + lower) / 2))
        attempts += 1
        print(guess)

        # User input, telling computer if its guess is high or low or correct
        user_feedback = str.upper(input("High(h)/Low(l)/Correct(c)? > ")) 
        if user_feedback == "H":
            upper = guess
        elif user_feedback == "L":
            lower = guess
        elif user_feedback == "C":
            print("Woohoo!!! I guessed your number \
which was {}. It took me {} attempts.".format(guess, attempts))
            # play again?
            replay = str.upper(input("Would you like to play again? Y/n > "))  
            if replay == "N":                
                print("OK. See you next time.")
                break
            else:
                game()
        # handle incorrect user feedback entries
        else:
            if user_feedback != "H" or "L" or "C":
                print("please enter either H, L or C")
                attempts -= 1

game()

1 Answer

Steven Parker
Steven Parker
200,416 Points

Good idea — I did the same thing when I took that course! This way, the computer always gets the number with the minimum number of guesses.