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 from 1 to 100: 4 Random decimal: 0.8090533853373294 Random price: 17.11 Random even number: 10 Random colour: red
How it works
- The output changes every time you run the program, because each number is picked at random.
random.randint(a, b)returns a whole number fromatob, and unlikerange(), both ends can come up.random.random()gives a decimal between 0 and 1, andrandom.uniform(a, b)gives a decimal betweenaandb.random.randrange(0, 21, 2)picks from 0, 2, 4 up to 20, following the same rules asrange().random.choice()picks one item from a list.
Other ways to write it
The same numbers every time with seed()
[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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises