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

Python Random Module

The Python Random Module is a built-in module that generates pseudo-random numbers and supports various functions for generating random floats, integers, and selecting random elements from sequences. It includes functions like seed(), randint(), choice(), and shuffle(), which are commonly used in applications such as games and simulations. The document also briefly introduces the NumPy library, highlighting its capabilities for creating and manipulating multi-dimensional arrays, which are essential for scientific computing and data analysis.

Uploaded by

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

Python Random Module

The Python Random Module is a built-in module that generates pseudo-random numbers and supports various functions for generating random floats, integers, and selecting random elements from sequences. It includes functions like seed(), randint(), choice(), and shuffle(), which are commonly used in applications such as games and simulations. The document also briefly introduces the NumPy library, highlighting its capabilities for creating and manipulating multi-dimensional arrays, which are essential for scientific computing and data analysis.

Uploaded by

devy6441
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Random Module

In Python, the Random Module is a built-in module that enables us to


generate random numbers. The Random Module generates Pseudo-random
numbers, which means that those numbers are technically not random.
Random objects like numbers, strings or a list can be generated by the
Random Module in Python.

What is the Seed value in the Python Random


Module?
The Seed value is a number in the Random Module that generates a fixed
set of Random numbers. Quite ironic and confusing, right?

Where it is used : Games (dice, cards), OTP generation, data shuffling, simulations.

What is advantage: different result received every time —not


predictable

Example: PUBG, Ludo, cards shuffle — sab me random hi use


hota hai

import random

# Dice roll

dice = [Link](1, 16)

print("🎲 Dice Result:", dice)

Program 2: Random Password Generator


import random
import string

# Characters to choose from


characters = string.ascii_letters + [Link] +
[Link]

password = ''.join([Link](characters) for i in


range(8))

print("🔐 Random Password:", password)

This built-in Python module provides functions for generating pseudo-random

numbers. It supports various distributions and includes functions for:

 Generating random floats (random(), uniform(), triangular()).

 Generating random integers (randint(), randrange()).

 Selecting random elements from sequences (choice(), sample(), choices()).

 Shuffling sequences (shuffle()).

 Setting and getting the state of the random number generator


(seed(), getstate(), setstate()).
 =====================

Functions in the Python Random Module


There are various types of functions available in the Python Random
Module. Let's have a look at them:

S No. Functions Description

1) seed() It generates a fixed


set of random
numbers

2) getstate() It gives the current


internal state of the
random number
generator.

3) getrandbits() Generates random


number bits

4) randrange() Generates random


numbers within a
specified range

5) randint() It also generates


random numbers
within a given range.

6) setstate() It restores the internal


state of the random
number generator.

7) choice() It gives a random


number from a
sequence.

8) choices() It gives multiple


numbers from a
sequence

9) shuffle() This function shuffles


the items in a
sequence

10) sample() This function returns a


given sample of a
sequence

11) random() This function returns a


random float number
between 0 and 1

12) uniform() Returns a random float


number between two
given parameters

13) triangular() Returns a random float


number between two
given parameters. You
can also set a mode
parameter to specify
the midpoint between
the two other
parameters.

14) betavariate() It gives a random float


number between 0
and 1 on the basis of
the Beta distribution.

15) expovariate() It gives a random float


number on the basis of
the Exponential
distribution.

16) gammavariate() It gives a random float


number on the basis of
the Gamma
distribution.

17) gauss() This function


generates a random
floating-point number
based on the Gaussian
distribution.

18) lognormvariate() This function gives a


random float number
based on a log-normal
distribution.

19) normalvariate() This function gives a


random float number
based on the normal
distribution

20) vonmisesvariate() This function returns a


random float number
based on the Von
Mises distribution.
21) paretovariate() This function returns a
random float number
based on the Pareto
distribution.

22) weibullvariate() This function returns a


random float number
based on the Weibull
distribution.

There are various types of functions available in the Python Random


Module. Let's have a look at them:

S No. Functions Description

1) seed() It generates a fixed set of


random numbers

2) getstate() It gives the current


internal state of the
random number
generator.

3) getrandbits() Generates random


number bits

4) randrange() Generates random


numbers within a
specified range

5) randint() It also generates random


numbers within a given
range.

6) setstate() It restores the internal


state of the random
number generator.

7) choice() It gives a random number


from a sequence.

8) choices() It gives multiple numbers


from a sequence

9) shuffle() This function shuffles the


items in a sequence

10) sample() This function returns a


given sample of a
sequence

11) random() This function returns a


random float number
between 0 and 1

12) uniform() Returns a random float


number between two
given parameters

13) triangular() Returns a random float


