How to generate a random number by the computer from two list

Hello Guys,

Please how can I have the computer print out a random card using an fstring from these two lists?
(2,3,4,5,6,7,8,9,10,J,Q,K,A)
(clubs, diamonds, spades, and hearts)

I have tried to use this code below to test generate a single from 1-10, but with the string inside the loop gets confusing:

#Random.Randint Program
import random
value = random.randint(1,10)
print(value)

Thanks,

Eagle Eye

@radeyeye
No need to use a loop to pick a random card.
Just use randint inside the tuples to get a random element, and combine them with fstring.

from random import randint

cards = (2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A')
card_types = ('clubs', 'diamonds', 'spades', 'hearts')

random_card = f'{cards[randint(0, len(cards) - 1)]} of {card_types[randint(0, len(card_types) - 1)]}'

print(random_card)

Happy coding :slight_smile:

Cheers.

1 Like

could use itertools.product also for this,

import itertools, random
value = random.choice(list(itertools.product((2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', \
'Q', 'K', 'A'), ('clubs', 'diamonds', 'spades', 'hearts'))))

or,

import more_itertools # would have to `pip install more-itertools`
more_itertools.random_product((2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'), 
                              ('clubs', 'diamonds', 'spiders', 'hearts'))

Thanks Francesco, that worked.


import random

# Choose a random suit.
suit = random.choice(['clubs', 'diamonds', 'spades', 'hearts'])

# Choose a random card value.
value = random.choice(['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'])

print(value, 'of', suit)

2 Likes

Awesome Steven !!! This one has interesting less coding.

You’re using random.randint() incorrectly.

For a the card rank, you need (0, 12) as there are 13 card ranks 2 – A
For the card suit, you need (0, 3) as there are four suits.

1 Like

Lists indexes are Zero-Based, meaning that the first element in the list is

cardValue[0]

Your random.randint() range must start from 0, not 1.

IMPORTANT
Lists have square brackets [].
When you use parentheses, that is a different data type (a different data object).