An Introduction to Random Number in Python

A random number in Python is any number between 0.0 to 1.0 generated with a pseudo-random number generator. It is possible to create integers, doubles, floats, and even longs using the pseudo-random generator in Python. Since it generates the numbers randomly, it is usually used in gaming and lottery applications. Another use of random numbers in Python is in Machine Learning, to create random weights for training the algorithms.

Python Random Module

Python provides the random module that allows one to work with random numbers. The module defines some methods that use the pseudo-random generator to generate random numbers in Python. Using these methods, you can perform various random number operations.

Methods in Random Module

To use random numbers in Python, you can use various methods declared in the random module. The table below describes all the methods along with their use.

Method

Description

seed()

Initializes the pseudo-random generator

getstate()

Returns an object that shows the internal state of the generator

setstate()

Restores the generator’s internal state

getrandbits()

Returns an integer with k random bits

randrange()

Returns a random integer from the specified range

randint()

Returns a random integer from the specified inclusive range

choice()

Selects and gives a random element from the non-empty list

choices()

Selects and returns a list of random elements from the non-empty list

shuffle()

Shuffles any given sequence in a random order

sample()

Returns specified numbers of lists from the given sequence

random()

Gives a random floating point number within 0.0 and 1.0

uniform()

Gives a random floating point number within an inclusive range

triangular()

Returns a random floating point number within the two specified parameters. It also allows you to set a midpoint parameter.

betavariate()

Gives a random floating point number from the beta distribution

expovariate()

Returns a random floating point number from the exponential distribution

gammavariate()

Returns a random floating point number from the gamma distribution

gauss()

Gives a random floating point number from a gaussian distribution

lognormvariate()

Gives a random floating point number from a log-normal distribution

normalvariate()

Returns a random floating point number from a normal distribution

vonmisesvariate()

Returns a random floating point number from von Mises distribution

paretovariate()

Gives a random floating point number from the Pareto distribution

weibullvariate()

Gives a random floating point number from the Weibull distribution

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

Performing Various Operations on Random Numbers in Python

Since you now know the methods that you can use with random numbers in Python, let’s use some of them.

Example: Using the Choice() Function

To get a random number in Python from a list, string, or tuple, you can use the choice() function. Look at the example below to get a random number from a list, and a random character from a string.

# importing random to use the generator

import random

# Defining a list

list_exm = [5, 7, 11, 22, 46, 84]

# Getting a random number

print(random.choice(list_exm))

# Initiating a string

str_exm = "Simplilearn"

# Printing a random character

print(random.choice(str_exm))

Output:

RandomNumberInPython_1.

Note: Your output may vary as the random number from the list and string is selected and printed.

Example: Generating Random Number in Python with the Randrange() Function

The Python randrange(beg, end, step) function is used to generate a random number between a given range. The first parameter defines the beginning, while the second parameter specifies the end of the range. The third parameter is a skip step. If you pass 2 as the third parameter, then the generator will skip 2 numbers and return the third. Use the following function to generate a random number in Python.

import random

print("Random number from range 15 to 85 is : ", end="")

# using the randrange() function

print(random.randrange(15, 85, 4))

Output:

RandomNumberInPython_2

Example: Using Randint() to Generate a Random Number in Python

The randint() function will generate a random number between the specified range. Let’s have a look at an example for the same.

import random

i = random.randint(20, 80)

print(i)

Output:

RandomNumberInPython_3

Example: Using Seed() and Random() to Generate and Save the State of Random Numbers in Python

The random() function is used to generate a number between 0.0 and 1.0. On the other hand, the Python seed() function is used to save the state, so that the random() function gives the same output on multiple executions. It seems fairly evident that it’s not that random, after all. Look at the following example to understand this better.

import random

# using random() function to generate a number

print("The random number is : ", end="")

print(random.random())

# using seed() function to save the state

random.seed(3)

# printing the seeded random number

print("The seeded number with 3 is : ", end="")

print(random.random())

# using seed() function again

random.seed(9)

# printing seeded random number

print("The mapped random number with 9 is : ", end="")

print(random.random())

# using the same seeds to print same numbers

random.seed(3)

print("The mapped random number with 3 is : ", end="")

print(random.random())

random.seed(9)

print("The mapped random number with 9 is : ", end="")

print(random.random())

Output:

RandomNumberInPython_4

As you can see in the output, the first number generation with a seed was random. But, when you use the same seed, the same number is printed.

FREE Data Science With Python Course

Start Learning Data Science with Python for FREEStart Learning
FREE Data Science With Python Course

Example: The Python Shuffle() Function to Shuffle a Sequence

The shuffle() function is used to shuffle a sequence randomly in this example, which is a list. The process of how it mixes with the list is depicted in the example below.

import random

example_list = [1, 3, 5, 7, 9, 11]

print("Original list : ")

print(example_list)

# Shuffling

random.shuffle(example_list)

print("\nAfter the shuffle : ")

print(example_list)

# Shuffling again

random.shuffle(example_list)

print("\nAfter the shuffle : ")

print(example_list)

Output:

RandomNumberInPython_5

Example: Using the Uniform() Function to Generate a Random Number in Python

The Python uniform() function takes two parameters: the lower limit and the upper limit, and returns a random number between the range. The lower limit is inclusive, but the upper limit is exclusive.

import random

# Using uniform() function

print("The random floating point number is : ", end="")

print(random.uniform(3, 7))

print("The random floating point number is : ", end="")

print(random.uniform(17, 23))

Output:

RandomNumberInPython_6

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Summing It Up

In this article, you have looked into everything you need to about random numbers in Python. You also went through the random module and different methods defined in it. This article showed the use of some of the methods, but if you want, you can try all the methods one-by-one to see how it works. 

The more you code, the more you learn. If you are new to Python and want to learn more about these basic concepts, Simplilearn’s Python Tutorial for Beginners is the right learning resource for you. If you’re looking to go pro, after clearing the basic concepts, you can opt for our Online Python Certification Course. If you are passionate about data science, you can also opt for our Data Science with Python Certification Course. This course is adept at helping you learn data analysis, machine learning, natural language processing, and more.

Have any questions for us? Leave it in the comments section of this article, and our experts will get back to you on the same, ASAP!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.