Register Login

Generate Random Number in Python

Updated Jan 31, 2022

In programming, random numbers play a significant role in various applications right from developing lottery games to cybersecurity to password guessing applications and statistical analysis. Due to the various roles of random numbers, there are various techniques & types random numbers are categorized into.

Like other programming languages, Python also supports generating random numbers. In this article, you will learn about random numbers and how to implement them in Python programs through various libraries.

What are random numbers?

Random numbers are arbitrary numbers that appear in a series with conditions such that:

  • The values are not uniformly distributed and appear haphazardly.
  • It should be impossible to forecast the next or future values based on past or present values.

Various applications of random numbers are in data science, cybersecurity, statistical analysis, and probability theory. The task of rendering random digits from any set of numbers should not be trivial. Random numbers are of two types:

  • True random numbers: Also known as hardware random numbers. To make a number truly random, the computer has to use some external physical variable that is unpredictable. Examples of such unpredictable variables are human actions, radioactive decay of isotopes, airwave static, rather than generating the entire code through an algorithm. Even at the quantum level, subatomic particles generate complete random behavior. It makes them the ideal variable require to generate an unpredictable TRNS (true random number system).
  • Pseudo Random Number Generator (PRNG): These are program or software-generated random numbers, and hence the name pseudo. They are not purely random because the computer uses a specific set of code or algorithms depending on a distribution mechanism. They are not entirely secure (when used in any cryptographic algorithm) because they rely upon a certain input and are predictable. Also, they have a deterministic output. Since programmers can set a seed number to replicate the “random” numbers generated, it is achievable to anticipate or foresee the numbers if the seed is known. APplications of pseudorandom number generation are in various tools like Python Interpreter, MS. Excel, cryptographic algorithms used for day-to-day data encryption. A common example use of PRNGs is in keystream generation.

In python, programmers use the random library to generate random numbers. Apart from that, we will also discuss numpy’s random() for generating random numbers in this chapter.

Python’s Random module:

Python comes with a built-in module through which programmers can generate or make random numbers. It supports a large collection of built-in methods.

Method Description
seed() This method helps in initializing the random number generator
getstate() This method helps in returning the present internal state of your random number generator
setstate() This method helps in restoring your random number generator’s internal state
getrandbits() This method helps in returning a number representing the random bits
randrange() This method helps in returning a random number between any given range
randint() This method helps in returning a random integer number within that given range
choice() This method helps in returning a random element from the given sequence
choices() This method helps in returning a list picking a random selection within that given sequence
shuffle() This method helps in taking a sequence & returning the sequence in a random order
sample() This method helps in returning a given sample of a sequence
random() This method helps in returning a random float number within the range 0 and 1
uniform() This method helps in returning a random float number between 2 given parameters
triangular() This method helps in returning a random floating point number between 2 given parameters. Here programmers can also set a mode parameter specifying the midpoint
betavariate() This method helps in returning a random floating point number within the range 0 - 1 based on the concept of Beta distribution
expovariate() This method helps in returning a random floating point number depending on the Exponential distribution
gammavariate() This method helps in eturning a random floating number depending on the concept of Gamma distribution
gauss() This method helps in returning a random floating number depending on the concept of Gaussian distribution
lognormvariate() This method helps in returning a random floating point number depending on a log-normal distribution
normalvariate() This method helps in returning a random floating number depending on the normal distribution
vonmisesvariate() This method helps in returning a random float number depending on the von Mises’s distribution concept
paretovariate() This method helps in returning a random float number depending on the Pareto distribution concept
weibullvariate() This method helps in returning a random float number depending on the Weibull’s distribution concept

Let us now take a look at some of them and how to implement them.

Program:

import random
# printing a random number from the given tuple
tup1 = (1, 2, 3, 4, 5, 6)
print(random.choice(tup1))
# printing a random letter from the given string
strg = "KarlosRay"
print(random.choice(strg))

Output:

Explanation:

Here, first, we will import the random. Then we will assign a tuple with the values 1 to 6. Then, we will use the print() and use the random.choice() and pass the tuple variable within it that will choose one of the elements from that tuple.

This is the use of random.choice(). The same thing has been done using the string in the next statement and this time the random.choice() randomly picked out a character from the string.

Randonrange() Program:

import random
print("Grabbing a random number from within a range : ", end = "")
print(random.randrange(10, 30, 3))

Output:

Explanation:

Here, first we will import the random. Then we use the print() to display a message and another print() to generate the random.randrange().

Generating list of Random numbers using Loop:

We can leverage the randint() method using for loop for generating a list of random integer numbers.

import random
randlist = []
for g in range(0, 5):
    numb = random.randint(2, 25)
    randlist.append(numb)
    print(randlist)

Output:

Explanation:

Here, first, we will import the random. Then we will use a list randlist that will hold all the different numbers that will get appended within the list. Next, we will use the range-based for loop that will iterate 5 times (0 to 4) and within it we will create random integers.

All the random integers will get stored in the numb variable. Then weave used the randlist.append() to append the values one by one from the numb. Finally, we use print() to display the list elements present within the randlist.

How to use random.sample():

This method helps in returning a given sample of a sequence. Here the function will take a sample range (lower and upper) along with the number of random items the function will generate for the random numbers.

import random
#Generate 6 different random numbers in between the range 12 and 40
randlist = random.sample(range(12,  40), 6)
print(randlist)

Output:

Explanation:

Here, first, we will import the random. Then we will use a variable randlist that will hold all the different numbers generated by the random.sample(). Inside the random.sample()  we will use a nested function popular and default range() that will generate random numbers from the range of numbers and the other parameter (here 6) defines the number of random numbers the function will generate.

Note that the ultimate output is a list. Finally we use the print() function to display all the random numbers created within the randlist.

Conclusion:

Random module in Python plays a significant role in different applications and security products. Various hashing and cryptographic, lottery and bricks game use this module and random number concept to make the application more autonomous.

Random number concept has also gain popularity in developing CAPTCHA and reCAPTCHA development. So, Python developers need to have a very clear idea of the most popular methods used within this module.


×