Hello guys, what’s up? Welcome to our Programiz tutorial in python programming language. Today I am going to teach you about how to generate random numbers in pythonprogramming language. Just like other object oriented programming (OOP) language, we can generate random numbers in python programming language. Generating random number in python is a basic program for python programmer. If you don’t know how to generate random numbers in python, you cannot claim yourself as a python programmer. In machine learning algorithm randomness is an important part of the configuration & evaluation. In machine learning we need to
 Split data into random train and test sets
 Random shuffling of a training dataset in stochastic gradient descent
 Random initialization of weights in an artificial neural network
Today we will show you various ways of generating a random number in Python programming language. In this tutorial in python programming language, we will cover the following topics
 Generate random numbers of integer and floats number.
 Select an item randomly from a List
 Generating a random number with the specific length
 Generate a random number which is multiple of n
 Generating a random number in python, which are cryptographically secure by using secrets module. We can also learn how to securely generate random numbers in python programming language, security keys, and URL
 Get and Set the state in python programming language
 ndimensional array random number generation
 Generate random numbers from a list or string
 Generate random numbers by Sampling & choose elements from population.
 Shuffle the sequence of data.
 Generate random strings and password.
 Generate random arrays, we will use use numpy.random module
 Generate random unique IDs, we will use UUID module

Some python module function And many more things
Random module in Python programming language
By using random module, we can generate random numbers in python programming language. To do this we need to import random module. Let’s see it in code: —
import random print("Printing random number using random.random()") print(random.random())
Output:
Printing random number using random.random() 0.5015127958234789
Function random() is used for generating a random number between 0 and 1 [0, 0.1 .. 1].
Generate Random Numbers by using randrang() function
from random import randint print("Printing random integer ", randint(0, 9)) print("Printing random integer ", randrange(0, 10, 2))
Output:
Printing random integer 2 Printing random integer 6
Randomly select an item from a List
Assume, we have the following cities list. And we want to retrieve an item randomly from the list. Let’s see how we can do this: —
import random city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'] print("Select random element from list  ", random.choice(city_list))
Output:
Select random element from the list  Chicago
import random for x in range(10): print random.randint(1,101)
x in range(10), determines how many random values we want to print. If we want to print 20 numbers, we can set just simply 20 in 2^{nd} line. random.randint(1,101) will select random integer values in between 1 and 100. So, we can say that, above code will print 10 random values of numbers between 1 and 100.
random.randrange() function in python programming language
In python programming language random.randrange() function is used for generating random number in a given range. For example, if we want to generate random numbers in between 20 to 60, then we can use this function.
How to use random.randrange()
Syntax:
random.randrange(start, stop[, step])
Above we can see that random.randrange() function takes 3 parameters. But, here two parameters (start and step) are optional
 randrange(): is exclusive function. For example, randrange (10,20,1). It will never select 20. It will only return random number from 10 to 19
 Start: starting number in a range. We can say it, lower limit. If we will not specified, by default it assume starts is 0
 Stop: last number in a range. We can also say it, upper limit.
 Step:difference between each number. It is optional parameters. If we will not specified, by default it assume step value is 0
 We can only use integer value parameters in random.randrange() function. Otherwise it will throw an ValueError.
 If stop <= start or step =0, it will also throw an ValueError.
Example:
By using random.randrange() function we can print a random number in a given range.
import random print("Generate random integer number within a given range in Python ") #random.randrange() with only one argument print("Random number between 0 and 10 : ", random.randrange(10)) #random.randrange() with two arguments print("Random number between 20 and 40 : ", random.randrange(20, 40)) #random.randrange() with three argument print("Random number between 0 and 60 : ", random.randrange(0, 60, 6))
Output:
Generate random integer number within a given range in Python Random number between 0 and 10 : 7 Random number between 20 and 40 : 32 Random number between 0 and 60 : 48
Generate the random number with the specific length
What if, if you need to generate a random number of length n. For example, if we want to generate random number which length are 4. We can generate a random number of certain length by using function random.randrange(). Let’s see some example: —
import random number = random.randrange(1000, 9999) print("First random number of length 4 is ", number) number = random.randrange(1000, 9999) print("Second random number of length 4 is ", number)
Output:
First random number of length 4 is 1931 Second random number of length 4 is 5715
Generate a random number of multiple of n
What if, if you need to print random integer values & those are in between 1 and 100 but values are multiple of 5? You have to use a little more arithmetic so that the random integer is in fact a multiple of five, then everything are same as before we have learned. Let’s check this in our below code:—
import random number = random.randrange(10, 100, 10) print("using randrange First random number multiple of 10 is ", number) number = random.randrange(10, 100, 10) print("Using randrange Second First random number multiple of 10 is ", number)
When above code will execute, our output looks like below−
using randrange First random number multiple of 10 is 70 Using randrange Second First random number multiple of 10 is 30
import random print(random.sample(range(1, 101), 10))
After executing the above code our output will be shown as a list:
[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]
from random import * print(uniform(1, 10))
random.uniform(start, end) in python programming language
 To generate a floating point number within a given range, we can use random.uniform()function.
 For example, we want to generate random float number in between 10.5 to 25.5. In the result we can get output which is less than 25.5. We never get 25.5.
