New Python programmer here. I’m trying to make a rock, paper, scissors game and I’m wondering why this code returns usually one answer but sometimes two. I’m trying to make it print one answer for choices1 and one for choices2.
Many thanks in advance 🙂
from random import randint
choices1 = ['rock', 'paper', 'scissors']
choices2 = ['rock', 'paper', 'scissors']
if randint(0,3) == 0:
print(choices1[0])
elif randint(0,3) == 1:
print(choices1[1])
elif randint(0,3) == 2:
print(choices1[2])
pass
if randint(0,3) == 0:
print(choices2[0])
elif randint(0,3) == 1:
print(choices2[1])
elif randint(0,3) == 2:
print(choices2[2])
>Solution :
You’re generating a new random number every time you call randint. What you want to do is generate a random number once and then do your if/elif checks.
result = randint(0,2)
if result == 0:
print(choices1[0])
elif result == 1:
print(choices1[1])
else:
print(choices1[2])
In fact, you’re repeating code here. A simpler solution would be
result = randint(0,2)
print(choices1[result])
As pointed out in the comments, you can even skip generating the index altogether and use the choice function provided by the random module:
result = random.choice(choices1)
print(result)
There are a few other issues. First, you’re generating a number between 0 and 3, inclusively, but your arrays only have indices going up to 2. Second, you’ve got a pass statement in the middle of nowhere. pass does nothing and is only needed in situations where you’re required to have at least one line of code. Third, there’s no reason to have two separate lists, choices1 and choices2, which contain the exact same values.
Putting everything together,
choices = ['rock', 'paper', 'scissors']
result1 = random.choice(choices)
result2 = random.choice(choices)
print("Player 1's result is", result1)
print("Player 2's result is", result2)