pythonlistif-statementsumblackjack

How to make a function that take all 11s in a list, turn them into 1 and sums the list? in Python


I'm new to python and programming in general, and I have the assignment to make a Black Jack game.

and I have this function that checks if the score(sum) is over 21 and has 11's in a list, it will turn the 11's into 1's. and if the sum is still over 21, then the user lost, and the game is over.

Basically something like this

my code:

user = [11,7,7]
user_score = sum(user)

def check_11_user():
  if user_score > 21:
    if 11 not in user:
      print("you lose")
    elif 11 in user:
      for x in range(len(user)):
        if user[x] == 11:
          user[x] = 1
          if user_score > 21:
            print("you lose")

my problem is, that it will print "you lose" even if the list will be [1,1,1] for exmaple.

thanks, i hope its clear enough


Solution

  • It's easier IMO if you start by turning all your aces into 1s -- you will never want to count more than one ace as an 11 (two 11s will always produce a bust), so once they're represented as 1s all you need to do is decide is whether to add 10 to the score or do nothing at all. If you have multiple 11s to contend with, you need to figure out how many of them to turn into 1s (subtracting some multiple of 10 from the score).

    >>> def best_blackjack_score(cards):
    ...     cards = [1 if rank == 11 else rank for rank in cards]
    ...     if 1 in cards and sum(cards) <= 11:
    ...         return sum(cards) + 10
    ...     return sum(cards)
    ...
    >>> best_blackjack_score([11, 7, 7])
    15
    >>> best_blackjack_score([11, 10])
    21
    >>> best_blackjack_score([11, 11])
    12
    

    Once you have a function that computes the score, you can do things like:

    if best_blackjack_score(cards) > 21:
        print("you lose!")
    

    as well as more complicated things like:

    if best_blackjack_score(my_cards) > 21:
        print("I lose!")
    elif best_blackjack_score(your_cards) > 21:
        print("You lose!")
    elif best_blackjack_score(my_cards) > best_blackjack_score(your_cards):
        print("I win!")
    # etc