Example: –
import random print("floating point within given range") print(random.uniform(10.5, 25.5))
Output:
floating point within given range 16.76682097326141
random.triangular(low, high, mode) in python programming
To use 3 number in a simulation for generating a random number in python programming language, we can use random.triangular() function. In this function by default lower limit/low is zero and the upper limit/high value is 1. This function return a random float value (n), where low <= n <= high and the mode is between those bounds.
Example:
import random print("floating point triangular") print(random.triangular(10.5, 25.5, 5.5))
Output:
floating point triangular
16.114862085401924
Cryptographically secure random generator in Python
If we want to generate cryptographically secure random number in python programming language we need to use a function. Do to this we have to use random.SystemRandom().random() instead of random. random(). If we generate random number by random.SystemRandom().random() function, then our output will be secure.
To secure the random generator in Python programming language, we have to use the following approaches.
 To secure random data need to import secrets module
 Have to use random.SystemRandom class
Example:
import random import secrets number = random.SystemRandom().random() print("secure number is ", number) print("Secure byte token", secrets.token_bytes(16))
Output:
secure number is 0.11139538267693572 Secure byte token b'xaexa0x91*.xb6xa1x05=xf7+>r;Yxc3'
Get and Set the state of python random Generator
In python programming language, it has two 2 functions. Those are random.getstate() and random.setstate(state). This 2 function help us to capture the current internal state of the random numbers. We can generate sequence of data by using this module. In random.setstate(state), you cannot change the sate value, if you want to get previous state. Because by changing the state value, you are altering the state.
To have a clear understanding let’s see an example: —
import random number_list = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] print("First Sample is ", random.sample(number_list,k=5)) state = random.getstate() # store this current state in state object print("Second Sample is ", random.sample(number_list,k=5)) random.setstate(state) # restore state now using setstate print("Third Sample is ", random.sample(number_list,k=5)) #Now it will print the same #second sample list random.setstate(state) # restore state now print("Fourth Sample is ", random.sample(number_list,k=5)) #again it will print the #same second sample list again
Output:
First Sample is [18, 15, 30, 9, 6] Second Sample is [27, 15, 12, 9, 6] Third Sample is [27, 15, 12, 9, 6] Fourth Sample is [27, 15, 12, 9, 6]
Look at above code. By setting the random generator, we are getting same sample list
Generate a random ndimensional array of float numbers
Whenever we want to generate an array of random numbers in numpy python programming language, we need to use numpy.random package._{}^{}
 numpy.random.rand():generate ndimensional array of random floating point numbers in the range of [0.0, 1.0)
 numpy.random.uniform: generate ndimensional array of random floating point numbers in the range of [low, high)
import numpy random_float_array = numpy.random.rand(2, 2) print("2 X 2 random float array in [0.0, 1.0] n", random_float_array,"n") random_float_array = numpy.random.uniform(25.5, 99.5, size=(3, 2)) print("3 X 2 random float array in range [25.5, 99.5] n", random_float_array,"n")
Output:
random float array in [0.0, 1.0] [[0.99158699 0.02109459] [0.41824566 0.66862725]] random float array in [25.5, 99.5] [[93.061888 86.81456246] [76.19239634 50.39694693] [82.25922559 78.63936106]]
Generate random numbers of multidimensional array of integers numbers
In python programming language, Nuumpy module has a numpy.random package, which can generate random numbers array. To generate random multidimensional array, we need to use the following Numpy methods.
 randint() // generate integer random number
 random_integers()// generate integer random number
 np.randint(low[, high, size, dtype]) // generate random integers array from low (inclusive) to high (exclusive).
 np.random_integers(low[, high, size]) // generate Random integers array of type numpy int between low and high, inclusive.
