Editor

Python Program to Generate a Random Number

Beginner · Basics

Games, quizzes and simulations often need numbers picked by chance, and Python's random module provides them. This program shows the most useful ways: a random whole number in a range, a random decimal, and a random item from a list.

Program

random_number.py
import random
# A whole number from 1 to 100, both ends included
print("Random number from 1 to 100:", random.randint(1, 100))
# A decimal from 0.0 up to, but not including, 1.0
print("Random decimal:", random.random())
# A decimal in a range, rounded to 2 places
print("Random price:", round(random.uniform(10, 50), 2))
# An even number from 0 to 20, by stepping in 2s
print("Random even number:", random.randrange(0, 21, 2))
# A random item from a list
colours = ["red", "green", "blue", "yellow"]
print("Random colour:", random.choice(colours))
Output
Random number from 1 to 100: 4
Random decimal: 0.8090533853373294
Random price: 17.11
Random even number: 10
Random colour: red

How it works

  1. The output changes every time you run the program, because each number is picked at random.
  2. random.randint(a, b) returns a whole number from a to b, and unlike range(), both ends can come up.
  3. random.random() gives a decimal between 0 and 1, and random.uniform(a, b) gives a decimal between a and b.
  4. random.randrange(0, 21, 2) picks from 0, 2, 4 up to 20, following the same rules as range().
  5. random.choice() picks one item from a list.

Other ways to write it

The same numbers every time with seed()

The same numbers every time with seed()
import random
random.seed(42) # fix the starting point
print([random.randint(1, 6) for _ in range(5)])
random.seed(42) # same seed, so the same numbers again
print([random.randint(1, 6) for _ in range(5)])
Output
[6, 1, 1, 6, 3]
[6, 1, 1, 6, 3]

Random numbers on a computer come from a formula, and random.seed() sets its starting point, so the same seed always gives the same numbers, which helps when testing.

Random numbers without repeats

Random numbers without repeats
import random
lottery = random.sample(range(1, 50), 6)
print("Lottery numbers:", sorted(lottery))
Output
Lottery numbers: [7, 9, 15, 16, 35, 44]

random.sample() picks different items, so no number can come up twice, unlike calling randint() six times. The numbers change on every run.

Try it yourself

Generate 10 random numbers from 1 to 6 and count how many of them are sixes.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises