Random Module in Python Class 11-12 Notes
Random numbers are widely used in programs which involves games or simulations. Some uses of random numbers are as follows:
♦ To shuffle a deck of playing cards randomly
♦ To play a game of chances where the computer needs to throw some dice, pick a number randomly or flip a coin.
♦ Generation of captcha
♦ Random selection of winner in lucky draw contest.
How to use random module?
To use random module, firstly you should import random at the beginning of your code.
There are many functions such as random(), randrange(), randint(), shuffle(), uniform(), and choice() in random module. Here we learn the working of these functions.
1. random( )
This function generates random numbers between 0 and 1. It means the result will be between 0 or less than 1 (including 0, but excluding 1). It will never give 1 as output means output may be 0, 0.123,0.9999 etc. It will generate different number on each execution. This function can be used to generate pseudorandom floating point values.
import random random_number=random.random() print(random_number)
This function generate random integer numbers between ranges (lower and upper argument).
Ex 1: random_number=random.randrange(10)
The above code will generate random number between 0 to 9. (as we know indexing)
import random random_number=random.randrange(10) print(random_number)
Ex 2: random_number=random.randrange(10,21)
The above code will generate random number between 10 to 20. (as we know indexing)
import random random_number=random.randrange(10,21) print(random_number)
Ex 3: random_number=random.randrange(10,20,3)
The above code will generate random number between 10 to 19 with step 3. (as we know indexing)
3. randint ()
This function returns a random integer between a given start and stop integer.
Parameters: It takes two parameters. Both are mandatory.
start: It is the start position of a range. The default value is 0 if not specified.
stop: It is the end position of a range.
import random random_number=random.randint(10,20) print(random_number)
Returns a random floating point number between 2 numbers.
Here a is lower limit and b is the upper limit of the random float. The returned random float may be equal or greater than a and less than b.
import random random_number=random.uniform(10,20) print(random_number)
Used for making a random selection from a sequence (list,tuple,string)
import random my_choice=random.choice(["RED","YELLOW","GREEN", "BLUE"]) print(my_choice)
Used to shuffle the contents in a sequence (list).
import random color=["RED","YELLOW","GREEN", "BLUE"] random.shuffle(color) print(color)
['RED', 'GREEN', 'YELLOW', 'BLUE']
['GREEN', 'RED', 'YELLOW', 'BLUE']
['BLUE', 'YELLOW', 'RED', 'GREEN']