# Play a number guessing game with the user. The computer will pick a # random number between 1 and 100 which the user will try and identify # in as few guesses as possible. import random # Pick the number that the user is trying to guess target = random.randrange(1, 101) # Keep track of the highest and lowest legal values that the user can guess. # A better design would be to set up these variables before selecting the # target. The the target can be selected as random.randrange(low, high + 1) low = 1 high = 100 # Read the first guess from the user, ensuring it is within the legal range guess = int(input("Enter an integer between " + str(low) + " and " + \ str(high) + ": ")) # Keep looping until the user enters a legal guess while guess < low or guess > high: print("That wasn't within the valid range. Try again.") guess = int(input("Enter an integer between " + str(low) + " and " + \ str(high) + ": ")) # Set the initial value for count to 1 count = 1 # While the user's guess is not equal to the target while guess != target: # If the user's guess is too high if guess > target: # Tell them that print("That's too high!") high = guess - 1 # If the user's guess is too low else: # Tell them that print("That's too low!") low = guess + 1 # Read the next number from the user guess = int(input("Enter an integer between " + str(low) + " and " + \ str(high) + ": ")) while guess < low or guess > high: print("That wasn't within the valid range. Try again.") guess = int(input("Enter an integer between " + str(low) + " and " + \ str(high) + ": ")) # Increase the count of the number of guesses by 1 count = count + 1 # Display a message indicating that the value was identified correctly print("That's correct! And it only took you", count, "guesses!")