list index is going out of range

Viewed 30

I am trying to make this sample rock paper scissor game and it was working well till I was just outputting the choices. Now when I added a scoring system as soon as the system picks rock I get the error at the bottom.

import random
score=0
options=["rock","paper","scissor"]
while True:
    our_input=input("Please select between rock/paper/scissor or q to quit ").lower()
    if our_input=="q":
        break
    if our_input in options:
        print("you chose "+our_input)
    else:
        print("Please enter a valid input")

    comp_number=random.randint(0,3)
    comp_choice=options[comp_number]
    print("comp chose "+comp_choice)

    if comp_choice=="rock" and our_input=="paper":
        print("You won!")
        score+=1
        print(score)

IndexError: list index out of range

2 Answers

As per the documentation of random.randint,

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

So, you can simply do

comp_number = random.randint(0, 2)

You just have to pick from 0 to 2 only.

comp_number=random.randint(0,2)

Seeing as you only have 3 options, [rock, paper, scissor] you only want to have 3 indexes in randomint. [0, 1, 2]

Related