PythonMastery

How do I generate a random number in Python?

random.randint(1, 6) includes both ends; choice picks one item, sample picks several without repeats. For passwords and tokens, use secrets instead.

random.randint(a, b) gives a whole number from a to b, and both ends are included.

python
import random

roll = random.randint(1, 6)
print(roll)
example output · yours will differ
4

Yours will differ, which is the point. Press Run a few times.

The other things people need

python
import random

print(random.random())                   # a float from 0.0 up to (not including) 1.0
print(random.uniform(1.5, 3.5))          # a float in a range
print(random.choice(["rock", "paper", "scissors"]))
print(random.sample(range(1, 50), 6))    # 6 different numbers, no repeats

deck = ["A", "K", "Q", "J", "10"]
random.shuffle(deck)                     # shuffles in place, returns None
print(deck)
example output · yours will differ
0.6394267984578837
2.0498536229468446
paper
[33, 7, 48, 12, 25, 3]
['Q', 'A', '10', 'K', 'J']

Watch out for deck = random.shuffle(deck): shuffle changes the list where it is and returns None, so that line throws your deck away.

The same "random" numbers every time

For tests, simulations you want to repeat, or a bug you're chasing, set a seed. The same seed gives the same sequence on every run:

python
import random

random.seed(42)
print([random.randint(1, 100) for _ in range(5)])

random.seed(42)
print([random.randint(1, 100) for _ in range(5)])
output
[82, 15, 4, 95, 36]
[82, 15, 4, 95, 36]

Passwords, tokens and anything secret: use secrets

random is built to be fast and repeatable, and with enough of its output someone can predict the rest. For a password, a reset link or an API key, use secrets, which draws from the operating system's secure source:

python
import secrets
import string

alphabet = string.ascii_letters + string.digits
password = "".join(secrets.choice(alphabet) for _ in range(16))

print(len(password), "characters")
print(len(secrets.token_urlsafe(32)), "character reset token")
output
16 characters
43 character reset token

The password generator project builds a complete tool around this.

Go deeper: Project: Number Guessing Game, Project: Password Generator, Statistics for Data Science

More short answers

all questions