I'm getting a KeyError after incrementing the value of another variable with the current value in the Key, don't know what I'm missing

Viewed 55
from random import shuffle
def makeDeck():
    Deck = []
    for i in range(4):
        valueCards = ["A", "K", "J", "Q"]
        Deck.append(valueCards)
        for cards in range(2,11):
            Deck.append(cards)
    shuffle(Deck)
    print(Deck)
    return Deck

I made some changes to the class by making self.score = self.setScore() as before when I set it to a number the value wasn't being updated at all.

class Player:
    def __init__(self, drawn = []):
        self.drawn = drawn
        
        self.score = self.setScore()
    def __str__(self):
        currentDraw = ""
        for cards in self.drawn:
            currentDraw += str(cards) + " "
        finalDraw = currentDraw + "score: " + str(self.score)
        return finalDraw


    def setScore(self):
        self.score = 0

        cardValues = {"A":11, "K":10, "J":10, "Q":10,
                      "2":2, "3":3, "4":4, "5":5, "6":6,
                      "7":7, "8":8, "9":9, "10":10}
        for cards in self.drawn:
            self.score += cardValues[cards]
        return self.score

I tested that I was being updated by printing out some values like so and those print the console just fine.

Player1 = Player(["4", "9"])
print(Player1)

When I add the next bit I receive the error and am not sure why.

cardDeck = makeDeck()
firstDraw = [cardDeck.pop()]
DrawOne = " ".join(str(e) for e in firstDraw)
secondDraw = [cardDeck.pop()]
DrawTwo = " ".join(str(j) for j in secondDraw)
thirdDraw = [cardDeck.pop()]
First = Player(firstDraw)
player1 = Player(secondDraw)
player2 = Player(thirdDraw)
defeat = False

while(defeat != True):
    choice = input("Higher or lower?: ")
    if choice == "Higher" or "higher":
        if DrawOne < DrawTwo:
            counter  += 1
            print(player1.score)
    if choice == "Lower" or "lower":
        if DrawOne > DrawTwo:
            counter += 1
            print(player1.score)
            player1
    else:
        defeat = True
        print(player1.score)
        print("Defeat")

2 Answers

In Makedeck you have those lines:

valueCards = ["A", "K", "J", "Q"]
Deck.append(valueCards)

That result in Deck being a list of one element, that element being a list of 4 strings.

You can check that the result of makedeck() = [["A", "K", "J", "Q"], 2, 3, 4, 5, 6, 7, 8, ...], and thus deck.pop() = ["A", "K", "J", "Q"]. What you really want is this instead:

Deck.extend(valueCards)

which will result in a list of 4 strings, and at the end of the function returns ["A", "K", "J", "Q", 2, 3, ...], which is what you want.

In the first case, you check if the element ["A", "K", "J", "Q"] exists as a key of your dict, which is not the case.

I fixed the KeyError and some other bugs, including:

  • KeyError problem, your cards type is interger,while dict cardValues key are strings
  • makeDeck error answerd by DriesDS
  • Variable counter not defined and never truly used
  • if-else syntax error and logic error

code:

from random import shuffle
def makeDeck():
    Deck = []
    for i in range(4):
        valueCards = ["A", "K", "J", "Q"]
        Deck.extend(valueCards)#answerd by DriesDS
        for cards in range(2,11):
            Deck.append(cards)
    shuffle(Deck)
    print(Deck)
    return Deck

class Player:
    def __init__(self, drawn = []):
        self.drawn = drawn
        
        self.score = self.setScore()
    def __str__(self):
        currentDraw = ""
        for cards in self.drawn:
            currentDraw += str(cards) + " "
        finalDraw = currentDraw + "score: " + str(self.score)
        return finalDraw


    def setScore(self):
        self.score = 0

        cardValues = {"A":11, "K":10, "J":10, "Q":10,
                      "2":2, "3":3, "4":4, "5":5, "6":6,
                      "7":7, "8":8, "9":9, "10":10}
        for cards in self.drawn:
            self.score += cardValues[str(cards)]#your cards type is interger,while dict cardValues key are strings
        return self.score

Player1 = Player(["4", "9"])
print(Player1)
cardDeck = makeDeck()
firstDraw = [cardDeck.pop()]
DrawOne = " ".join(str(e) for e in firstDraw)
secondDraw = [cardDeck.pop()]
DrawTwo = " ".join(str(j) for j in secondDraw)
thirdDraw = [cardDeck.pop()]
First = Player(firstDraw)
player1 = Player(secondDraw)
player2 = Player(thirdDraw)
defeat = False
counter = 0

while(defeat != True):
    choice = input("Higher or lower?: ")
    if choice == "Higher" or choice == "higher":
        if DrawOne < DrawTwo:
            counter  += 1
            print(player1.score)
    elif choice == "Lower" or choice == "lower":
        if DrawOne > DrawTwo:
            counter += 1
            print(player1.score)
    else:
        defeat = True
        print(player1.score)
        print("Defeat")

result:

4 9 score: 13
['A', 6, 6, 9, 5, 7, 'A', 4, 'Q', 5, 7, 5, 9, 8, 9, 4, 'K', 7, 'J', 3, 8, 'K', 2, 9, 'J', 4, 2, 8, 'K', 10, 7, 'A', 3, 'Q', 6, 2, 5, 6, 'Q', 3, 'J', 10, 2, 10, 4, 10, 'Q', 'A', 3, 8, 'K', 'J']
Higher or lower?: higher
10
Higher or lower?: lower
Higher or lower?: 1
10
Defeat
Related