I am a python newbie. I am in the phase of testing my code but I am quite confused why sometimes this works and sometimes it does not. As per my understanding the random.randint(0,13) this means that random numbers from 0 to 12 which is the number of my cards list.
Error im geting:
Traceback (most recent call last):
File "main.py", line 72, in <module>
generate_random_hand()
File "main.py", line 32, in generate_random_hand
computer_hand.append(cards[rand1])
IndexError: list index out of range
Here is the code:
#Init
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computer_hand = []
player_hand = []
isContinue = True
#Generate first 2 cards of computer and player
def generate_random_hand():
for _ in range(0,2):
rand1 = random.randint(0,13)
rand2 = random.randint(0,13)
computer_hand.append(cards[rand1])
player_hand.append(cards[rand2])
Here is the screenshot of the problem:
Image of ERROR
EDIT:
Seems like I have mistaken the functionality of
for _ in range() which does not include the 2nd argument
and the random.randint() which includes the 2nd argument. Since I cannot delete this post anymore.
>Solution :
Seems you have an incorrect assumption.
A quick test gave me the following output:
>>> from random import randint
>>> randint(0,13)
3
>>> randint(0,13)
1
>>> randint(0,13)
10
>>> randint(0,13)
2
>>> randint(0,13)
12
>>> randint(0,13)
12
>>> randint(0,13)
3
>>> randint(0,13)
12
>>> randint(0,13)
6
>>> randint(0,13)
2
>>> randint(0,13)
13
So when you eventually get a 13, the exception tells you the value provided is not in the range of indices in your list of cards: 0-12