Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question
#1
Card = collections.namedtuple('Card',['rank','suit'])

class FrenchDeck:
    ranks = [str(n) for n in range(2,11)] + list('JQKA')
    suits = 'spades diamonds clubs hearts'.split()

    def __init__(self):
        self._cards = [Card(rank,suit) for suit in self.suits
                                        for rank in self.ranks]
    def __len__(self):
        return len(self._cards)

    def __getitem__(self,position):
        return self._cards[position]


deck = FrenchDeck()

from random import choice
print(choice(deck))
So when I run the print(choice(deck)) code above it prints a different card every time for example:Card(rank='3', suit='clubs')

How would I get it to print out "3 of clubs" instead of the Card(rank='3', suit='clubs') ?
Reply
#2
First, pls use Python tags to post code, makes is a lot easier to see what is going on.

Change your print statement to
chc = choice(deck)
print (f"{chc.rank} of {chc.suit}")
Reply
#3
ok thanks for your help
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020