ByteBoard Notes Notes

Generate random numbers and find their mean, median and mode

Computer Science XI · Experiment 27 of 27 · Python

11-CSPython programs
Expt. No.27
Page No.54

random and statistics modules

Aim

To write a Python program that generates 10 random integers between 1 and 100 and displays their mean, median and mode using the statistics module.

Concepts used

Algorithm

  1. Import the random and statistics modules.
  2. Generate 10 numbers with random.randint(1, 100) and store them in a list.
  3. Display the list.
  4. Display the mean, median and mode.

Program

# Random numbers with their mean, median and mode import randomimport statistics nums = []for i in range(10):    nums.append(random.randint(1, 100))print("Random numbers:", nums)print("Mean   :", statistics.mean(nums))print("Median :", statistics.median(nums))print("Mode   :", statistics.mode(nums))

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python random_statistics.py
Random numbers: [32, 51, 10, 66, 2, 64, 26, 12, 24, 48] Mean : 33.5 Median : 29.0 Mode : 32

✓ Printed by running this program, not typed by hand.

Result

The program printed 10 random numbers and their mean, median and mode. Every run gives different numbers; when no value repeats, mode() returns the first number in the list.

Viva voce: what the examiner may ask

01What range of values can random.randint(1, 100) give?

Any whole number from 1 to 100, both ends included.

02How is randrange(1, 100) different?

The stop value 100 is not included, so it gives 1 to 99.

03How is the median found for 10 numbers?

The numbers are sorted and the mean of the two middle values (5th and 6th) is taken.

04What does random.random() return?

A float from 0.0 up to, but not including, 1.0.

Variations for the lab test

  1. Simulate 20 throws of a dice and count how many sixes appear.
  2. Generate a random 4-digit OTP.
  3. Pick a random name from a list of names.
! Common mistake Expecting the same output every time: random numbers change on each run, so your output will not match the one shown here.
Back to the 11-CS index