random() module in Python
In this tutorial, we are going to see how to use the random module in Python.
A random module is generally used to generate Pseudo-random numbers. The pseudo-random numbers are generated by some deterministic computation.
Table of contents
- random( )
- randint( )
- randrange( )
- choice( )
- shuffle( )
different random() function in Python
There are various functions are used to generate these random numbers. let’s see it one by one.
To use a random module from Python first we need to import it from the Python library.
This random.random( ) function is used to generate the float numbers between 0.0 to 1.0.
>>> import random >>> random.random() 0.930526309688996
The arguments are not needed in it.
This random.randint( ) function which returns the random value from the given range.
consider the below example,
>>> import random >>> random.randint(1,50) 20
here, inside the parameter we passed 1 as a start value and 50 as given as end value.so it will return a random number between the range 1 and 50.
Note: it will also return the start or end number also. ie.,1 or 50 as a random number.
This random.randrange( ) function will return a value that is given inside the range sequence.
>>> import random >>> random.randrange(1,20,2) 17
Inside the range function, we were given the start value is 1, the end value is 10 and the step value is given 2 so it will generate any random numbers between 1 and 20 inside with step value 2.
The random.choice( ) will return a random number from the given sequence of numbers.
>>> import random >>> random.choice((10,11,12,14,15,16)) 12
Here the sequence of numbers was given inside the choice. So, it will return a number from it.
The random.shuffle( ) will randomly shuffle the elements present inside the list.
>>> import random >>> value = [10,11,12,13,14,15] >>> random.shuffle(value) >>> value [13, 14, 15, 10, 12, 11]