Python random Module: randint, choice and shuffle
Random Numbers in Python: random.randint()
The random module makes values your program can't know in advance. random.randint(a, b) gives back a random whole number from a to b, and both ends are included.
import random
roll = random.randint(1, 6)
print("You rolled", roll) # Output: You rolled 4 (or any number from 1 to 6)
Run it twice, and you'll likely see two different numbers. That's the whole point! Because the output changes every run, the live example below prints something that doesn't change: a check that the roll is in range.
import random
roll = random.randint(1, 6)
print(1 <= roll <= 6)
print(type(roll))True <class 'int'>
Think of it like rolling a real dice. You know it lands on 1, 2, 3, 4, 5 or 6. You just don't know which one until you roll.
The rules
random.randint(1, 6)can give 1, 6, or anything between. Both ends are in.- That's different from
range(1, 6)in chapter 10, which stops before 6. - Each call is a new roll: call it again for a new number.
- The first number must not be bigger than the second.
Roll many times
Put randint() in a for loop to roll again and again. Every number lands in range, even though you can't know which:
import random
all_good = True
for i in range(100):
roll = random.randint(1, 6)
if roll < 1 or roll > 6:
all_good = False
print("100 rolls, all from 1 to 6:", all_good)100 rolls, all from 1 to 6: True
Avoid: the numbers the wrong way round
import random
print(random.randint(6, 1))ValueError: empty range in randint(6, 1)
"Empty range" means there are no numbers from 6 up to 1. Put the small number first: randint(1, 6).
Common beginner doubt: "Are these numbers truly random?" Not quite. The computer works them out with a clever formula, so they're called pseudo-random ("pseudo" means "pretend"). For games and practice, they're random enough.
random.randint(a, b) gives a random whole number from a to b, both ends included.