[go: up one dir, main page]

0% found this document useful (0 votes)
3 views12 pages

How to Generate Random Numbers in Python

The document provides a comprehensive guide on generating random numbers in Python using the random library. It covers various methods such as generating random integers and floating-point numbers, creating lists of random numbers, and selecting random elements from a list. Additionally, it includes code examples for each method to illustrate their usage.

Uploaded by

shailenderojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

How to Generate Random Numbers in Python

The document provides a comprehensive guide on generating random numbers in Python using the random library. It covers various methods such as generating random integers and floating-point numbers, creating lists of random numbers, and selecting random elements from a list. Additionally, it includes code examples for each method to illustrate their usage.

Uploaded by

shailenderojha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

How to Generate Random Numbers in Python?

Shiksha Online
Updated on Jan 22, 2024 11:43 IST
In Data Science or Statistics, there are various instances where a programmer might
need to work with random inputs. Python offers many predefined functions to
generate and use random data.

In this article, we will guide you on how to generate random numbers of int and float
types using Python. We will particularly focus on the random library in Python. So,
without further ado, let’s get started!

We will be covering the following sections today:


Methods to Generate Random Numbers in Python

Generating a f loating random number between 0 and 1 – random()

Generating a random integer within a given range – randint()

Generating a random integer list using f or loop – randint()

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Generating a sample of random integers within a given range – sample()

Selecting a random number f rom a given list – choice()

Generating a random number f rom a list in the specif ied range – randrange()

Generating a f loating random number within a given range – unif orm()

Generating a randomly shuf f led list – shuf f le()

Generating a f loating random number sequence – seed()

Methods to Generate Random Numbers in Python

The random module in Python contains pseudo-random number generators for


various distributions:

Let’s see how each of the above methods works to generate random numbers:

Generating a f loating random number between 0 and 1 – random()

One method is to use the random() function from the random module that
generates a random float value in the range [0.0, 1.0], as shown:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

n = random.random()
print (n)

Output:

From nerd to expert ninja! Unlock Python on a deeper level and explore the best Python
programmes f rom top colleges and online Python courses with our detailed guide.

What have we done here?

We f irst import the random module of Python.

T hen, we call the random() method to get a random f loat between 0-1 and store it in the
variable n.

Print the randomly generated number.

Generating a random integer within a given range – randint()

The random module also provides a randint() method to generate an integer


number within a specified range. Let’s understand how to generate random number
in Python with Range.

The function takes two numbers as arguments, [min, max] – defining the lower and
upper limit of the range. Let’s look at the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

n = random.randint (40,100)
print (n)

Output:

63

What have we done here?

Firstly, import the random module of Python.

T hen, we call the randint(min, max) method to get a random integer within the given range
and store it in the variable n.

Print the randomly generated number.

Generating a random integer list using f or loop – randint()

We can also use the randint() method of the random module to generate a list of
integer numbers. For this, we use a for loop that iterates over a specified range.

Let’s look at the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

rand_list = []
f or i in range(0,5):
n = random.randint (100,200)
rand_list .append(n)
print (rand_list )

Output:

[199, 107, 199, 103, 112]

What have we done here?

Import the random module of Python.

Declare an empty Python list variable rand_list.

T hen, use a f or loop to iterate over a range that will determine the number of elements in
the list.

Once the loop has completed its execution, print the randomly generated number list.

Generating a sample of random integers within a given range –


sample()

The random module also provides a sample() method to generate a sampled list
of random numbers within a specified range.

Let’s understand through the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

n = random.sample(range(50,100), 10)
print (n)

Output:

[58, 56, 64, 54, 84, 50, 80, 89, 87, 55]

What have we done here?

Import the random module of Python.

T hen, we simply call the sample() f unction that takes range(min, max) as one argument
and the number of elements in the list as the other argument, which is 10 in this case.

Finally, we print the sample of 10 randomly generated numbers between 50-100.

Selecting a random number f rom a given list – choice()

The random module provides another in-built method called choice() that returns a
random element from a list, tuple, or string.

Let’s look at the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

mylist = [1, 3, 5, 7, 9]

#Print a random number from the list


n = random.choice(mylist )
print (n)

Output:

What have we done here?

Import the random module of Python.

Declare a variable mylist and initialize it with the given elements: [1, 3, 5, 7, 9]

T hen, we call the choice() f unction that takes the list variable as an argument and
generates a random element f rom the specif ied list.

Generating a random number f rom a list in the specif ied range –


randrange()

This random module method, called the randrange() function, generates a random
number from a list obtained by start-stop skipping within a specified range.

The function takes three arguments, [start(optional), stop, step(optional)] – defining


the start and stop of the range. There is also a step parameter that determines the
step point of the range.

Let’s understand through the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

n = random.randrange(20, 50, 4)
print (n)

Output:

44

What have we done here?

Import the random module of Python.

T hen, we call the randrange() f unction, which takes the start=20, stop=50, and step=4 as
parameters in this case.

T he f unction generates a random element f rom the list [24,28,32,36,40,44,48] that is


obtained f rom the specif ied range.

Generating a f loating random number within a given range –


unif orm()

The random module also provides a unif orm() method to generate a random
floating-point value within a specified range.

The function takes two numbers as arguments, [x,y] – defining the lower and upper
limit of the range. Let’s look at the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

n = random.unif orm(13,17)
print (n)

Output:

14.821073447519757

What have we done here?

Import the random module of Python.

T hen, call the unif orm(x,y) f unction to get a random f loat value within the given range and
store it in the variable n.

Print the randomly generated number.

Generating a randomly shuf f led list – shuf f le()

The random module has a shuf f le() function that takes a Python list as an
argument and shuffles the elements of the list in place to return None.

Let’s understand through the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

mylist = [1, 2, 3, 4, 5, 6, 7]

#Print a random list


random.shuf f le(mylist )
print (mylist )

Output:

[3, 4, 5, 2, 1, 6, 7]

What have we done here?

Import the random module of Python.

Declare a variable mylist and initialize it with the given elements: [1,2,3,4,5,6,7]

T hen, we call the shuf f le() f unction that takes the list variable as an argument and
generates a shuf f led list with the same elements.

Print the list.

Generating a f loating random number sequence – seed()

Lastly, the random module has a seed() function that can be used when you need
to generate a sequence of random floating-point values.

This function takes the seed value as an argument, initialising the pseudo-random
number generator. Let’s understand through the following example:

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
Copy code

#Import the random library


import random

#Specify seed
val = int (input ("Ent er seed value : "))

random.seed(val)
f or i in range(val):
print (random.random(), end = ' ')

Output:

What have we done here?

Import the random module of Python.

T ake an integer input f rom the user as the seed value and store it in the variable val.

T hen, call the seed() f unction with the input seed value as the argument.

Inside the f unction body, run a f or loop, iterating it over the range of the seed value.

Use the random() f unction to generate f loating random numbers as specif ied by the seed
value. For instance, in the above case, the given seed is 3, so a sequence of three
f loating-point values is printed.

Endnotes

This article discussed the most common methods in Python’s random module that
can generate pseudo-random numbers. We learned how to generate random
integers as well as random floating-point values. We also learned how to select

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.
random elements from a Python list. You can explore related articles here if you’d
like to learn more about Python and practice Python programming.

FAQs on How to Generate Random Numbers in Python

How do I generate a random integer within a specif ic range in Python?

Can I generate a random number that excludes the upper limit?

How to generate random f loating-point numbers?

Is there a way to choose a random element f rom a list?

How can I generate a list of unique random numbers?

What f unction should I use f or cryptographic purposes or secure random number


generation?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 23-Jan-20 24.

You might also like