number between two
given parameters. You
can also set a mode
parameter to specify the
midpoint between the
two other parameters.

14) betavariate() It gives a random float


number between 0 and 1
on the basis of the Beta
distribution.

15) expovariate() It gives a random float


number on the basis of
the Exponential
distribution.
16) gammavariate() It gives a random float
number on the basis of
the Gamma distribution.

17) gauss() This function generates a


random floating-point
number based on the
Gaussian distribution.

18) lognormvariate() This function gives a


random float number
based on a log-normal
distribution.

19) normalvariate() This function gives a


random float number
based on the normal
distribution

20) vonmisesvariate() This function returns a


random float number
based on the Von Mises
distribution.

21) paretovariate() This function returns a


random float number
based on the Pareto
distribution.

22) weibullvariate() This function returns a


random float number
based on the Weibull
distribution.

Examples of the Python Random Module


Using the randint() function

[Link] random
2.#using the randint() function
1.n1 = [Link](1,15) #
n1 = [Link](1, 15, 2)
3.
4.#printing the random value
[Link] (n1)
Generate a Random Float between 0 and 1
import random
n1 = [Link]()
print (n1)

Randomly Select from List, String, and Tuple


import random
#declaring a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#printing random elements from the list
print([Link](my_list))
#declaring a string
my_string = "Tpoint"
#printing random elements from the string
print([Link](my_string))
#declaring a tuple
my_tuple = (2, 0, 1, 9)
#printing random elements from the tuple
print([Link](my_tuple))
Python NumPy


Numpy is a general-purpose array-processing package. It provides a high-


performance multidimensional array object, and tools for working with these
arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient
multi-dimensional container of generic data.

Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same


type, indexed by a tuple of positive integers. In Numpy, number of
dimensions of the array is called rank of the array. A tuple of integers
giving the size of the array along each dimension is known as shape of
the array. An array class in Numpy is called as ndarray. Elements in
Numpy arrays are accessed by using square brackets and can be
initialized by using nested Python Lists.

Creating a Numpy Array

Arrays in Numpy can be created by multiple ways, with various number of Ranks,
defining the size of the Array. Arrays can also be created with the use of various
data types such as lists, tuples, etc. The type of the resultant array is deduced from
the type of the elements in the sequences.
Note: Type of array can be explicitly defined while creating the array.

Numerical Python is very big and important library it is used in


scientific computing, data analysis, and machine learning
Where it is used : Data Science , Machine Learning (ML), Artificial Intelligence (AI),
Image Processing, Physics / Engineering , Stock Market & Business Analytics

import numpy as np

matrix = [Link]([[1, 2], [3, 4]])

print(matrix.T) # Transpose

print([Link](matrix)) # Total sum


print([Link](matrix))# Average
mport numpy

matrix = [Link]([[1, 2], [3, 4]])

print(matrix.T) # Transpose

print([Link](matrix)) # Total sum


print([Link](matrix))# Average

import numpy as np

# Creating a rank 1 Array


arr = [Link]([1, 2, 3])
print(arr)

# Creating a rank 2 Array


arr = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr)

# Creating an array from tuple


arr = [Link]((1, 3, 2))
print(arr)

Array with Rank 1:


[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]

Array created using passed tuple:


[1 3 2]

Accessing the array Index


import numpy as np

arr = [Link]([[-1, 2, 0, 4],


[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])

# Printing a range of Array


# with the use of slicing method
arr2 = arr[:2, ::2]
print ("first 2 rows and alternate columns(0 and 2):\n", arr2)

# Printing elements at
# specific Indices
arr3 = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", arr3)

Output
first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[0. 6. 2. 3.]

Basic Array Operations


In numpy, arrays allow a wide range of operations which can be
performed on a particular array or a combination of Arrays. These
operation include some basic Mathematical operation as well as Unary
and Binary operations.

import numpy as np

# Defining Array 1
a = [Link]([[1, 2],
[3, 4]])

# Defining Array 2
b = [Link]([[4, 3],
[2, 1]])

# Adding 1 to every element


print ("Adding 1 to every element:", a + 1)

# Subtracting 2 from each element


print ("\nSubtracting 2 from each element:", b - 2)

# sum of array elements


# Performing Unary operations
print ("\nSum of all array elements: ", [Link]())

# Adding two arrays


# Performing Binary operations
print ("\nArray sum:\n", a + b)

Output
Adding 1 to every element: [[2 3]
[4 5]]
Subtracting 2 from each element: [[ 2 1]
[ 0 -1]]

Sum of all array elements: 10

Array sum:
[[5 5]
[5 5]]
More on Numpy Arrays

You might also like