Hi there, I am in a first year programming class at Dalhousie University (Halifax, Nova Socita, Canada), and I need a little help with an assignment. The exercise is as follows:
"[10 Points] Create a number guessing game. First, ask the user for some positive integer, n. Ask the user to select any number between 0 and n and have your program try to guess it. After each guess, ask the user if the guess is correct. If incorrect, your program should ask the user if the user's chosen number is higher or lower than the guess. Have the program keep track of the number of guesses it needed to find the answer. Try to find the answer in as few guesses as possible! An excellent implementation should be able to guess a number between 0 and 1000 within 10 tries. Remember to add descriptive comments to your code."
Heres what I have:
import random
n = input("Hi! Please enter a positive integer!")
print "Thanks! Now, pick a number between 0 and your number!"
guess = random.randint(0, n)
attempts = 0
print "Is", guess, "your number?"
answer = input ("1 = yes, 2 = no")
while answer == 2:
highlow = input ("Is the number higher or lower? 1 = higher 2 = lower")
if highlow == 1:
guess1 = random.randint(guess, 50)
print "Is", guess1, "your number?"
answer = input ("1 = yes, 2 = no")
attempts += 1
if highlow == 2:
guess1 = random.randint(0, guess)
print "Is", guess1, "your number?"
answer = input ("1 = yes, 2 = no")
attempts += 1
if answer == 1:
print "I WIN!!!!!"
print "I guessed your number in", attempts, "guesses!"
The program works, however, is not very smart. As you can see, I set it to guess a number between 0 and 50 rather than 1000 and it still cannot guess the number is a decent number of tries. I know whats wrong with it, its that I am having the program guess random numbers between 0 and the initial guess or between the initial guess and 1000, which can keep the computer guessing for ages. How can I make the program smarter so that it keeps track of its guesses and makes it next guess based on that, rather than just guessing another random number? Would Appreciate any help!