Skip to content

Python Number Game

An answer to this question on Stack Overflow.

Question

This is a piece of code that allows the user to choose a number and the computer guesses the number. However, when the computer is guessing it sometimes guesses the same number more than once. How do I stop the computer from guessing a number it has already guessed.

import random
print('This is a game where the user chooses\n' +
  'a number for the computer to guess.')
guess = random.randint(1, 50)
number = int(input('\n\nChoose a number between 1 and 50: '))
while guess != number:
    if guess > number:
        guess = random.randint(number, 50)
    
    else: guess < number
    guess = random.randint(1, number)
print(guess)
input('Enter to see the next number')
print('The computer guessed your number:', guess,'!')
input('\n\n\nPress enter to exit!')

Answer

You could try this:

#!/usr/bin/env python
import random
print('This is a game where the user chooses a number for the computer to guess.')
guesses = range(1,51)
random.shuffle(guesses)
number = int(input('\n\nChoose a number between 1 and 50: '))
while True:
  guess=guesses[0]
  print "The computer guessed %d" % (guess)
  if guess > number:
    guesses=[x for x in guesses if x<guess]
  elif guess < number:
    guesses=[x for x in guesses if x>guess]
  else:
    break
print('The computer guessed your number!')

We'll store all possible guesses and randomize their order. Then we'll use information from the user to progressively eliminate potential guesses. We don't have to reshuffle or choose random numbers as we go because removing elements from a randomly ordered array maintains the "randomness" of the next element we'll pull from it.

While fixing the range on your random.randint() call would also resolve the problem (and in a cleaner fashion), the method I describe offers an alternative approach which is more general (say, for instance, if the user suddenly tells you that their number is odd).