I'm very new at Python and trying to create Blackjack with as little help as possible, but how can I condense this?

Viewed 56
import random
card1 = random.randint(1, 14)
if card1 == 1:
    print('1 of Hearts')
elif card1 == 2:
    print('2 of Hearts')
elif card1 == 3:
    print('3 of Hearts')
#It's basically this over and over again, 11-14 would be ace, jack, queen, and king.

I'm trying to condense my code down into a way to where I don't have to make a new line of code every time I want to specify what a number from the random.randint means. If there isn't a way then please tell me so I'm not just searching for this for days.

If there's a problem in my communication with this please tell me and I'll fix it.

3 Answers

Maybe what you need is this?

import random
card1 = random.randint(1, 14)
print("{} of Hearts".format(card1))

Still, you need to declare special cases for JQK though.

Adding to AerysS's answer, here is a version that accounts for Ace, Jack, Queen and King. Since Ace is usually counted as "1", that is what my code does.

import random
card1 = random.randint(1, 13)
card1 = {1:"Ace",11:"Jack",12:"Queen",13:"King"}.get(card1,card1)
print("{} of Hearts".format(card1))

The proper way to do this is to create a deck of cards, then draw from it. You can create the deck by iterating through suit and rank lists with nested for loop. Then you can randomly draw from the deck:

import random
suits = ['C', 'S', 'H', 'D']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']

#to create a deck of cards
deck = []
for i in range(len(suits)):
    for j in range(len(ranks)):
        deck.append((suits[i],ranks[j])) #each card id a tuple of (suit, rank)

#to draw a card:
drawn_card = random.choice(deck)
print(drawn_card)
Related