Python Practice › Basic Programs › Program 31
Generate random numbers
Write a Python program to generate random numbers.
Output
74 [1, 4, 4, 5, 1] 1.706 [32, 18, 42, 11, 3, 34]
Approach
- Use the
randommodule:randintfor whole numbers,randomanduniformfor decimals. - Seed the generator to make the output repeatable.
Solution
import random random.seed(10)print(random.randint(1, 100))print([random.randint(1, 6) for _ in range(5)])print(round(random.uniform(1.5, 2.5), 3))print(random.sample(range(1, 50), 6))Output
74 [1, 4, 4, 5, 1] 1.706 [32, 18, 42, 11, 3, 34]
Line by line
Line 3
A fixed seed makes the sequence repeat on every run. Remove it to get different numbers each time.
Line 4
randint(1, 100) includes both ends.
Line 5
Five dice rolls.
Line 6
uniform returns a float between the two values.
Line 7
sample picks 6 different numbers, like a lottery draw.
Learn the concept
New to this topic? Read the lesson, then come back.