Can't figure out why my list index is out of range

Question:

i created a function to count the value of a blackjack hand with a for loop but it keep telling me that the index is out of range and i can’t figure out why

i tried switching from "for card in total_cards" to a "for card in range(0, len(total_cards))" hoping that that would solve my problem, but i keep getting the same error. Since both errors seems to originate from the function, what am i missing here? Thank you all in advance.

import random

def count_total(total_cards):
    total = 0
    for card in total_cards:
        total += total_cards[card]
    return total


cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

house_cards = []
player_cards = []
for i in range (1, 5):
    if i % 2 == 0:
        player_cards.append(cards[random.randint(0, len(cards) - 1)])
    elif i % 2 != 0:
        house_cards.append(cards[random.randint(0, len(cards) - 1)])

print(house_cards)
print(player_cards)

should_continue = True
while should_continue:
    action = input("Typr 'y' to ask for a card or 'n' to stop: ")
    if action == "n":
        should_continue = False
        break
    elif action == "y":
        player_cards.append(cards[random.randint(0, len(cards) - 1)])
        count_total(player_cards)
        if count_total(player_cards) > 21:
            should_continue = False
            print("You have gone over 21, you lost!")
            break
Asked By: Niccolò Baresani

||

Answers:

This is the problem:

for card in total_cards:
    total += total_cards[card]

You don’t need to index into the collection – the for loop is doing that for you. Just change it to:

for card in total_cards:
    total += card
Answered By: Woodford

I’m relatively new, but I believe when you iterate through a list in python using the for loop, you have already "pulled" the data out of it. So:

for card in total_cards:
    total += total_cards[card]

should be:

for card in total_cards:
    total += card
Answered By: sentinel_33

player_cards contain values from 0 to len(cards)-1=12. At the first call to count_total, player_cards has 3 elements, one from for-loop i==2 and i==4 and one from line above call. In count_total you use "for card in total_cards" meaning that card take the values of total_cards which is player_cards. Then you try to retrieve elements from a list of length three with index "card" = values from 0 to 12.

If your using range you need to subtract 1 from the upper limit:
for card in range(0, len(total_cards)-1)

Answered By: hoax
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.