Python Lab Manual
Python Lab Manual
Python Lab Manual
SC
-I
MAT
HEM
ATIC
SI-
LAB
Index
SI. No. Program Name
Lab 1: Python Basic operations
Lab 9: Python Program for Establishing Consistency and solving system of linear equations.
Guido van Rossum was interested on watching a comedy show, which is telecasting on
the BBC channel from 1969 to 1974 The complete Monty Python's Flying Circus.
Guido Van Rossum thought he needed a name that was short, unique, and slightly mysterious for
his programming language, so he decided to call the language Python.
Applications of Python Programming
Web Development
Game Development
Scientific and Numeric applications
Artificial Intelligence and Machine Learning based applications
Data Science related applications
Desktop GUI applications
Software Development
Enterprise-level/Business Applications
Education programs and training courses
Web Scraping Applications
Image Processing
Output:
What's your name? "Alex"
Nice to meet you Alex!
The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block
is executed. Otherwise, the else-block is executed.
1. Python program to check whether a person is eligible for vote.
n=int(input("Enter age: "))
if(n >= 18):
print("Eligible for vote")
n = int(input())
if(n%2 = = 0):
print(“Number is an even number‟)
else:
print(" Number is an odd number ")
Output:
20
Number is an even number
n = int(input())
if(n%2 = = 0):
print("Number is an even number")
else:
print("Number is an odd number")
n = int(input((“Enter a number”))
if(n%4==0):
print(“Leap year”)
else:
print(“Not Leap year”)
Output:
2000
Leap year
n = int(input("Enter a number"))
if(n%4==0):
print("Leap year")
else:
print("Not Leap year")
4. Write python program to read a particular student mark and print the grade
Output:
39
pass class
Output:
Enter range: 5
The sum is 15
sum = 0
for val in range(1, n + 1): # Using n + 1 to include the input value in the
sum += val
print("The sum is", sum) # Printing the sum in each iteration
2. Python program to find the factorial of a given number.
Output:
Enter a number:7
The factorial of 7 is 5040
output:
A = [1,4,5,12]
[5,7,8,9]
[10,3,0,5]
A[0] = [1,4,5,12]
A[1][3] = 9
A[0][2] = 5
2nd column= [4, 7, 3]
import numpy as np
import numpy as np
M2 = np.array([[9, 0, 7],
[0, 5, 4],
[3, 2, 1]])
import numpy as np
# Example matrix addition
M1 = np.array([[1, -2, 3], [4, 5, -6], [-7, -8, 9]])
M2 = np.array([[9, 0, 7], [0, 5, 4], [3, 2, 1]])
#Subtract the matrices using numpy.subtract()
result_matrix = np.subtract(M1, M2)
rows1, cols1, rows2, and cols2 are obtained from the user as the number of rows and columns for
the two matrices.
if cols1 != rows2: checks if the number of columns in the first matrix is equal to the number of
rows in the second matrix. If not, it prints an error message and exits because matrices with these
dimensions cannot be multiplied together.
User input is taken for each element of matrix1 and matrix2 using nested loops.
result is initialized as a matrix filled with zeros, having dimensions rows1 x cols2.
The outermost loops iterate through the rows of matrix1 (rows1) and the columns of matrix2
(cols2).
The innermost loop (k) iterates through the columns of matrix1 and the rows of matrix2,
multiplying corresponding elements and summing them up to calculate the elements of the
resulting matrix result.
After performing multiplication, the code prints the resulting matrix (result) to display the
outcome of the matrix multiplication.
This code essentially performs matrix multiplication for matrices entered by the user, provided
that the dimensions satisfy the requirements for matrix multiplication (where the number of
columns in the first matrix must match the number of rows in the second matrix).
#Get the dimensions of the matrices from the user
rows1 = int(input("Enter the number of rows for matrix 1: "))
cols1 = int(input("Enter the number of columns for matrix 1: "))
rows2 = int(input("Enter the number of rows for matrix 2: "))
cols2 = int(input("Enter the number of columns for matrix 2: "))
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]
OR
Using NumPy library,
import numpy as np
import numpy as np
matrix2 = np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]])
def transpose_matrix(matrix):
# Get the number of rows and columns in the matrix
rows = len(matrix)
cols = len(matrix[1])
# Fill the transpose matrix with the elements from the original matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose
for i in range(rows):
row = []
for j in range(cols):
element = int(input(f"Enter element [{i+1}][{j+1}]: "))
row.append(element)
matrix.append(row)
def transpose_matrix(matrix):
# Get the number of rows and columns in the matrix
rows = len(matrix)
cols = len(matrix[1])
# Fill the transpose matrix with the elements from the original matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose
for i in range(rows):
row = []
for j in range(cols):
element = int(input(f"Enter element [{i+1}][{j+1}]: "))
row.append(element)
matrix.append(row)
OR
Using NumPy library,
import numpy as np
# Create a matrix
matrix = np.array([[1, 2, 3], [0, 11, 6], [-6, 8, 10]])
import numpy as np
# Create a matrix
matrix = np.array([[1, 2, 3], [0, 11, 6], [-6, 8, 10]])
print(round(determinant))
# importing Numpy package
import numpy as np
print(round(determinant))
import numpy as np: Imports the NumPy library with the alias np, which allows access to
NumPy functions using np.
arr = np.array([[2, 0, 1], [-2, 3, 4], [-5, 5, 6]]): Creates a 3x3 NumPy array (a matrix) named arr
with specified elements.
print(arr): Displays the contents of the NumPy matrix arr created earlier.
inverse = np.linalg.inv(arr): Computes the inverse of the matrix arr using NumPy's
np.linalg.inv() function and stores the result in the variable inverse.
from sympy import *: Imports the SymPy library, enabling the use of its functions without
prefixing them with sympy.
Creating a Matrix:
M_rref = M.rref(): Computes the Reduced Row Echelon Form (RREF) of the matrix M using the
rref() method from SymPy. The RREF is stored in the variable M_rref.
print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref)): Prints
the RREF of matrix M along with the pivot columns.
# import sympy
from sympy import *
M = Matrix([[2,3,-1,-1],[1,-1,-2,-4],[3,1,3,-2],[6,3,0,-7]])
print("Matrix : {} ".format(M))
print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref))
# import sympy
from sympy import *
M = Matrix([[2,3,-1,-1],[1,-1,-2,-4],[3,1,3,-2],[6,3,0,-7]])
print("Matrix : {} ".format(M))
import numpy as np: Imports the NumPy library and assigns it the alias np, allowing access to
NumPy functions using the prefix np.
arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]]): Creates a 3x4 NumPy array (a matrix)
named arr with specified elements.
print(arr): Displays the contents of the NumPy matrix arr created earlier.
rank = np.linalg.matrix_rank(arr): Calculates the rank of the matrix arr using NumPy's
np.linalg.matrix_rank() function and stores the result in the variable rank.
import numpy as np: Imports the NumPy library and assigns it the alias np, allowing access to
NumPy functions using the prefix np.
arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]]): Creates a 3x4 NumPy array (a matrix)
named arr with specified elements.
print(arr): Displays the contents of the NumPy matrix arr created earlier.
rank = np.linalg.matrix_rank(arr): Calculates the rank of the matrix arr using NumPy's
np.linalg.matrix_rank() function and stores the result in the variable rank.
import numpy as np
x_matrix = matrix_A.copy()
y_matrix = matrix_A.copy()
z_matrix = matrix_A.copy()
x_matrix[:, 0] = matrix_B
y_matrix[:, 1] = matrix_B
z_matrix[:, 2] = matrix_B
det_x = np.linalg.det(x_matrix)
det_y = np.linalg.det(y_matrix)
det_z = np.linalg.det(z_matrix)
x = det_x / det_A
y = det_y / det_A
z = det_z / det_A
return x, y, z
import numpy as np
if det_A == 0:
return "Determinant of matrix A is zero. Cramer's rule cannot be
applied."
x_matrix = matrix_A.copy()
y_matrix = matrix_A.copy()
z_matrix = matrix_A.copy()
x_matrix[:, 0] = matrix_B
y_matrix[:, 1] = matrix_B
z_matrix[:, 2] = matrix_B
det_x = np.linalg.det(x_matrix)
det_y = np.linalg.det(y_matrix)
det_z = np.linalg.det(z_matrix)
x = det_x / det_A
y = det_y / det_A
z = det_z / det_A
return x, y, z
# Solve AX = B for X
X = np.linalg.solve(A, B)
import numpy as np
# Solve AX = B for X
X = np.linalg.solve(A, B)
import numpy as np: Imports the NumPy library with the alias np to access NumPy functions.
B = np.array([14, 13, 5]): Creates a 1-dimensional NumPy array representing the constant matrix
'B' of the system of linear equations.
Calculating Ranks:
rank_A = np.linalg.matrix_rank(A): Computes the rank of the coefficient matrix 'A' using
NumPy's np.linalg.matrix_rank() function.
Compares the ranks and shapes of the matrices to determine the nature of the system of equations
(consistent or inconsistent).
If the ranks of the coefficient matrix 'A' and the augmented matrix are equal and equal to the
number of variables, it's a consistent system with a unique solution.
If the ranks are equal but less than the number of variables, it's consistent with infinitely many
solutions.
If the system is consistent and has a unique solution, it calculates and prints the values of 'x', 'y',
and 'z' using np.linalg.solve() and displays the solution.
import numpy as np
# Check if the rank of the coefficient matrix equals the rank of the augmented matrix
rank_A = np.linalg.matrix_rank(A)
rank_augmented = np.linalg.matrix_rank(augmented_matrix)
# Check if the rank of the coefficient matrix equals the rank of the augmented
matrix
rank_A = np.linalg.matrix_rank(A)
rank_augmented = np.linalg.matrix_rank(augmented_matrix)
import sympy as sp: Imports the SymPy library with the alias sp, providing access to its
functionalities.
x, y = sp.symbols('x y'): Defines symbolic variables 'x' and 'y' using sp.symbols(). These symbols
are used to represent variables in mathematical expressions.
f = x**2 + y**3 - 2*x*y + 1: Defines a multivariable function 'f' using the previously defined
symbols 'x' and 'y'.
partial_x = sp.diff(f, x): Calculates the partial derivative of function 'f' with respect to 'x' using
sp.diff().
partial_y = sp.diff(f, y): Calculates the partial derivative of function 'f' with respect to 'y' using
sp.diff().
print("Partial derivative of f with respect to x =", partial_x): Prints the computed partial
derivative of 'f' with respect to 'x'.
print("Partial derivative of f with respect to y =", partial_y): Prints the computed partial
derivative of 'f' with respect to 'y'.
import sympy as sp
import sympy as sp