Why does python come up with a TypeError even though I converted to strings?

Question:

So I created a Player and Dealer class for my blackjack game, but when I put the integer I want to print in an f-string, it comes up with a TypeError:

in results

print(f"{name}'s hand is {Player.hand}, total is {sum(Player.hand_val)}") 
TypeError: unsupported operand type(s) for +: 'int' and 'str'

It’s really confusing because I clearly printed it as a string. I also tried .format(), and str(), but they all showed up the same error message.

class Player:
    wallet = 5000
    hand_val = []
    hand = []

    def __init__(self, wallet, hand_val=None, hand=None):
        self.wallet = wallet
        self.hand_val = hand_val
        self.hand = hand


class Dealer(Player):
    hand_val = []
    hand = []

    def __init__(self, hand_val, hand, wallet):
        super().__init__(hand_val, hand)
        self.hand_val = hand_val
        self.hand = hand

def cardgenerate():
    cards = [("A", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5), ("6", 6), ("7", 7), ("8", 8), ("9", 9), ("10", 10),
             ("J", 10), ("Q", 10), ("K", 10)]
    select = r.choice(cards)
    cardGen.append(select[0])
    cardGen_value.append(select[1])


cardGen = []
cardGen_value = []


def hit():
    for i in range(2):
        cardgenerate()
    # playerHand is from even indexes from cardGen[]
    Player.hand.append(cardGen[0])
    Player.hand_val.append(cardGen[0])

    # dealerHand is from odd indexes from cardGen[]
    Dealer.hand.append(cardGen[1])
    Dealer.hand_val.append(cardGen[1])

def stay():
    cardgenerate()
    Dealer.hand.append(cardGen[0])
    Dealer.hand_val.append(cardGen[0])


def pcheck_lose():
    if sum(Player.hand_val) > 21:
        print("BUST!!! You lost")
        Player.hand_val = []
        return True


def dcheck_lose():
    if sum(cardGen_value) > 21:
        print("THE DEALER BUSTED!!! You won")
        Dealer.hand_val = []
        return True


def results():
    print(f"{name}'s hand is {Player.hand}, total is {sum(Player.hand_val)}")
    print(f"Dealer's hand is {Dealer.hand}, total is {sum(Dealer.hand_val)}")

Asked By: keqae

||

Answers:

You need to be sure that hand_val list has only integer/float values, somewhere maybe during initialization you are providing it a string?

hand_val = ['30', 30]
print(sum(hand_val))

gives unsupported operand type(s) for +: ‘int’ and ‘str’

hand_val = [30, 30]
print(sum(hand_val))

gives output of 60.

If you still want to provide str to the table, and then sum it up, you can cast value to int by using int(<str_variable>)

like so:

str = '30'
print(type(int(str)))

Output:
<class ‘int’>

Answered By: Alraku

I think this is the problem:

change this:

Player.hand_val.append(cardGen[0])

to

Player.hand_val.append(cardGen_value[0])
Answered By: Shahab Rahnama
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.