Home > other >  How do I convert two repeating for loops for my blackjack game into a single function
How do I convert two repeating for loops for my blackjack game into a single function

Time:10-31

I am creating a blackjack game and I am familiar with the rules of the game. But my conundrum lies elsewhere. I am able to randomly append cards to computer and user. But for that purpose I have written the for loop twice. I want to just write a function for randomly assigning two different set of cards to the user and computer. I have included the code below for better understanding

import random
print("Welcome to Blackjack!")
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def deal_cards():
  return random.choice(cards)


user_cards = []
for _ in range(2):
  card = random.choice(cards)
  if card in user_cards:
    continue
  else:
    user_cards.append(card)


computer_cards = []
for _ in range(2):
  card = random.choice(cards)
  if card in computer_cards:
    continue
  else:
    computer_cards.append(card)

print(user_cards)
print(computer_cards)

CodePudding user response:

You can try something like this

def deal_hand():
    hand = []
    for _ in range(2):
        card = random.choice(cards)
        if card in hand:
            continue
        else:
            hand.append(card)
    return hand

and then

user_hand = deal_hand()
dealer_hand = deal_hand()
  • Related