Home > Back-end >  How do i change elements in a list?
How do i change elements in a list?

Time:09-23

I am making a program to emulate a game of blackjack. One thing i need to account for are the royal cards (king, queen etc.) For these the value should changed to be ten. I want the game to finely print that the dealer has either of these cards if they do, but i need to add a "score" but i cant sum a int with string object. I've tried solving this problem by introducing a for loop in the dealer function to replace every royal with the value 10, but when i return the "score", it seems as the values have not been changed because I get the error:

line 22, in dealer score=cards[0] cards[1]

TypeError: unsupported operand type(s) for : 'int' and 'str'

My code is under:

import random

deck=[2,3,4,5,6,7,8,9,10,'A','J','Q','K']*4

#Deal cards from deck
def deal(deck):
    cards=[]
    for i in range(2):
        cards.append(random.choice(deck))
    return cards

#Dealers hand
def dealer():
    cards=deal(deck)
    
    for i in range(len(cards)):
        royals=['J','Q','K']
        if i in royals:
            cards[i]=10
            score=cards[0] cards[1]
        else:
            score=cards[0] cards[1]
    

    return (f'Dealer has the cards {cards[0]} and ?', score)

CodePudding user response:

instead of using J ,Q ,K use number such as 11,12,13 respectively then it will add the score.

CodePudding user response:

It seems likely that you're modifying cards out of scope. Try passing cards as an argument to the function and returning it. I could be wrong about that.

It seems to be like a better solution might be to put the value of the face cards in the list (1, 11, 12, 13) and then having doing something like min(cards[i], 10) with a special check for the ace.

I would also advise iterating over the list items directly instead of integer indexing.

CodePudding user response:

The problem is you evaluate score before checking if both cards are number. So you get an error when the last card is a letter.

def dealer():
    cards = deal(deck)

    for i in range(len(cards)):
        royals = ['J', 'Q', 'K']
        if cards[i] in royals:
            cards[i] = 10
        elif cards[i] == 'A':
            cards[i] = 11

    score = sum(cards)
    return (f'Dealer has the cards {cards[0]} and ?', score)

This is if you want to use the letters, it would be easier just using 11,12,13.

If you dont want to change the original list, this will be easier:

def dealer():
    cards = deal(deck)
    score = 0
    for i in range(len(cards)):
        royals = ['J', 'Q', 'K']
        if cards[i] in royals:
            score  = 10
        elif cards[i] == 'A':
            score  = 11
        else:
            score  = cards[i]

    return (f'Dealer has the cards {cards[0]} and ?', score)
  • Related