Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading