Account
Categories

Random Module


Definition:

If you want to generate a random number within a range or select a random item, you can use the random module.

Now you will clearly understand the code logic with the help of the flowchart.

Random Module Flowchart :

Start
↓
You write program and import random module
import random
↓
Python loads random module
↓
random module generates random values
↓
You ask for random number
random.randint(1, 15)
↓
Module selects a random number between 1 to 15
↓
Result comes →  7
↓
You ask for random item
random.choice([1, 2, 3])
↓
Module selects one item randomly from list
↓
Result comes →  2
↓
Print outputs
7
2
↓
End

Syntax:


import random

Example:


import random

print(random.randint(1, 15))
print(random.choice([1, 2, 3]))

Output:

Exercise

Use random module to generate a random number between 1 to 10 and select a random item from a list.