Key Functions
import random random.randint(1, 6) # 1..6 inclusive random.randrange(0, 10, 2) # 0,2,4,6,8 random.random() # 0.0–1.0 random.uniform(1.5, 2.5) # float in range random.choice(["a","b","c"])# one element random.choices(lst, k=5) # with replacement random.sample(lst, k=3) # without replacement random.shuffle(lst) # in-place
Reproducible Randomness
random.seed(42) print(random.randint(1, 100)) # same number every run
Dice-Roll Simulator
import random
rolls = [random.randint(1, 6) for _ in range(1000)]
for face in range(1, 7):
print(face, rolls.count(face))
Secure Randomness
For passwords or tokens, use secrets, not random:
import secrets token = secrets.token_hex(16)
Practise this on PyForm — free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm →