0

Before we start, I am quite new to python.

This code is supposed to create a 5 card hand that would be later on used in a game of 'Go Fish'. The reason there's so many variables is for purposes later on in the game, so please ignore the messiness if possible.

Obviously card's aren't able to repeat, since there's only one of each card in a normal deck of cards. To avoid creating a hand with two cards that are the same, I used the while loops (as you can see in the code). I seem to be having a problem with the while loops though. The 'or' statements seem to create a problem in the code where it won't execute in the shell (The '>>>' doesn't even appear, just a blank cursor).

To fix the execution problem, I changed the code to use equal signs

For example : While p55 == p11 == p22 == p33 == p44 :

However, when running the code, I still encounter duplicates of cards.

If anyone can help me figure out how to get around this duplicate error, that would be great.

Thank you in advance!

def player_hand():
    CardSuit = ['Hearts','Diamonds','Clubs','Spades']
    CardNum = ['Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King']

    PlayerHand = []

    p1 = str(random.choice(CardNum))
    p11 = p1, 'of', str(random.choice(CardSuit))
    p111 = " ".join(p11)
    PlayerHand.append(p111)

    p2 = str(random.choice(CardNum))
    p22 = p2, 'of', str(random.choice(CardSuit))
    while p22 == p11 :
        p2 = str(random.choice(CardNum))
        p22 = p2, 'of', str(random.choice(CardSuit))
    p222 = " ".join(p22)
    PlayerHand.append(p222)

    p3 = str(random.choice(CardNum))
    p33 = p3, 'of', str(random.choice(CardSuit))
    while p33 == p11 or p22 :
        p3 = str(random.choice(CardNum))
        p33 = p3, 'of', str(random.choice(CardSuit))
    p333 = " ".join(p33)
    PlayerHand.append(p333)

    p4 = str(random.choice(CardNum))
    p44 = p4, 'of', str(random.choice(CardSuit))
    while p44 == p11 or p22 or p33 :
        p4 = str(random.choice(CardNum))
        p44 = p4, 'of', str(random.choice(CardSuit))
    p444 = " ".join(p44)
    PlayerHand.append(p444)

    p5 = str(random.choice(CardNum))
    p55 = p5, 'of', str(random.choice(CardSuit))
    while p55 == p11 or p22 or p33 or p44 :
        p5 = str(random.choice(CardNum))
        p55 = p5, 'of', str(random.choice(CardSuit))
    p555 = " ".join(p55)
    PlayerHand.append(p555)

    return PlayerHand
Evan Cooper
  • 146
  • 1
  • 2
  • 10

1 Answers1

3
p33 == p11 or p22

This is not the same as

p33 == p11 or p33 == p22

This type of question comes up often, here is one such example.

The reason the first case does not work:

p33 == p11 or p22

Is broken into

(p33 == p11) or (p22)

Notice that the truthiness of p22 is evaluated separately.

Community
  • 1
  • 1
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218