SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
Practical 01
Programs to understand the control structures of python.
1. Python program to print "Hello Python"
print("Hello World")
print("Shreel Gandhi\n230410107033")
OUTPUT:-
2. Python program to find the area of a triangle
b=float(input("Enter base:"))
h=float(input("Enter height:"))
area=0.5*b*h
print(f"the area of triangle is {area}")
print("Shreel Gandhi\n230410107033")
OUTPUT:-
3. Python Program to Check Leap Year
year=int(input("ENTER YEAR:"))
if year%4==0:
print(year,"is a leap year")
else:
print(year,"is not a leap year")
ENROLLMENT NO.:230410107033 Page|1
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
print("Shreel Gandhi\n230410107033")
OUTPUT
4. Python Program to Find the Sum of Natural Numbers
n1=int(input("Enter starting no:"))
n2=int(input("Enter ending no:"))
sum=0
for i in range(n1,n2+1):
sum+=i
print(sum)
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|2
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
5. Python Program to Print all Prime Numbers between an
Interval
no=int(input("Enter starting range no:"))
no1=int(input("Enter no:"))
for i in range(no,no1+1):
if i>1:
for j in range(2,i):
if i%j==0:
break
else:
print(i)
OUTPUT:-
ENROLLMENT NO.:230410107033 Page|3
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
Practical 02
Develop programs to learn different data-types (string “ ”, set { },
list [],dictionary { : }, tuple ( )) in python.
1. Python Program to Remove Punctuation from a String
import string
st=input("Enter string:")
no_pun=""
for char in st:
if char not in [Link]:
no_pun=no_pun+char
print(no_pun)
print("Shreel Gandhi\n230410107033")
OUTPUT:
2. Python Program to Illustrate Different Set Operations – Union,
Intersection, Difference, Symmetric Difference
s1={2,4,5,6}
s2={1,3,4,8}
print([Link](s2))
print([Link](s2))
print([Link](s2))
print((s1-s2|s2-s1))
print("Shreel Gandhi\n230410107033")
ENROLLMENT NO.:230410107033 Page|4
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
OUTPUT:
3. Python Program to demonstrate list slicing
l1=[1,4,5,2,'SVIT','name']
print(l1[1:-1:2])
l2=[4,6,7,8,2,"Hello"]
print(l2[::-1])
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|5
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
4. Python Program to compare two lists
ls1=[2,4,5,6,"hey"]
ls2=[2,4,5,6,"hey"]
print(ls1==ls2)
print("Shreel Gandhi\n230410107033")
OUTPUT:
5. Python Program to Check If a List is Empty
l1=[3,4,5,7]
if not l1:
print("List is empty")
else:
print("list is not empty")
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|6
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
6. Python Program Concatenate Two Lists
a=[1,2,3,"Shreel"]
b=[5,6,7,'Maitri']
for i in b:
[Link](i)
print(a)
print("Shreel Gandhi\n230410107033")
OUTPUT:
7. Python Program to Merge Two Dictionaries
d1={"name":"Shreel","age":21}
d2={"name1":"Lency","age1":20,"age2":90}
#d1|d2
print({**d1,**d2})
print("Shreel Gandhi\n230410107033")
OUTPUT:
8. Python Program to Iterate Over Dictionaries Using for Loop
dict1={"name":"Krishna","favsub":"python","food":"pizza","age":22}
for i in dict1:
print(i,dict1[i])
print([Link]())
print("Shreel Gandhi\n230410107033")
ENROLLMENT NO.:230410107033 Page|7
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
OUTPUT:
9. Python Program to Sort a Dictionary by Value
dt1={"name":"Krishna","favsub":"python","food":"pasta","college":"SVIT"}
print([Link]())
print(sorted([Link]()))
print("Shreel Gandhi\n230410107033")
OUTPUT:
10. Python Program to Find the size of a Tuple
tup=(1,2,3,4)
print(len(tup))
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|8
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
10. Python Program to find Sum of Tuple’s elements (numbers)
t1=(2,4,5,6)
print(sum(t1))
print("Shreel Gandhi\n230410107033")
OUTPUT:
11. Python Program to Count the Number of Each Vowel
a="aeiou"
s1="hellowhats up why so sad"
occ={i:[Link]().count(i) for i in a}
print(occ)
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|9
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
Practical 03
3. Develop programs to learn concept of functions scoping,
recursion and list mutability
1. Python program to demonstrate use of local variable,non-local
and global variable
a=15
def localfun():
a=20
print("This is local variable",a)
def innerfun():
nonlocal a
a=30
print("This is non local variable",a)
innerfun()
print("The global variable is",a)
localfun()
print("Shreel Gandhi\n230410107033")
ENROLLMENT NO.:230410107033 Page|10
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
2. Python Program to Make a Simple Calculator
print("1. + 2. - 3. * 4. /")
op = ["+", "-", "*", "/"]
choice = input("Enter choice (1/2/3/4): ")
if choice in ['1', '2', '3', '4']:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid input! Please enter 1, 2, 3, or 4.")
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|11
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
3. Python Program to Find Factorial of Number Using
Recursion
def fact(n):
if n==0 or n==1:
return 1
else:
return n*fact(n-1)
n=int(input("Enter number:"))
print(fact(n))
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|12
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
4. Python Program to Display Fibonacci Sequence Using
Recursion
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# n = int(input("Enter the number you want to find in fibonnaci: "))
# print(fibonacci(n))
terms=int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(terms):
print(fibonacci(i), end=" ")
print("\nShreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|13
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
PRACTICAL-4
AIM: Develop programs to understand working of exception handling and
assertions.
try:
numerator = float(input("Enter numerator: "))
denominator = float(input("Enter denominator: "))
result = numerator / denominator
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter valid numeric values!")
else:
print(f"Result: {result}")
finally:
print("Execution completed.")
print("Shreel Gandhi\n23041007033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|14
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
PRACTICAL-5
AIM: Develop programs to demonstrate use of NumPy
1. Print Numpy version and configuration information.
import numpy as np
print(np.__version__)
np.show_config()
print("Shreel Gandhi\n230410107033")
OUTPUT:
2. Create a numpy array with numbers ranging from 50 to [Link] print attributes of
created object.
a=[Link](50,101)
print(a)
print("Shreel Gandhi\n230410107033")
OUTPUT:
[Link] a null vector of size 10.
ENROLLMENT NO.:230410107033 Page|15
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
a1=[Link](10)
print(a1)
print("Shreel Gandhi\n230410107033")
OUTPUT:
4. Create a vector of size 10 initialized with a seed equal to last four digits of your
enrolment number.
seed = 7033
[Link](seed)
vector = [Link](10)
print(vector)
print("Shreel Gandhi\n23040107033")
OUTPUT:
5. Create a matrix of size 5x5 initialized with random integers with a seed equal to last four
digits of your enrolment number.
a=[Link](10,size=(5,5))
seed=7033
[Link](seed)
print(a)
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|16
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
6. Create an identity matrix of size 5x5.
a=[Link](5)
print(a)
print("Shreel Gandhi\n230410107033")
OUTPUT:
7. Do the following
a. Create a numpy array mat1 of size5x2 with numbers ranging from1 to 10.
mat1=[Link](1,11)
[Link](mat1,(5,2))
print(mat1)
print("Shreel Gandhi\n230410107033")
OUTPUT:
b. Create an other numpy array mat2 of size2x5 with floating point numbers
between 10 to 20.
mat2=[Link](10,20,10)
[Link](mat2,(2,5))
print(mat2)
print("Shreel Gandhi\n230410107033")
Output:
c. Calculate the matrix product of mat1 and mat2.
mat3=[Link](mat1,mat2)
print(mat3)
print("Shreel Gandhi\n230410107033")
d. Print vector containing minimum and maximum in each row of mat1.
ENROLLMENT NO.:230410107033 Page|17
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
mat1 = [Link](1, 11).reshape(5, 2)
min_in_rows = [Link](mat1, axis=1)
max_in_rows = [Link](mat1, axis=1)
min_max_vector = np.column_stack((min_in_rows, max_in_rows))
print(min_max_vector)
OUTPUT:
e. Print vector containing mean and standard deviation in each column of
mat2 Perform vstackand hstack on mat1 and mat2.
print([Link](mat2))
print([Link](mat2))
print("Shreel Gandhi\n230410107033")
OUTPUT:
f. Perform vstack and hstack on mat1 and mat2.
mat2 = [Link](10, 20, 10).reshape(5, 2)
v_stacked = [Link]((mat1, mat2))
h_stacked = [Link]((mat1, mat2))
print("\nVertical Stack of mat1 and mat2:")
print(v_stacked)
print("\nHorizontal Stack of mat1 and mat2:")
print(h_stacked)
print("Shreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|18
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
g. Split mat1 horizontal into 2 and split mat2 vertical into 2 parts.
mat1 = [Link](1, 11).reshape(5, 2)
mat2 = [Link](10, 20, 10).reshape(2, 5)
# Horizontal split of mat1
mat1_split = [Link](mat1, 2)
print("\nHorizontal split of mat1 into 2 parts:")
for i, part in enumerate(mat1_split, 1):
print(f"Part {i}:\n{part}")
# Vertical split of mat2
mat2_split = [Link](mat2, 2) # will work because shape is (2,5)
print("\nVertical split of mat2 into 2 parts:")
for i, part in enumerate(mat2_split, 1):
print(f"Part {i}:\n{part}")
print("\nShreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|19
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
8. Create a vector vec of size 20 initialized with double numbers ranging from20 to 40
and do the following.
a. Reshape it to a 5x4 matrix mat.
import numpy as np
vec=[Link](20,40,20)
mat=[Link](5,4)
print(mat)
print("Shreel Gandhi\n230410107033")
OUTPUT:
b. Print every 4th element of vec.
print(vec[::4])
OUTPUT:
c. Print elements of vec less than or equal to 25.
print(vec[vec<=25])
OUTPUT:
d. In vec assign every number at even location to 1.
vec[::2]=1
print(vec)
OUTPUT:
e. In vec assign from start position to10th position every second element to 0.
vec[:10:2]=0
print(vec)
OUTPUT:
ENROLLMENT NO.:230410107033 Page|20
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
f. Reverse elements of vec.
print(vec[::-1])
OUTPUT:
g. In mat print each row in the second column and print each column in the second row
# Print each row's value in the second column (index 1)
print("Each row's value in the second column:")
for row in mat:
print(row[1])
# Print each column's value in the second row (index 1)
print("\nEach column's value in the second row:")
for col in mat[1]:
print(col)
OUTPUT:
h. Apply some universal functions such as sin,sqrt,cos,exp on vec.
sin_vec = [Link](vec)
sqrt_vec = [Link](vec)
cos_vec = [Link](vec)
exp_vec = [Link](vec)
# Display results
print("Original vector (vec):")
print(vec)
print("\nSine of vec:")
print(sin_vec)
ENROLLMENT NO.:230410107033 Page|21
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
print("\nSquare root of vec:")
print(sqrt_vec)
print("\nCosine of vec:")
print(cos_vec)
print("\nExponential of vec:")
print(exp_vec)
OUTPUT:
i. Print transpose and inverse of mat.
vec = [Link](20, 40, 20)
mat = [Link](5, 4)
print("\nTranspose of mat:\n", mat.T)
print("\nPseudo-inverse of mat:\n", [Link](mat))
print("\nShreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|22
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: PDS SUBJECT CODE: 3150713
9. Demonstrate shallow copy and deep copy.
import copy
arr = [Link]([1, 2, 3, 4, 5])
print("Original array:", arr)
# Shallow copy
shallow = [Link]() # or [Link]() with .view() is true shallow copy
shallow[0] = 99
print("\nAfter changing shallow copy:")
print("Shallow copy:", shallow)
print("Original array:", arr) # Changes in shallow copy reflect in original
# Deep copy
arr = [Link]([1, 2, 3, 4, 5]) # Reset original
deep = [Link]()
deep[0] = 88
print("\nAfter changing deep copy:")
print("Deep copy:", deep)
print("Original array:", arr)
print("\nShreel Gandhi\n230410107033")
OUTPUT:
ENROLLMENT NO.:230410107033 Page|23