""" card.py Zelle's python book, chap 10 exercise 11 pg 333-334 : create a playing card object. Jim Mahoney | Nov 2014 """ from random import randrange suit_names = ['Spades', 'Clubs', 'Diamonds', 'Hearts'] card_ranks = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King'] def random_choice_from(some_list): """ Return a random element from a list """ # ... but lookup random.choice which does this for you ... length = len(some_list) random_index = randrange(length) return some_list[random_index] class Card(object): """ An object that represents a playing card, including its rank (e.g. 'Ace' or 'Two') and suit (e.g. 'Clubs' or 'Hearts') """ def __init__(self, rank=False, suit=False): # Set card rank, or pick a random rank if one isn't given. if not rank in card_ranks: rank = False if not rank: rank = random_choice_from(card_ranks) self.rank = rank # Set card suit, or pick a random suit if one isn't given. if not suit in suit_names: suit = False if not suit: suit = random_choice_from(suit_names) self.suit = suit def getRank(self): return self.rank def getSuit(self): return self.suit def __str__(self) : return self.getRank() + ' of ' + self.getSuit() def BJValue(self): """ Return Black Jack value : Ace is 1, 10 through King is 10 """ # This is *not* a great implementation ... but it works. if self.rank == 'Ace': return 1 elif self.rank == 'Two': return 2 elif self.rank == 'Three': return 3 elif self.rank == 'Four': return 4 elif self.rank == 'Five': return 5 elif self.rank == 'Six': return 6 elif self.rank == 'Seven': return 7 elif self.rank == 'Eight': return 8 elif self.rank == 'Nine': return 9 else: return 10 def main(): for i in range(20): card = Card() print 'The {} has blackjack value {}.'.format(str(card), card.BJValue()) main()