import random # # readInteger: reads an integer value from the user within a confined range # # Parameters: # low: the lowest value that is accepted # high: the largest value that is accepted # # Returns: # The first value entered by the user between low and high # def readInteger (low, high): retval = input ("Enter a number between " + str (low) + " and " + str (high) + ": ") while (retval < low) or (retval > high): print "That wasn't in the range!" retval = input ("Enter a number between " + str (low) + " and " + str (high) + ": ") return retval # # constants, specifying the range in which the random number is picked # LOW = 1 HIGH = 100 # # play the game until the user says to stop # play = "yes" while (play == "yes") : # # Pick a random target value that the user is trying to guess # target = random.randrange (LOW, HIGH + 1) guess = target + 1 num_guesses = 0 min_accepted = LOW max_accepted = HIGH # # Loop until the user has guessed the correct number # while (guess != target): # # Read the guess from the user # guess = readInteger (min_accepted, max_accepted) num_guesses = num_guesses + 1 # # Advise the user if the guess was too high, too low, or just right # if (guess < target): print "That was too low!" min_accepted = guess + 1 if (guess > target): print "That was too high!" max_accepted = guess - 1 print "It took you", num_guesses, "guesses!" # # Ask the user whether he/she wants to play again # play = raw_input ("Do you want to play again (yes or no)? ")