Dice rolls, loot drops, shuffled cards, a random enemy: games are full of chance. Python's random module gives you all of it in a few lines.
A RANDOM WHOLE NUMBER
import random
roll = random.randint(1, 6)
print("You rolled", roll)
randint(1, 6) gives a whole number from 1 to 6, both ends included, just like a die. Run it again and you get a different result.
PICK FROM A LIST
import random
loot = ["sword", "shield", "potion", "gold"]
print(random.choice(loot))
choice picks one item. To pick several different items at once, use random.sample(loot, 2).
SHUFFLE A LIST
import random
cards = ["A", "K", "Q", "J"]
random.shuffle(cards)
print(cards)
shuffle changes the list itself and returns None. Write random.shuffle(cards), not cards = random.shuffle(cards).A CHANCE OF SOMETHING HAPPENING
random.random() gives a decimal from 0 up to (not including) 1. Compare it to a percentage to make something happen "sometimes":
import random
if random.random() < 0.25:
print("Critical hit!") # happens about 1 time in 4
else:
print("Normal hit")
THE SAME "RANDOM" RESULT EVERY TIME
For testing, you can make the random numbers repeat with random.seed(). Same seed, same sequence:
import random
random.seed(1)
first = [random.randint(1, 6) for _ in range(5)]
random.seed(1)
second = [random.randint(1, 6) for _ in range(5)]
print(first == second)True
import random
dice = [random.randint(1, 6) for _ in range(3)]
print(len(dice), min(dice) >= 1, max(dice) <= 6)COMMON BEGINNER MISTAKES
import random at the top. Without it, Python says NameError: name 'random' is not defined.random.py. Python then imports your file instead of the real module. Rename it.randint(1, 6) can return 6, but range(1, 6) stops at 5.PRACTICE IT, DON'T JUST READ IT
In Function Forest you build a dice-rolling battle helper out of small functions, with real Python running on your phone.
PLAY FUNCTION FOREST ▸FAQ
How do I get a random number in Python?
import random, then random.randint(1, 6) for a whole number from 1 to 6, both included.
How do I pick a random item from a list?
random.choice(my_list) returns one random item.
Why does random.shuffle return None?
It shuffles the list in place. Call random.shuffle(cards) and then use cards.