Search code examples
pythonfunctionintegertypeerror

I have this TypeError : Unsupported operand type(s ) for +: 'int' and 'function'


import random

def deal_card():
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    card = random.choice(cards)
    return card


user_cards = []
computer_cards = []

for _ in range(2):
    user_cards.append(deal_card)
    computer_cards.append(deal_card)



def calculate_score(cards):
    if sum(cards) ==21 and len(cards) == 2:
        return 0

    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)

    return sum(cards)



user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)

print(user_score)

1


Solution

  • user_cards.append(deal_card)
    computer_cards.append(deal_card)
    

    These lines caused trouble.

    You appended the function deal_card, instead of the value calling the function will return (deal_card()).

    When the line sum(cards) ran, Python tried to add deal_card (the function) with a number. This will cause an error.

    Change .append(deal_card) to .append(deal_card()) should solve your issue.