Now, let see the examples.
Generate multidimensional array integers:
Following code generate 4 x 4 dimensional arrays of integers in between 10 and 50, where 10 & 50 are exclusive
import numpy print("4 x 4 array of ints between 10 and 20 inclusive") newArray = numpy.random.randint(10, 50, size=(4, 4)) print(newArray)
Output:
[[10 48 30 24] [13 46 30 11] [12 28 49 26] [30 18 49 35]]
Generate a 5 x 3 array of ints between 60 and 100, inclusive:
Following code generate 5 x 3 dimensional arrays of ints in between 60 and 100, where 60 and 100 are inclusive
import numpy print("3 x 5 array of ints between 10 and 20 exclusive") newArray = numpy.random.random_integers(60, 100, size=(3, 5)) print(newArray)
Output:
[[63 76 95 93 75] [71 84 63 99 93] [65 64 66 69 92]]
Generate random number from a list or string
random.choice()
To pick a random element from the sequence, we can use random.choice(seq)method. random.choice(seq) returns a single item/number from the list or string.
Example:
list = [55, 66, 77, 88, 99] print("random.choice to select a random element from a list  ", random.choice(list))
Output:
random.choice to select a random element from a list 77
When we have to randomly choose more than one element from the sequence, there we can use random.choices(population, weights=None, *, cum_weights=None, k=1) method
Example: –
import random #sampling with replacement list = [20, 30, 40, 50 ,60, 70, 80, 90] sampling = random.choices(list, k=5) print("sampling with choices method ", sampling)
Output:
sampling with choices method [90, 50, 40, 60, 40]
random.sample()
Example: –
import random list = [2,5,8,9,12] print ("random.sample() ",random.sample(list,3))
Output:
random.sample() [2, 9, 5]
random.shuffle(x[, random])
If we want to shuffle or randomize a list or string sequence, there we can use random.shuffle() function. Shuffle card game is a common example of this.
Example:
list = [2,5,8,9,12] random.shuffle(list) print ("Printing shuffled list ", list)
Output:
Printing shuffled list [5, 9, 12, 2, 8]
Generate random number from an array
Example:
import numpy array =[10, 20, 30, 40, 50, 20, 40] single_random_choice = numpy.random.choice(array, size=1) print("single random choice from 1D array", single_random_choice) multiple_random_choice = numpy.random.choice(array, size=3, replace=False) print("multiple random choice from 1D array without replacement ", multiple_random_choice) multiple_random_choice = numpy.random.choice(array, size=3, replace=True) print("multiple random choice from 1D array with replacement ", multiple_random_choice)
Output:
single random choice from 1D array [10] multiple random choices from the 1D array without replacement [20 20 10] multiple random choices from the 1D array with replacement [10 50 50]
Generate random UUIDs
UUID means Universally Unique IDentifier. In python programming language, it provides immutable UUID objects. To do this we have to use uuid.uuid4() function. This function can generate 128 bit long random unique ID. UUIDs object is cryptographically safe.
Example:
import uuid # get a random UUID safeId = uuid.uuid4() print("safe unique id is ", safeId)
Output:
safe unique id is UUID('78mo45068btg345b52kn8c7fraga847da')
Generating random number for a Dice Game
I have created a simple dice game to understand random module functions. In this game, we have two players and two dice. To understand random numbers in python, below I will show you a dice game example.
Rules of the dice game:
 Each player shuffle both the dice and play one by one.
 Sum the two dice number and adds it to each player’s scoreboard.
 The Player will be the winner, who scores high number
import random PlayerOne = "Eric" PlayerTwo = "Kelly" EricScore = 0 KellyScore = 0 # each dice contains six numbers diceOne = [1, 2, 3, 4, 5, 6] diceTwo = [1, 2, 3, 4, 5, 6] def playDiceGame(): """#Both Eric and Kelly will roll both the dices using shuffle method""" for i in range(5): #shuffle both the dice 5 times random.shuffle(diceOne) random.shuffle(diceTwo) firstNumber = random.choice(diceOne) # use choice method to pick one number randomly SecondNumber = random.choice(diceTwo) return firstNumber + SecondNumber print("Dice game using a random modulen") #Let's play Dice game three times for i in range(3): # let's do toss to determine who has the right to play first EricTossNumber = random.randint(1, 100) # generate random number from 1 to 100. #including 100 KellyTossNumber = random.randrange(1, 101, 1) # generate random number from 1 to #100. dosen't including 101 if( EricTossNumber > KellyTossNumber): print("Eric won the toss") EricScore = playDiceGame() KellyScore = playDiceGame() else: print("Kelly won the toss") KellyScore = playDiceGame() EricScore = playDiceGame() if(EricScore > KellyScore): print ("Eric is winner of dice game. Eric's Score is:", EricScore, "Kelly's score is:", KellyScore, "n") else: print("Kelly is winner of dice game. Kelly's Score is:", KellyScore, "Eric's score is:", EricScore, "n")
Output:
Dice game using a random module Kelly won the toss Eric is the winner of a dice game. Eric's Score is: 9 Kelly's score is: 6 Kelly won the toss Eric is the winner of a dice game. Eric's Score is: 11 Kelly's score is: 9 Eric won the toss Kelly is the winner of a dice game. Kelly's Score is: 12 Eric's score is: 5
Today we have learned many things about python programming language. I hope you guys have understood everything which I have discussed earlier. . So, guys, that’s about how to generate random numbers in python programming language. Later I will discuss another tutorial on python programming language. Till then, take care. Happy Coding