The idiomatic way would be to use random.choice()
.
That can be used on a 1. dict
or a sequence like a 2. tuple
(a list
would also work), depending on how important is to you the number-to-text relationship (e.g. 1 -> Head).
- with
dict()
:
import random
coin_outcome = {1: 'Head', 2: 'Tail'}
print("Flipping the coin")
coin_values = list(coin_outcomes.keys())
outcome = random.choice(coin_values)
print(coin_outcome[outcome])
- with
tuple()
:
import random
coin_outcome = 'Head', 'Tail'
print("Flipping the coin")
outcome = random.choice(coin_outcome)
print(outcome)
You can rework it in a number of different ways that do avoid random.choice()
, but this would mean hardcoding a number of assumptions.
For example, if you were to use random.randint()
to get the key of the coin_outcome
dictionary (as in 1.) you should make sure that the result of random.randint()
is a valid key, and you cannot use say 10
and 20
without adding extra logic to handle this.