Re: Python: Help With Beginner Stuff

  • From: "R Dinger" <rrdinger@xxxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Fri, 15 Oct 2010 12:35:51 -0700

Hi Jim,

Here is how to do it via interval bisection using mostly your code:

# comp_guess.py
# Simulate the computer guessing a number between 1 and 100 until it guesses 
correctly.

lower = 1
upper = 100
guesses = 0

answer = int(raw_input("Give me a number between 1 and 100 for the computer to 
guess: "))
print "\nThe answer is %d." % (answer)

while True:
  comp_guess = (lower + upper)/2 # The computer makes a guess
  guesses += 1
  print "For guess %d, the computer guessed %d." % (guesses, comp_guess)
  if comp_guess == answer:
    break
  elif comp_guess < answer:
    print "The computer guessed too low."
    lower  = comp_guess +1 # So it won't guess the same number again.
    print "lower is now %d." % (lower)
  else:
    print "The guess is too high."
    upper = comp_guess -1 # So it won't guess the number again.
    print "upper is now %d." % (upper)

print "The computer guessed the number in %d guesses" % (guesses)
print "Can you beat that?"

raw_input("Press Enter to quit")

Other related posts: