Paulo Pinto Paulo Pinto -4 years ago 169
Python Question

how to check if the number is in the list

Hi I am trying to make a computer vs. computer guessing game and I don't want the computer1 to guess the same number twice. I want to know how to stop this. I believe it is around the if statement, but I'm stuck. I need help.

from random import randint

try:
guess = randint(0,5)
computer1 = randint(0,5)
GuessList = [ ]
GuessList.append(computer1)

while computer1 != guess:
print("COmputer guessed ",computer1)
if computer1 in GuessList:
computer1 = randint(0, 5)
#computer1 = randint(0,5)

except KeyboardInterrupt:
print("goodbye")


print("COMPUTER FINALLY GUESSED "), guess)


My output is the computer1 guessing the same number more than once, but it will eventually get it.

Answer Source

You can just add,

while computer1 in GuessList:
    computer1 = randint(0, 5)

After your computer1 = randint(0, 5). You might have to remove your GuessList = [ ] because that will reset your GuessList each time. Instead, you should have that at the very start of your code and leave the append statement.

Or you can use

computer1 = random.choice(GuessesLeft)

GuessesLeft is a list of all the numbers computer1 has not guessed. Each time it makes a guess youc an just delete that item from the list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download