jeudi 5 janvier 2023

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":

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']



Aucun commentaire:

Enregistrer un commentaire