20130122

We did an in-class exercise of top-down programming and stepwise refinement.  Our goal was to develop a simple number-guessing game.

We start with a very general description of the program, such as "The program chooses a number, then the user tries to guess it."  We break this down into discrete steps.  As we do so, we often think of other desirable features that we add as we go along.  I've used italics to indicate new ideas.

1.  The program chooses a secret number in the range 1 to 100.

2.  Let the user guess values until she gets it right, or until she runs out of guesses

3.  Print a list showing the user's guesses

4.  Give the user a score based on her skill at guessing


Now we refine each of these steps.  

1.1    Use the randint() function from the random module to choose a random number in the range 1 .. 100.   Call this number secret_number.

1.2    Initialize all the required variables.  We list this as a step here but it is really just a reminder.  As we go through the rest of the steps and discover that we need particular variables, we repeatedly return to this step and assign initial values to the variables we are using.  I will show the new variables in bold when we use them for the first time.


2.1    while (secret_number != current_guess) and (number_of_guesses_made < max_number_of_guesses):

               
2.2    get current_guess from user
                2.3    increment number_of_guesses_made
                2.4    add current_guess to a list called list_of_guesses
                2.5    tell the user if current_guess is too high or too low

3.1    print "Your guesses :",list_of_guesses

4.1    if the user did not guess the secret number, her score is 0.  Otherwise her score is max_number_of_guesses + 1 - number_of_guesses_made


Notice that some lines of Python have already appeared.  In our next refinement, the process of creating the Python program is complete.

# guessing game
# Robin Dawes, 2013

# choose a random number

from random import *

secret_number = randint(1,101)

print "I have chosen a number between 1 and 100.  Try to guess it."

# initialize variables

current_guess = 0
max_number_of_guesses = 7
number_of_guesses_made = 0
list_of_guesses = []

while (secret_number != current_guess) and (number_of_guesses_made < max_number_of_guesses):
    current_guess = input("Please enter your guess : ")
    number_of_guesses_made += 1
    list_of_guesses.append(current_guess)
    if current_guess < secret_number:
        print "Too low"
    elif current_guess > secret_number:
        print "Too high"
    else:
        print "You got it!"
       
print "Your guesses :" , list_of_guesses

if (current_guess != secret_number):
    print "You used up all your guesses.  My number was ",secret_number
    print "Your score is 0"
else:
    print "Your score is",max_number_of_guesses + 1 - number_of_guesses_made
    print "Goodbye"