RANDOM MODULE
Python has a built-in module that you can use to make random numbers. Random can be used to at many places where random action is required such as to get a random number, generating a random password, selecting a random elements from a list, shuffle the turns or elements randomly, deciding the elements to appear randomly etc.
To use it first, import the module by writing down
>>> import random
Few commonly used functions in random module are as follows:
-
random() : Returns a random float number between 0 and 1
-
randrange() :Returns a random number between the given range
-
randint() : Returns a random number between the given range
-
seed(): Initialize the random number generator
Let us understand the concept by studying few examples
Example 1: To display 2 random numbers using random(), will print numbers between 0 and 1.
Code
Output
Example 2: To display a random number between user defined range.
Code
Output
Example 3: To rearrange the elements stored in a list using random.shuffle()
Code
Output
Example 4: To pick a random number from the list using random.choice()
Code
Output
Try It Yourself
Problem Statement 1 - Generate 5 random numbers between 1 and 10.
Problem Statement 2 - Take two list, one to store week days Mon to Fri and second to store 5 fruits. Assign a random fruit to each day from Mon to Fri.
Example:
days=['Mon', 'Tue', 'Wed', 'Thurs', 'Fri']
color=['Apple', 'Guava', 'Grapes', 'Banana', 'Mango']
Expected Output:
Mon = Apple
Tue = Guava
Wed = Banana
Thurs = Grapes
Fri = Grapes