0

I am trying to list every card in a deck of cards (along with a number assigned to the card) using this code:

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

def translate():
    rank = ""
    suit = ""
    cards = ""
    cardNum = 0

    for x in rankName:
        rank = x

    for y in suitName:
        suit = y

    for i in range(0, NUMCARDS):
        cards += rank
        cards += " of "
        cards += suit
        cardNum = i
        i += 1

        print cardNum
        print "    "
        print cards

My output is only getting "King of clubs" 52 times though. What do I need to do?

1
  • Ah, the joys of indentation levels. Commented Jun 14, 2013 at 23:05

2 Answers 2

3

There are built-in methods for accomplishing what you want as well.

import itertools

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

cross_product = itertools.product(rankName, suitName)

for card_num, (rank, suit) in enumerate(cross_product, start=1):
  print("{0}    {1} of {2}".format(card_num, rank, suit))
Sign up to request clarification or add additional context in comments.

2 Comments

im afraid that this is not cleaner than two simple for loops, quite the opposite is the case IMO
@Paranix intertools.product and enumerate are encapsulated, generic versions of the for loops. You should read up on them, as they much easier to understand if you know them.
2

Your loops should be nested, but right now they just execute in order. Right now, rank goes through all rankNames and gets set to the last one, suit goes through all suitNames and gets set to the last one, and then they're printed out 52 times.

You shouldn't even really have that last loop.

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

def translate():
    cardNum = 0

    for x in rankName:
        rank = x

        for y in suitName:
            suit = y

            cards = ""
            cards += rank
            cards += " of "
            cards += suit
            i += 1

            print cardNum
            print "    "
            print cards

Also, rank = x and suit = y could just be for rank in rankName: and for suit in suitName. Also also, pre-initializing the variables isn't really useful.

1 Comment

Never mind, I figure it out. Set the cardNum to += 1 instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.