VIVEKANADA COLLEGE OF
TECHNOLOGY AND MANAGEMENT,
ALIGARH
PRATICAL FILE
FOR
PYTHON LAB
LAB CODE: KME552
B.TECH 3RD YEAR (ME)
SESSION: 2023-24
SUBMITTED TO: SUBMITTED BY:
MR. PRABHAT SINGH NAME:
(CSE DEPTT.) ROLL NO:
INDEX
S.NO EXPERIMENTS DATE OF SIGN. OF
EXPERIMENTS FACULTTY
1
To write a python program Simple Calculator by Using
Functions.
2 To write a python program linear search.
3 To write a python program to perform Matrix Multiplication.
To write a Python program binary search (Iterative Method).
4
5 To write a python program first n prime numbers.
6 To write a python program exponentiation (power of number)
using a for loop.
To write a python program find the square root of a number
7
(Newton’s method).
WAP to find largest among three numbers using if
8
WAP to display menu for calculating area and perimeter of circle
9 using if else
WAP to arrange in ascending order b/w 3 numbers using if elif
10
WAP to take ten integer from user and print average of these using
11 while loop
12
Python Program to Solve Quadratic Equation.
13 Remove Duplicates from a list in Python
14 WAP to input and print the element sum of users defined matrix.
15 DRAW various types of Matplotlib plot line style.
PROGRAM-1
To write a python program Simple Calculator by Using Functions.
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a number.")
continue
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
# check if user wants another calculation
# break the while loop if answer is no
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
OUTPUT:
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
PROGRAM-2
To write a python program linear search.
def search(a, l, x):
# Traversing the array
for i in range(l):
if (a[i] == x):
return i
return -1
a = [10, 8, 6, 4, 2]
print("The given array is ", a)
x=6
print("Element to be searched is ", x)
l = len(a)
ind = search(a, l, x)
if(ind == -1):
print("Element Not Found")
else:
print("Element is at index ", ind)
OUTPUT:
The given array is [10, 8, 6, 4, 2]
Element to be searched is 6
Element is at index 2
PROGRAM-3
To write a python program to perform Matrix Multiplication.
# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
OUTPUT:
[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]
PROGRAM 4
To write a Python program binary search (Iterative Method).
# Binary Search in python
def binarySearch(array, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
array = [3, 4, 5, 6, 7, 8, 9]
x=4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
OUTPUT:
Element is present at index 1
PROGRAM-5
To write a python program first n prime numbers.
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
break
else:
print(num)
OUTPUT:
Enter the start of range: 1
Enter the end of range: 100
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
PROGRAM-6
To write a python program exponentiation (power of number)using
a for loop.
base = 3
exponent = 4
result = 1
while exponent != 0:
result *= base
exponent-=1
print("Answer = " + str(result))
OUTPUT:
Answer = 81
PROGRAM-7
To write a python program find the square root of a number
(Newton’s method).
def newtonsqrt(n): approx=0.5*n
better=0.5*(approx+n/approx)
while better!=approx:
approx=better better=0.5*(approx+n/approx)
return approx
print(newtonsqrt(25))
OUTPUT:
Answer is 5.0
PROGRAM-8
WAP to find largest among three numbers using if
a= 52
b= 56
c= 95
if(a>=b) and (a>=c):
print("A is greater")
elif(b>=c) and (b>=a):
print("B is grater")
else:
print("C is greater")
OUTPUT:-
C is greater
PROGRAM -9
WAP to display menu for calculating area and perimeter of circle
using if else
import math
print("Menu:")
print("1. Calculate Area")
print("2. Calculate Perimeter")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
while True:
if choice == "1":
radius = float(input("Enter the radius of the circle: "))
area= math.pi*radius**2
print("The area of the circle is:",area)
break
elif choice == "2":
radius = float(input("Enter the radius of the circle: "))
perimeter=2*math.pi*radius
print("The perimeter of the circle is:",perimeter)
break
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
OUTPUT:-Menu:
1. Calculate Area
2. Calculate Perimeter
3. Exit Enter your choice (1-3): 1
Enter the radius of the circle: 25
The area of the circle is: 1963.4954084936207
PROGRAM-10
WAP to arrange in ascending order b/w 3 numbers using if elif
num1=int(input("Enter First number : "))
num2=int(input("Enter Second number : "))
num3=int(input("Enter Third number : "))
if num1<num3:
if num2<num3:
x,y,z=num1,num2,num3
else:
x,y,z=num1,num3,num2
elif num2<num1 and num2<num3:
if num1<num3:
x,y,z=num1,num2,num3
else:
if num1<num3:
x,y,z=num2,num1,num3
else:
x,y,z=num2,num3,num1
else:
if num1<num2:
x,y,z=num3,num1,num2
else:
x,y,z=num3,num2,num1
print("Numbers in ascending order are : ",x,y,z)
OUTPUT:-
Enter First number : 5
Enter Second number : 9
Enter Third number : 2
Numbers in ascending order are : 2 5 9
PROGRAM-11
WAP to take ten integer from user and print average of these using
while loop
sum=0
fori in range(0,10):
a=int(input("enter the number"))
count=0
while (count<10)
sum=sum+a
count=count+1
print('average of numbers is',(sum/10))
OUTPUT;
enter the number2
enter the number3
enter the number4
enter the number5
enter the number6
enter the number7
enter the number8
enter the number9
enter the number10
enter the number11
average of numbers is 65.0
Program -12
Python Program to Solve Quadratic Equation
# Solve the quadratic equation ax**2 + bx + c = 0
# import complex math module
import cmath
a=1
b=5
c=6
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))
OUTPUT
The solution are (-3+0j) and (-2+0j)
Program -13
Remove Duplicates from a list in Python
#initializing the list
list_value1=[12,15,11,12,8,15,3,3]
print("The initialized list is ",list_value1)
res_list=[]
for i in list_value1:
if i not in res_list:
res_list.append(i)
#printing the list after removing duplicate elements
print("The resultant list after removing duplicates is ",res_list)
OUTPUT
The initialized list is [12, 15, 11, 12, 8, 15, 3, 3]
The resultant list after removing duplicates is [12, 15, 11, 8, 3]
PROGRAM-14
WAP TO INPUT AND PRINT THE ELEMENT SUM OF USERS
DEFINED MATRIX.
# An example code to take matrix input by user
Rows = int(input("Give the number of rows:"))
Columns = int(input("Give the number of columns:"))
# Initializing the matrix
example_matrix = []
print("Please give the entries row-wise:")
# For user input
for _ in range(Rows): # This for loop is to arrange rows
r = []
for __ in range(Columns): # This for loop is to arrange columns
r.append(int(input()))
example_matrix.append(r)
# Printing the matrix given by user
for _ in range(Rows):
for __ in range(Columns):
print(example_matrix[_][__], end=" ")
print()
OUTPUT:
Give the number of rows:2
Give the number of columns:3
Please give the entries row-wise:
3
5
2
7
4
6
352
746
PROGRAM-15
DRAW VARIOUS TYPES OF MATPLOTLIB PLOT LINE STYLE
# Importing packages
import matplotlib.pyplot as plt
# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]
# Plot a simple line chart with 'solid' linestyle
plt.plot(x, y, linestyle='-')
plt.show()
# Plot a simple line chart with 'dashed' linestyle
plt.plot(x, y, linestyle='dashed')
# Or you can use: plt.plot(x, y, linestyle='--')
plt.show()
# Plot a simple line chart with 'dotted' linestyle
plt.plot(x, y, ':')
plt.show()
# Plot a simple line chart with 'dash_dot' linestyle
plt.plot(x, y, '-.')
plt.show()
# Importing packages
import matplotlib.pyplot as plt
# Define x and y values
x = [7, 14, 21, 28, 35, 42, 49]
y = [8, 13, 21, 30, 31, 44, 50]
# Plot a simple line chart with 'solid' linestyle
plt.plot(x, y, linestyle='-')
plt.show()
# Plot a simple line chart with 'dashed' linestyle
plt.plot(x, y, linestyle='dashed')
# Or you can use: plt.plot(x, y, linestyle='--')
plt.show()
# Plot a simple line chart with 'dotted' linestyle
plt.plot(x, y, ':')
plt.show()
# Plot a simple line chart with 'dash_dot' linestyle
plt.plot(x, y, '-.')
plt.show()
OUTPUT