COMputer Programming
COMputer Programming
COMputer Programming
PRACTICAL FILE
Aryan Baibaswata
1
Experiment 1:
Write a Python Program to print “Hello,
World!”
print(“Hello, World!”)
Output:
2
Experiment 2a:
Write a Python program to calculate
the area of a circle given the radius.
3
Experiment 2b:
Perform basic arithmetic operations on
variables.
4
Experiment 3a:
Write a Python program to check if a
number is even or odd
5
Experiment 3b
Implement a simple calculator using
conditional statements
6
Output:
7
Experiment 4a:
Write a Python program to print the
Fibonacci series using a for loop
8
Experiment 4b:
Use a while loop to find the factorial of
a number
9
Experiment 5a:
Write a function to calculate the sum of
two numbers
def sum(a,b):
return a+b
Output:
10
Experiment 5b:
Write a function to check if a string is a
palindrome or not
def paliString():
x = input("Enter string to check: ")
tempString = x[::-1]
if tempString == x:
return f"String {x} is a palindrome."
return f"String {x} is not a palindrome."
print(paliString())
11
Experiment 6a:
Perform various operations on lists
(e.g., Slicing, sorting)
list1 = [3,4,7,8,1,2,3,0]
newList = list1[0::2]
x = len(list1)
for i in range(x):
for j in range(i+1, x):
if list1[i] >= list1[j]:
list1[i], list1[j] = list1[j], list1[i]
print(list)
Output:
12
Experiment 6b:
Use dictionaries to store and retrieve
student grades
student={}
while True:
x = input("Enter student name:")
y = input("Enter student grade")
student[x] = y
cont = input("Continue(y/n)? \n>>>")
if cont in 'yY':
continue
else:
break
print(student)
Output:
13
Experiment 7a:
Create a class to represent a book with
attributes and methods
class Book:
def __init__(self, name, author, price, genre):
self.name = name
self.author = author
self.price = price
self.genre = genre
def __str__(self):
return f"{self.name} by {self.author} ({self.price}) \n{self.genre}"
x = Book("The Alchemist", "Paulo Coelho", 350, "Fiction")
print(x)
Output:
14
Experiment 7b:
Implement inheritance by creating
subclasses for different types of books.
class Book:
def __init__(self, name, author, price, genre):
self.name = name
self.author = author
self.price = price
self.genre = genre
def __str__(self):
return f"{self.name} by {self.author} ({self.price}) \n{self.genre}"
class Detective(Book):
def __init__(self, name, author, price, genre, subgenre):
super().__init__(name, author, price, genre)
self.subgenre = subgenre
def __str__(self):
return super().__str__() + f", {self.subgenre}"
class Fiction(Book):
def __init__(self, name, author, price, genre, subgenre):
super().__init__(name, author, price, genre)
self.subgenre = subgenre
15
def __str__(self):
return super().__str__() + f", {self.subgenre}"
16
Output:
17
Experiment 8a:
Write a generator function to generate
the Fibonacci Series
def gen_fib(n):
a, b = 0, 1
while a < n:
yield a
a,b = b, a+b
y = gen_fib(x)
for i in y:
print(i)
Output:
18
Experiment 8b:
Use lambda functions, map, and filter
to perform operations on a list.
u = lambda x: x+1
list1 = [1,2,3,4]
print(list1)
list2 = list(map(u, list1))
print(list2)
def lester(x):
if x<18:
return False
else:
return True
list3 = [17,23,54,20,1,32,4,7,9,22]
list4 = list(filter(lester, list3))
print(list3)
print(list4)
19
Output:
20
Experiment 9a:
Create a module that contains
functions for mathematical operations.
def add(x,y):
return x+y
def sub(x,y):
return x-y
def mult(x,y):
return x*y
def div(x,y):
return x/y
21
Experiment 9b:
Import and use functions from external
packages (e.g., math, random)
print(operators.add(10,9))
print(random.randint(0,8))
while True:
x = random.randint(0,10)
guess = int(input("Guess a number between 0 and 10. \n>>> "))
if guess == x:
print("You guessed right.")
else:
print("You guessed wrong.")
print("The number was", x)
y = input("Continue? \n>>> ")
if y in 'nN':
break
22
Output:
23
Experiment 10a:
Create and manipulate NumPy Arrays
import numpy as np
list1,list2=[x for x in range (0,10)],[x for x in range(10,20)]
arr = np.array([list1,list2])
print(arr)
print("1",arr[0],arr[1],sep="\n")
print('2',arr[0][3])
print('3',arr[0][2:6],arr[1][5:-1:-1],sep="\n")
print('4',arr[0:1][0:6:2])
print(arr.reshape(4,5))
24
Output:
25
Experiment 11a:
Implement string operations (e.g.,
concatenation, slicing)
#concatenation
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
print(str3)
#substring
str4 = str3[0:5]
print(str4)
#length
print(len(str3))
#lowercase
print(str3.lower())
#uppercase
print(str3.upper())
#replace
print(str3.replace("World", "Universe"))
26
#split
print(str3.split(" "))
#strip
str5 = " Hello World "
print(str5.strip())
Output:
27
Experiment 11b:
Validate email addresses using regular
expressions
import re
def emails():
email = input("Enter an email address: ")
if re.match("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
email):
print("Valid email address.")
else:
print("Invalid email address.")
emails()
Output:
28
Experiment 12a:
Read data from a text file and perform
operations
def create():
f1 = open("sample.txt","w")
while True:
str = input('enter content')
f1.write(str+'\n')
ans = input('want to continue')
if ans in "nN":
f1.close()
break
def funa():
x=int(input("Enter line size: "))
cnt=0
f1=open('sample.txt','r')
for line in f1.readlines():
if len(line) <= x:
cnt+=1
print(cnt, 'number of lines returned')
def count():
cnt=0
f2=open("sample.txt","r")
str=f2.read()
29
s=str.split()
for wd in s:
if wd[0] in 'tT':
cnt+=1
f2.close()
print(cnt)
def pali():
cnt=0
f2=open('sample.txt','r')
str=f2.read()
s=str.split()
for wd in s:
if wd==wd[::-1]:
cnt+=1
f2.close()
print(cnt)
def avgword():
f1 = open("sample.txt","r")
str = f1.read()
cnt = 0
wdcnt = 0
for wd in str.split():
cnt += 1
wdcnt += len(wd)
30
avgwd = wdcnt/cnt
f1.close()
print("avg word size is: ",avgwd)
def altword():
f1=open('sample.txt','r')
f2=open('two.txt','w')
str=f1.read()
cnt=0
for wd in str.split():
if cnt%2==0:
f2.write(wd+" ")
cnt+=1
f1.close()
f2.close()
f1=open("two.txt","r")
print(f1.read())
f1.close()
def consonant():
f1=open("sample.txt","r")
f2=open("two.txt","w")
for line in f1.readlines():
if line[0] not in "aeiouAEIOU":
31
f2.write(line)
f1.close()
f2.close()
f1.open("two.txt","r")
print(f1.read())
f1.close()
def to():
f1 = open("sample.txt")
str = f1.read()
cnt = 0
l = str.split()
for i in l:
if i == "to" or i == "To":
cnt +=1
print("number of \"to\"\'s are:", cnt)
f1.close()
def the():
f1 = open("sample.txt",'r')
lst = f1.readlines()
cnt = 0
for i in f1.readlines():
x = i.split()
32
if x[0] == "The" or x[0]=="the":
cnt += 1
print("Number of lines starting with the:", cnt)
while True:
ch=int(input("1. create\n2. count the number of lines starting with
t \n3. count the number of lines <= size \n4.count no of to \n5.count
lines starting with the \n6. count palindrome words \n7.copy
alternate words \n8. copy lines not starting with vowel \n9. average
word size\nenter choice\n>>>"))
if ch==1:
create()
elif ch==2:
count()
elif ch==3:
funa()
elif ch==4:
to()
elif ch==5:
the()
elif ch==6:
pali()
elif ch==7:
altword()
elif ch==8:
consonant()
33
elif ch==9:
avgword()
else:
print("Invalid input!")
ans=input("wish to go bk?")
if ans in"yY":
break
34
Output:
35
Experiment 12b:
Handle exceptions for file operations
and input validation.
#example showing how to handle exceptions for file operations and
input validation
def readfile(fileName):
try:
with open(fileName, 'r') as f:
print(f.read())
except FileNotFoundError:
print("File not found.")
except:
print("Some error occured.")
finally:
print("Done.")
def writefile(fileName):
try:
with open(fileName, 'w') as f:
f.write("This is a new line\n")
f.write("This is another new line\n")
f.write("This is yet another new line\n")
f.write("This is the last new line\n")
except FileNotFoundError:
print("File not found.")
36
except:
print("Some error occured.")
finally:
print("Done.")
def appendfile(fileName):
try:
with open(fileName, 'a') as f:
f.write("This is a new line\n")
f.write("This is another new line\n")
f.write("This is yet another new line\n")
f.write("This is the last new line\n")
except FileNotFoundError:
print("File not found.")
except:
print("Some error occured.")
finally:
print("Done.")
writefile("file.txt")
appendfile("file.txt")
readfile("file.txt")
37
Output:
38