Python Practice › Basic Programs › Program 31

Generate random numbers

EasyBasic Programs · 31 of 40

Write a Python program to generate random numbers.

Advertisement
Output
74
[1, 4, 4, 5, 1]
1.706
[32, 18, 42, 11, 3, 34]

Approach

  1. Use the random module: randint for whole numbers, random and uniform for decimals.
  2. Seed the generator to make the output repeatable.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs