Outline for June 4, 2007
-
Greetings and felicitations!
-
Building a program: how to guess a number between 1 and 100
-
One guess
-
Ask user if she is thinking of a number between 1 and 100
-
Guess the midpoint of this interval; if correct, stop
-
If this guess is not right, ask if the number is more; if it is in which case look in 51 to 100
-
Otherwise, number is less, so look in 1 to 499
-
Keep repeating ii, iii, and iv until you guess the number
-
Many guesses
-
Create an outer loop asking the user if she is thinking of a number
-
If yes, do what's in (a), above
-
Continue looping until user says to quit
#
# Computer guesses a number
#
print "Please pick a number between 1 and 100. I will try to guess it."
print "Please answer 'yes' or 'no' when asked a question; if your answer is not'yes',"
print "I will assume you mean 'no'! Also, if you're on, you will confuse me."
print ""
while raw_input("Are you thinking of a number between 1 and 100 (yes/no)? ") == "yes":
#
# outer loop: initialize counter, high, low and computer first guess
#
count = 0
low = 1
high = 100
guess = (high - low) / 2 + low
#
# construct prompt
#
ask = "Is your number " + str(guess) + "? "
#
# ask if guess is right; enter inner loop if not
#
while raw_input(ask) == "no":
#
# inner loop
#
# ask whether guess was too high or too low, and adjust next guess appropriately
#
if raw_input("Is your number more than that (yes/no)? ") == "yes" :
low = guess + 1
else :
high = guess - 1
#
# compute next guess
#
guess = (high - low) / 2 + low
#
# construct prompt to ask if guess is right
#
count = count + 1
ask = "Is your number " + str(guess) + "? "
#
# back to outer loop
# announce how long it took to guess the number, and tell user how to quit
#
print "Aha! Got it in", count, "guesses!"
print "If you want to quit, just say no to the next question"
#
# say goodbye
#
print "Goodbye!"
Here is a PDF version of this document.