Search code examples
pythonlistclassblackjack

Python list doesn't seem to be updating


I'm fairly new to python and I'm trying to create blackjack. However, when I'm trying to print out what the player's hand is, I run into a few difficulties.
This is my code for hitting (drawing a card):

def hit(card, deck):
    global money, choice

    choice = input("How much would you like to bet?\n")
    money -= int(choice)
    print("You have decided to bet $" + str(choice))
    card = card.drawCard(deck.deck)
    card.getPt()
    deck.addScore(card)
    deck.addCard(card)
    c = str(card)
    p = str(deck)
    print("You have drawn: " + str(c) + "\n")
    print("The player has:\n" + str(p) + "\n")
    print("Total score:", deck.score)

And this is my code for printing my cards out:

def __str__(self):
    for i in range(0, len(self.deck)):
        self.print = self.print + "\n" + str(self.deck[i])
    return self.print

The first thing my code does is draw two cards for the dealer and the player, which runs fine. However, after the player draws a card is where it gets a bit wonky. The output is something like this:

The player has drawn Card A  
The player has drawn Card B
Total score: number

How much would you like to bet?  
number

You have bet number  
You have drawn Card B

Player has:  
Card A  
Card B  
Card A  
Card B  
Card B  

When I draw a new card, the card doesn't change, it stays the last card I drew. Then, when I print my deck, it prints my old deck and my new deck. However, the score is correct, which indicates that my list is only three cards long. What is going on, and why is it printing five cards?

Full code
Example output


Solution

  • Well, to get to the answer in short: you never reset Deck.print. So it keeps accumulating at each call to __str__

    But in general this code could be improved significantly E.g. your __str__ function is far from being pythonic. Something along the lines of

    return '\n'.join(self.deck)
    

    would look much better.

    In general there is no need to prepend each variable with "self." if they are used within the function only. In most cases in a class method you either update an object variable (self.something) or return some value from the function, but not both. There may, of course, be exceptions to this, but it seems in your case this is the rule and not the exception.

    Using globals is also something you should avoid whenever possible.