Python Random Number Generator
Random numbers in Python: a random integer in any range, floats, picking and shuffling, and secure random values - with ready-to-paste code
How to generate a random number in Python: import random for games and simulations, secrets for anything security-related. Pick a range above for a ready-to-paste snippet, or copy the examples below.
Random Integer in a Range
Both functions are in the standard library - nothing to install. randint includes both ends; randrange excludes the stop value, like range().
import random
random.randint(1, 10) # 1..10, both ends included
random.randrange(0, 10) # 0..9, stop is excluded
random.randrange(0, 100, 5) # 0, 5, 10 ... 95
Random Float
random() returns a float in [0.0, 1.0); uniform(a, b) scales it to your range.
import random
random.random() # 0.0 <= x < 1.0
random.uniform(1.5, 4.5) # float between 1.5 and 4.5
Pick and Shuffle
choice picks one item, sample picks several without repeats, shuffle reorders a list in place.
import random
items = ["red", "green", "blue", "yellow"]
random.choice(items) # one item
random.sample(items, 2) # two different items
random.shuffle(items) # shuffles the list in place, returns None
Secure Random Numbers with secrets
The random module is a Mersenne Twister: fast and reproducible, but predictable. For passwords, tokens, invite codes or prize draws use secrets, which reads from the operating system CSPRNG.
import secrets
secrets.randbelow(10) + 1 # 1..10
secrets.choice(["a", "b"]) # secure pick
secrets.token_hex(16) # 32 hex characters
secrets.token_urlsafe(16) # URL-safe token
secrets.SystemRandom().shuffle(items) # secure shuffle
Common Mistakes
Naming your own file random.py shadows the module, so import random loads your file and random.randint fails with an AttributeError - rename the file and delete __pycache__. Use random.seed(42) only when you want the same sequence every run (tests, simulations).
import random
random.seed(42) # reproducible sequence
print(random.randint(1, 6))
Frequently Asked Questions
How do I import random in Python? ▶
How do I generate a random number between 1 and 10 in Python? ▶
What is the difference between randint and randrange? ▶
Is Python random secure? ▶
[ HOW TO CITE THIS PAGE ]
Generate-Random.org. (2026). Python Random Number Generator. Retrieved from https://generate-random.org/random-number-python
Python Random Number Generator - Generate-Random.org (https://generate-random.org/random-number-python)