NETAJI SUBHAS UNIVERSITY OF TECHNOLOGY
COMputer Programming
PRACTICAL FILE
SEMESTER 1 (BATCH 2023-27)
BRANCH- CSE
Aryan Baibaswata
Submitted to: Ms. Mahima Yadav
EXPERIMENT 1: WRITE A PYTHON PROGRAM TO PRINT “HELLO, WORLD!”....................................................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
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.....................................10
EXPERIMENT 5B: WRITE A FUNCTION TO CHECK IF A STRING IS A PALINDROME OR NOT.............................11
EXPERIMENT 6A: PERFORM VARIOUS OPERATIONS ON LISTS (E.G., SLICING, SORTING)...............................12
EXPERIMENT 6B: USE DICTIONARIES TO STORE AND RETRIEVE STUDENT GRADES.......................................13
EXPERIMENT 7A: CREATE A CLASS TO REPRESENT A BOOK WITH ATTRIBUTES AND METHODS.....................14
EXPERIMENT 7B: IMPLEMENT INHERITANCE BY CREATING SUBCLASSES FOR DIFFERENT TYPES OF BOOKS...15
EXPERIMENT 8A: WRITE A GENERATOR FUNCTION TO GENERATE THE FIBONACCI SERIES............................18
EXPERIMENT 8B: USE LAMBDA FUNCTIONS, MAP, AND FILTER TO PERFORM OPERATIONS ON A LIST..........19
EXPERIMENT 9A: CREATE A MODULE THAT CONTAINS FUNCTIONS FOR MATHEMATICAL OPERATIONS.......21
EXPERIMENT 9B: IMPORT AND USE FUNCTIONS FROM EXTERNAL PACKAGES (E.G., MATH, RANDOM)........22
EXPERIMENT 10A: CREATE AND MANIPULATE NUMPY ARRAYS...................................................................24
EXPERIMENT 11A: IMPLEMENT STRING OPERATIONS (E.G., CONCATENATION, SLICING)..............................26
EXPERIMENT 11B: VALIDATE EMAIL ADDRESSES USING REGULAR EXPRESSIONS..........................................28
EXPERIMENT 12A: READ DATA FROM A TEXT FILE AND PERFORM OPERATIONS..........................................29
EXPERIMENT 12B: HANDLE EXCEPTIONS FOR FILE OPERATIONS AND INPUT VALIDATION............................36
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.
x = int(input("Enter radius of circle: "))
pi = 3.14
area = pi*(x**2)
print(f"The area of the circle is {area}")
Output:
3
Experiment 2b:
Perform basic arithmetic operations on
variables.
x=int(input("Enter the value of x: "))
y=int(input("Enter the value of y: "))
a = x+y
b = x-y
c = x*y
d = x/y
print(f"The sum of the two numbers: {a} ")
print(f"The difference of the two numbers: {b} ")
print(f"The product of the two numbers: {c} ")
print(f"The quotient of the two numbers: {d} ")
Output:
4
Experiment 3a:
Write a Python program to check if a
number is even or odd
x = int(input("Enter the value of number: "))
if x%2==0:
print(f"{x} is even")
else:
print(f"{x} is odd")
Output:
5
Experiment 3b
Implement a simple calculator using
conditional statements
x = int(input("Enter the first number:"))
y = int(input("Enter the second number:"))
while True:
menu = int(input("1.Add \n2. Subtract \n3. Multiply \n4. Division \n5. Quit\nEnter option number: \n>>>"))
if menu == 1:
print(x+y)
elif menu == 2:
print(x-y)
elif menu == 3:
print(x*y)
elif menu == 4:
print(x/y)
elif menu == 5:
quit()
else:
print("Invalid option.")
6
Output:
7
Experiment 4a:
Write a Python program to print the
Fibonacci series using a for loop
n = int(input("Enter the number of terms: "))
a=0
b=1
print(a)
print(b)
for i in range(2,n):
c = a+b
a=b
b=c
print(c)
Output:
8
Experiment 4b:
Use a while loop to find the factorial of
a number
n = int(input("Enter the number: "))
fact = 1
while n>0:
fact = fact*n
n = n-1
print(fact)
Output:
9
Experiment 5a:
Write a function to calculate the sum of
two numbers
def sum(a,b):
return a+b
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print(f"Sum of {x} and {y} is {sum(x,y)}")
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}"
x = Book("The Alchemist", "Paulo Coelho", 350, "Fiction")
y = Detective("The Hound of Baskervilles", "Arthur Conan Doyle",
250, "Detective", "Sherlock Holmes")
z = Fiction("The Alchemist", "Paulo Coelho", 350, "Fiction",
"Adventure")
print(x)
print(y)
print(z)
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
x = int(input("How many terms do you want to generate? \n>>> "))
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)
import operators, 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