Python Draw Cards - Dictionary Card Deck

from random import randint suits = { 0: 'Clubs', 1: 'Diamonds', 2: 'Hearts', 3: 'Spades' } cards = { 0: 'Ace', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', 7: '8', 8: '9', 9: '10', 10: 'Jack', 11: 'Queen', 12: 'King' } def draw_cards(num_of_cards, list_dealt=[]): for z in range(num_of_cards): x = randint(0,3) #random integer 0 to 3 to pick suit y = randint(0,12) #random integer 0 to 12 to pick card mycard = "{0} of {1}".format(cards[y],suits[x]) if mycard not in list_dealt: list_dealt.append(mycard) else: num_of_cards = num_of_cards - z return draw_cards(num_of_cards,list_dealt) return list_dealt mydraw = draw_cards(5) #call the function with the number of cards you want. i = 0 for x in mydraw: i += 1 if i == len(mydraw): print("...And your last card is the {0}".format(str(x))) else: print("You got the {0}".format(str(x)))
Representing a deck of cards with two Python dictionaries. The first dictionary represents the card suits with keys of 0 to 3. The second dictionary represents the cards in any given suit with keys of 0-12. The function draw_cards() is called with the number of cards you want to draw. Optionally, you can supply a list of cards that have already been dealt from the possible 52. As with a real deck of cards, you should not be able to draw a duplicate. Therefore, when draw_cards() calls itself, it provides the list_dealt list containing the cards that have already been drawn from the deck. You could go further and make this into a game.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.