Python Random Choices in Practice
Random choice picks one item by chance. Real programs use it for draws, dice, and shuffles.
Pick one drink
random.seed(7) fixes the picks. choice() then picks coffee every time.
import random
random.seed(7)
print(random.choice(["tea", "coffee", "juice"]))Roll a die three times
randint(1, 6) picks a whole number from 1 to 6. Three calls give three rolls.
import random
random.seed(7)
print(random.randint(1, 6))
print(random.randint(1, 6))
print(random.randint(1, 6))Mix a small deck
shuffle() mixes the list itself. The same seed gives the same mix.
import random
random.seed(7)
cards = ["ace", "king", "queen", "jack"]
random.shuffle(cards)
print(cards)Example
import random
random.seed(5)
names = ["Ada", "Bob", "Cy", "Dee"]
winner = random.choice(names)
roll = random.randint(1, 20)
random.shuffle(names)
print("Winner:", winner)
print("Roll:", roll)
print("Order:", names)Key points
- Use random.choice(items) to pick one item from a list
- Use random.randint(a, b) to pick a whole number from a to b
- Use random.shuffle(items) to mix a list
- shuffle() changes the list itself, and gives back nothing new
- seed: a starting point that fixes the random picks
- Use random.seed(n) to fix the picks, so a run repeats
- The same seed gives the same picks on every run
In this example, the seed is 5, so the picks stay fixed. choice() picks Cy as the winner. randint(1, 20) rolls a 12. shuffle() then mixes the four names into a new order. The printouts show the winner, the roll, and the mixed order.
Note
Without a seed, the picks change on every run, so testing gets hard.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does random.seed(7) do before a choice?