# Trying coding 5 card poker

**URL:** <https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202>\
**Category:** Curriculum Help\
**Tags:** python\
**Created:** [January 18, 2024, 1:51pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202 "2024-01-18T13:51:01Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![gabbuz04.parkour](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/gabbuz04.parkour/32/321148_2.png) [@gabbuz04.parkour](https://forum.freecodecamp.org/u/gabbuz04.parkour)\
**Post date:** [January 18, 2024, 1:51pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/1 "2024-01-18T13:51:01Z")

</div>

### Tell us what’s happening:

I’m trying to do a Python’s poker program, but I’m having an issue with changing cards(probably due to suits and suits\_name). My idea was prining the cards with suits symbol, but changing them by typing suits name(as 2 of hearts, 5 of clubs…). There’s a way to give cards the suits value (hearts) but print them with symbol only?

And one more question: I’m a beginner with programming and I’m trying to coding this by myself. Do you think it’s an acceptable code? (It’s obviously not finished)

### Your code so far

```auto
import random, time

suits = ["♥️", "♦️", "♣️", "♠"]
hearts, diamonds, clubs, spades = suits
suits_name = (hearts, diamonds, clubs, spades)
value = (10, 11)
A = value[0]
J = value[1]
Q = value[1]
K = value[1]
number = [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K]

def start():
    play = input("You wanna play? ")
    if play.lower() in ("yes", "sure", "yeah"):
        unique_cards = set()
        while len(unique_cards) < 5:
            unique_cards.add(f"{random.choice(number)}{random.choice(suits_name)}")
        cards = list(unique_cards)
        print("Your cards are:", ", ".join(cards) )
        time.sleep(4)
        while True:
            change_cards = input("Want to change cards? ")
            if change_cards.lower() == "yes":
                quantity = input("Which cards? ")
                if quantity.lower() == "none":
                    print("chepalle")
                    break
                elif quantity.lower() in cards:
                    cards.remove(quantity.lower())
                    new_cards = [f"{random.choice(number)}{random.choice(suits_name)}" for _ in range(len(quantity.split(',')))]
                    cards.extend(new_cards)
                    print("Your new cards are: ", ", ".join(cards))
                    break
                elif quantity.lower() == "all":
                    all_choice = [f"{random.choice(number)}{random.choice(suits_name)}" for _ in range(5)]
                    print("Your new cards are: ", ", ".join(all_choice))
                    break
                else:
                    print("Invalid cards selected")
            elif change_cards.lower() == "no":    
                break
        # CONTROLLARE CARTE CON IPOTETICO AVVERSARIO/AVVERSARI
        print("ngul")
    else:
        exit()
    

start()

```

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [January 18, 2024, 8:26pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/2 "2024-01-18T20:26:41Z")

</div>

Cool project 👍

I would keep the suit names as strings in the code, and just use the symbols when printing the output for the user to see. I would keep the `suits` list as:

> `suits = ["Hearts", "Diamonds"...etc]`

internally in the code. You could have a dictionary mapping those to symbols

> `suit_dict = {"Hearts": "♥️", "Diamonds": "♦️" ... etc}`

and only use that when you print. Maybe `cards` is a collection of small lists

> `[[5,"Hearts"],[Q,"Diamonds"], ... etc]`

and when you print them something like

> `print(cards[0][0], "of", suit_dict[cards[0][1]])`

in a loop so it prints the value, and then looks up the suitable symbol in the dictionary. This way you can look up if the user wants to change “5 of hearts” you can check it against your list:

> `[[5,"Hearts"],[Q,"Diamonds"], ... etc]`

Something like that, I hope I made sense.

Basically: Keep the suit to symbol mapping in a dictionary and use it when you print the cards. Keep text for everything else to easily parse user input.

---

<div class="post-metadata">

**Author:** ![gabbuz04.parkour](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/gabbuz04.parkour/32/321148_2.png) [@gabbuz04.parkour](https://forum.freecodecamp.org/u/gabbuz04.parkour)\
**Post date:** [January 19, 2024, 1:31pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/3 "2024-01-19T13:31:35Z")

</div>

I tried that, but it says str object is not callable. Can you please help me? I would assign multiple values to the cards (suits and suits names) so the terminal prints the symbols but i can change cards typing their values in name, but I don’t know if it’s possible.  
Anyway thank you

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [January 19, 2024, 1:51pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/4 "2024-01-19T13:51:16Z")

</div>

> [@gabbuz04.parkour](#):
>
> I tried that, but it says str object is not callable.

Can you show me the code that generated this error?

---

<div class="post-metadata">

**Author:** ![gabbuz04.parkour](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/gabbuz04.parkour/32/321148_2.png) [@gabbuz04.parkour](https://forum.freecodecamp.org/u/gabbuz04.parkour)\
**Post date:** [January 19, 2024, 1:56pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/5 "2024-01-19T13:56:57Z")

</div>

I’ve already deleted it, because I’ve copied this code on a new file and made some little changes, but this evening or tomorrow I’ll try another time and if it shows the same error, I’ll reply to you

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [January 19, 2024, 1:59pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/6 "2024-01-19T13:59:00Z")

</div>

If what I said above makes sense, you can try implementing it.

I’m happy to help with any questions or errors.

---

<div class="post-metadata">

**Author:** ![gabbuz04.parkour](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/gabbuz04.parkour/32/321148_2.png) [@gabbuz04.parkour](https://forum.freecodecamp.org/u/gabbuz04.parkour)\
**Post date:** [January 22, 2024, 2:04pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/7 "2024-01-22T14:04:02Z")

</div>

I’ve tried different solutions, but nothing…  
Tried with your idea of dict, reassigning values, but nothing. Tried also this:

```auto
suits = ["♥️", "♦️", "♣️", "♠"]
suits_name = hearts, diamonds, clubs, spades = suits
hearts="♥️"
diamonds="♦️"
clubs="♣️"
spades="♠"

```

also tried that

```auto
suits_name = hearts, diamonds, clubs, spades = suits = ["♥️", "♦️", "♣️", "♠"]

```

I don’t know if these attempts are stupid or not, but this code still doesn’t work and I don’t know how to proceed, I want to code the checking hands part but firstly want to finish this.

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [January 22, 2024, 2:18pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/8 "2024-01-22T14:18:05Z")

</div>

> [@pkdvalis](#):
>
> suit\_dict = {“Hearts”: “❤”, “Diamonds”: “♦” … etc}

Can you share your code with the attempt using a dictionary? I really think that’s the way to go here. This makes it easy to map back and forth between the symbols and the words.

You could even use two lists:

```auto
suits = ["♥️", "♦️", "♣️", "♠"]
suits_name = ["hearts", "diamonds", "clubs", "spades"]

```

If the user types “3 of spades” to switch you lookup “spades” in the `suits_name` list and then lookup the same index in the `suits` list.

I could also see the user typing in the number of the card. For example:

```auto
Your cards are: 2♠, 5♣️, 11♥️, 11♦️, 11♣️
Want to change cards? yes
Which cards? 1,3

```

To refer to `2♠` and ` 11♥️` then you can just remove those in the `cards`. Easier for the player to type too

---

<div class="post-metadata">

**Author:** ![gabbuz04.parkour](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/gabbuz04.parkour/32/321148_2.png) [@gabbuz04.parkour](https://forum.freecodecamp.org/u/gabbuz04.parkour)\
**Post date:** [February 19, 2024, 1:08pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/9 "2024-02-19T13:08:29Z")

</div>

In the end, I’ve modified a little bit using classes, but I’m still having issues with how changing cards.

```auto
    import random, time
    from random import shuffle

    from enum import Enum

    class CardSuits(Enum):
        Hearts = "Hearts"
        Diamonds = "Diamonds"
        Clubs = "Clubs"
        Spades = "Spades"

    class CardValues(Enum):
        Two = 2
        Three = 3
        Four = 4
        Five = 5
        Six = 6
        Seven = 7
        Eight = 8
        Nine = 9
        Ten = 10
        Jack = "J"
        Queen = "Q"
        King = "K"
        Ace = "A"

    class Card:

        _symbols = {"Hearts": "♥️", "Diamonds": "♦️", "Clubs": "♣️", "Spades": "♠"}

        def __init__ (self, suit: CardSuits, value: CardValues) -> None:
            self.suit = suit
            self.value = value

        def __str__ (self) -> str:
            return f"{self.value.value}{self._symbols[self.suit.name]}"

        def __repr__ (self) -> str:
            return f"{self.value.value}{self._symbols[self.suit.name]}"

    def start():
        play = input("You wanna play? ")
        if play.lower() in ("yes", "sure", "yeah"):
            all_cards = [Card(suits, value) for suits in CardSuits for value in CardValues]
            shuffle(all_cards)
            unique_cards = set()
            while len(unique_cards) < 5:
                unique_cards.add(random.choice(all_cards))
            cards = list(unique_cards)
            print("Your cards are:", ", ".join(str(card) for card in cards))
            #time.sleep(4)
            while True:
                change_cards = input("Want to change cards? ")
                if change_cards.lower() == "yes":
                    quantity = input("Which cards? ")

                    card_input_index = first, second, third, fourth, fifth 
                    first, second, third, fourth, fifth = (1, 2, 3, 4, 5) 
                    first = cards[0]
                    second = cards[1]
                    third = cards[2]
                    fourth = cards[3]
                    fifth = cards[4]
                    

                    if quantity.lower() == "none":
                        break

                    elif quantity.lower() in card_input_index:
                        cards.remove(card_input_index)
                        while len(cards) < 5:
                        cards.add(random.choice(all_cards))
                        print("Your cards are:", ", ".join(str(card) for card in cards))
                        break
                    
                    
                    elif quantity.lower() == "all":
                        all_cards = [Card(suits, value) for suits in CardSuits for value in CardValues]
                        unique_cards = set()
                        while len(unique_cards) < 5:
                            unique_cards.add(random.choice(all_cards))
                        cards = list(unique_cards)
                        print("Your new cards are:", ", ".join(str(card) for card in cards))
                        break                
                    else:
                        print("Invalid cards selected")
                elif change_cards.lower() == "no":    
                    break     

            #CHECKING PHASE
                

            #SCORE DASHBOARD?
            
            
            while True:        
                continue_playing = input("You want to keep playing?")
                if continue_playing.lower() == "yes":
                    wanna_shuffle = input("Wanna shuffle the deck?")
                    if wanna_shuffle.lower() == "yes":
                        shuffle(all_cards)
                        print("Deck shuffled")
                        break
                    elif continue_playing.lower() == "no":
                        break
                    else:
                        continue
                elif continue_playing.lower() == "no":
                    exit()    
            start()   
            
            
        else:
            exit()
        

    start()

```

So now I’m trying to understand how change cards by an index input (1st, 4th / second or even 1, 4, 5…) instead of write every possible change.  
I’ve tried with that card\_input\_index, but the terminal gives me this error:

> UnboundLocalError: cannot access local variable ‘first’ where it is not associated with a value

So now I’ll search about this error and try to fix it

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [February 19, 2024, 1:49pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/10 "2024-02-19T13:49:45Z")

</div>

No, frankly this is not the way to use classes.

Use dictionary or list for these, or a set.

A class is to define a type of thing that you want to instantiate multiple instances of. Maybe you could define a deck of cards that has 52 cards and you can instantiate multiple decks and keep track of which cards have been dealt that way?

I see how you are using Enum/Class here:  
[https://docs.python.org/3/howto/enum.html](https://docs.python.org/3/howto/enum.html)

That’s fine but it does not solve your problem. I’ve explained as best I can above. I think you are over-complicating it.

If the user types “1” to change the first card, you just need to access `cards[0]`, or `cards[n - 1]`.

If you want the user to type “first” to change the first card, you just need to look it up in a dictionary, or use a simple `if` statement. Keep it simple.

```auto
n = input("What cards do you want to change?")

change(cards[n-1])

```

or

```auto
if n == "first":
    change(cards[0])

```

There’s only 5 cards so it will work. Or you look it up in a dictionary mapping:

```auto
dictionary =	{
  "first": 0,
  "second": 1,
  "third": 2
}

change(cards[dictionary[input]])

```

[https://www.w3schools.com/python/python\_dictionaries.asp](https://www.w3schools.com/python/python_dictionaries.asp)

---

<div class="post-metadata">

**Author:** ![Mundednes](https://avatars.discourse-cdn.com/v4/letter/m/ed655f/32.png) [@Mundednes](https://forum.freecodecamp.org/u/Mundednes)\
**Post date:** [July 5, 2024, 11:04am UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/11 "2024-07-05T11:04:37Z")

</div>

When I first dabbled in coding games, I found that poker was a perfect balance of challenge and fun. It helped me grasp concepts like logic flow, variables, and conditionals in a practical way. Plus, there’s something satisfying about seeing your code deal out hands and determine winners.

---

<div class="post-metadata">

**Author:** ![pkdvalis](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/pkdvalis/32/350571_2.png) [@pkdvalis](https://forum.freecodecamp.org/u/pkdvalis)\
**Post date:** [July 8, 2024, 10:02pm UTC](https://forum.freecodecamp.org/t/trying-coding-5-card-poker/665202/13 "2024-07-08T22:02:13Z")

</div>

Closed on July 8, 2024, 10:02pm UTC


