Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Random choice function adds invinsible "0"?

I wanted to define a function that gets me the set amount of keys in a dictionary and puts it in a list.
The function though adds a "0" to the list, which is not a key and also exceeds the set amount?
I tried the code in 2 different editors (VS Code and Thonny), both did this in like 40% of the time…

The Code:

import random

def random_card(times):
    chosen_card = []
    for t in range(times):
        chosen_card += random.choice(list(cards))
    return chosen_card

cards = {
        'A': 1,
        '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 
        'J': 10, 'Q': 10, 'K': 10
        }

player_cards = random_card(2)
pc_cards = random_card(2)

print(f"Your cards: {player_cards}\nDealer cards: {pc_cards}")

print(list(cards))

Outputs with the "0":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your cards: ['8', '1', '0']
Dealer cards: ['9', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['Q', '1', '0']
Dealer cards: ['7', '1', '0']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

Your cards: ['J', '1', '0']
Dealer cards: ['Q', '4']
['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

>Solution :

Problem lies here

chosen_card += random.choice(list(cards))

using += cause problems for any string of length greater than 1, in your case it is 10. Consider following simple examples

cards = []
cards += "7"
print(cards) # ['7']
cards += "10"
print(cards) # ['7', '1', '0']

It did add 1 then 0 rather than 10. If you have to use += AT ANY PRICE then encase added value in list, namely

cards = []
cards += ["10"]
print(cards) # ['10']

otherwise you might use .append which is method altering list inplace, following way

cards = []
cards.append("10")
print(cards) # ['10']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading