You are on page 1of 52

2020 - 21

Vianney Nagar, A.B.Road, Gwalior, Madhya Pradhesh, PIN-474 010

COMPUTER SCIENCE
PRACTICAL PROGRAMS

SUBMITTED BY: SUBMITTED TO:


Name :Dev Tiwari GLEN RONSON DSOUZA
Class: XII Commerce Faculty CS Department
Reg. No: St. John Vianney School

1|Page
2020 - 21

COMPUTER SCIENCE
PRACTICAL PROGRAMS

INTERNAL EXAMINER EXTERNAL EXAMINER


GLEN RONSON DSOUZA Examiner Name:
Examiner. No: Examiner.No:
St. John Vianney School

Signature: Signature:

Date: Date:

2|Page
2020 - 21

INDEX
SR.NO PROGRAM NAME PAGE NO

1 Program to input user information and demonstrate arithmetic functions 5


using if-elif condition.

2 Program to create four def functions and perform arithmetic operations 6


through function call.
7
3 Program that prints the table of any number using for loop on user input.
8
4 Calculate the GST of item on user input for item cost and GST% required.

5 Demonstration of Sting methods concatenation, repetition, membership, 9


slicing and range().

6 Program to find number of upper and lower case letters from the given string 10
and also demonstrate built in string functions.
11
7 Program to create a list to perform slicing and built in functions.
12
8 Program to create a tuple and perform tuple slicing.
13
9 Program to find the square root of the numbers by creating a list of numbers.

10 Program to find the area, circumference of the circle and the area, perimeter 14 – 15
of the rectangle by using functions for circle and rectangle operation.
16
11 Program of to find the Factorial of a given number using recursion.
17 – 18
12 Program to read, write and append the text file.
19
13 Program to write (dump) and read (load) the binary file.
20
14 Program to copy the content from a file and write on the other.
21
15 Program to capitalize the first 'n' letter of sentence.
22
16 Program to find the time taken using simple and recursion method of sum.

17 Program to add, delete and display the records of an Employee using stack 23 – 24
list.

18 Program to add, delete and display the records of an Employee using Queue 25 – 26
list.
3|Page
2020 - 21

19 Python program to calculate the area of regular polygon. 27


28
20 Program to find the roots of a quadratic equation.
29
21 Python program to calculate arc length of an angle.
30
22 Python program to convert a binary number to decimal number.

23 Python program that takes a list of words and return the length of the 31
longest.

24 Python program to capitalize first and last letter of each word of a given 32
string.

25 Program to swap each character of a given string from lowercase to 33


uppercase and vice versa.
34
26 Program to read a specific line from a file.
35
27 Program to read an entire file.
36
28 Program for inserting a record in a binary file-student.dat.
37
29 Program to read record from a file "student.dat".

30 Program to read record from a file "student.dat" using search method by roll 38
no.

31 Program to implement data insert, modify, search, display and delete using 39-42
dictionary (menu Driven).
43
32 Python program to count the number of record present in "student.csv" File.
44
33 Python program to print record in the form of comma separated values.
45
34 Python program to search record for given student name from csv file.
46
35 Program to write student data onto a csv file importing the cav module.
47
36 Program to write student data onto a csv file importing the cav module.

37 Program to create a new and check the python database connectivity, to 48


create a new database, to show, to create a table and show the description
using python-mysql connectivity.
Program to demonstrate four major operations performed on a table 49-51
38 through MY-SQL connectivity.

4|Page
2020 - 21

PROGRAM: 1
#Program to input user information
#Demonstration of if-elif condition
#Demonstrate arithmetic functions

num1=float(input("Enter first number:"))


num2=float(input("Enter second number:"))
op=input("Enter operator[+-*/% **]:")
result=0
if op=='+':
result=num1+num2
elif op=='-':
result=num1-num2
elif op=='*':
result=num1*num2
elif op=='/':
result=num1/num2
elif op=='%':
result=num1%num2
elif op=='**':
result=num1**num2
else:
print('invalid operator!!')

print (num1,op,num2,'=', result)

OUTPUT:

Enter first number:5


Enter second number:2
Enter operator[+-*/% **]:+
5.0 + 2.0 = 7.0
5.0 - 2.0 = 3.0
5.0 * 2.0 = 10.0
5.0 / 2.0 = 2.5
5.0 % 2.0 = 1.0
5.0 ** 2.0 = 25.0

5|Page
2020 - 21

PROGRAM: 2

#Program to create four def functions


#perform arithmetic operations through function call

def sum(a,b):
print ('The sum is: ',a+b)
def sub(a,b):
print ('The difference is: ',a-b)
defmult(a,b):
print ('The product is: ',a*b)
def div(a,b):
print ('The quotient is: ',a/b)
x=float(input('Enter the number: '))
y=float(input('Enter the number: '))
sum(x,y)
sub(x,y)
mult(x,y)
div(x,y)

OUTPUT:

Enter the number: 5


Enter the number: 2
The sum is: 7.0
The difference is: 3.0
The product is: 10.0
The quotient is: 2.5

6|Page
2020 - 21

PROGRAM: 3

#Program that prints the table of any number using for loop
#User needs to input the number

num=int(input('Enter the number for the table: '))


print("\nMultiplication table of",num)
for a in range(1,11):
print(num , 'x' , a , '=', num*a)

OUTPUT:

Enter the number for the table: 5


Multiplication table of 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

7|Page
2020 - 21

PROGRAM: 4

#calculate the GST of item


#User input for item cost and GST% required.

choice='y'
total=0.0
while choice == 'y' or choice == 'y':
item_price=int(input("Enter the price of an item:"))
gst=int(input("Enter the GST% on the item:"))
total=total+(item_price+(item_price*gst)/100)
choice=input("Press y to continue or press 'n' to display total amount:")
print("Total amount to be paid: " ,total)

OUTPUT:

Enter the price of an item:5000


Enter the GST% on the item:10
Press y to continue or press 'n' to display total amount:y
Enter the price of an item:2500
Enter the GST% on the item:10
Press y to continue or press 'n' to display total amount:n
Total amount to be paid: 8250.0

8|Page
2020 - 21

PROGRAM: 5

#Demonstration of Sting methods


#concatenation,repetition, membership, slicing and range ()

a=("Hello")
b=("Python") # concatenation
print('The concatenation is: ',a+b)

c=("PYTHON")
print ('The repeated string is: ',c*3) # repetition

d=("python")
print('The character "p" in string exists: ','P' in d) # membership
print('The character "H" in string exists: ','H' in d)

e=("hello python")
print('The slice of the string is: ',e[1:3])
print('The slice of the string is: ',e[-4:-1]) # string slicing
print('The slice of the string is: ',e[5:8])

print('The range of characters of index (0-101)in the interval of 5: ',list(range(0,101,5))) #


range()

OUTPUT:

The concatenation is: HelloPython


The repeated string is: PYTHONPYTHONPYTHON
The character "p" in string exists: False
The character "H" in string exists: False
The slice of the string is: el
The slice of the string is: yth
The slice of the string is: py
The range of characters of index (0-101)in the interval of 5: [0, 5, 10, 15, 20, 25, 30, 35, 40,
45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

9|Page
2020 - 21

PROGRAM: 6
#program to find number of upper case and lower case letters from the given string
#also demonstrates built in string functions
string1="The text is HELLO PYTHON"
print(string1)
uprcase=0
lwrcase=0
i=0
while i<len (string1):
if string1[i].islower()== True:
lwrcase +=1
if string1[i].isupper()== True:
uprcase +=1
i+=1
print("No. of uppercase letters in the string=",uprcase)
print("No. of lowercase letters in the string=",lwrcase)
print('To upper:',string1.upper())
print('To lower:',string1.lower())
str2=":"
print('Joining ":" between every character:', str2.join(string1))
print('Swapping from Upper case to Lower Case:',string1.swapcase())
print('Partitioning a piece of text from the string:',string1.partition('PYTHON'))
print('Stripping characters from the word "PYTHON":',string1.rstrip("HON"))
print('Comparing whether the string is lower:',string1.islower())
print('Comparing whether the string is Upper:',string1.isupper())
print('Comparing whether the string is space:',string1.isspace())
print('Comparing whether the string is alphabetic:',string1.isalpha())

OUTPUT:
The text is HELLO PYTHON
No. of uppercase letters in the string= 12
No. of lowercase letters in the string= 8
To upper: THE TEXT IS HELLO PYTHON
To lower: the text is hello python
Joining ":" between every character: T:h:e: :t:e:x:t: :i:s: :H:E:L:L:O: :P:Y:T:H:O:N
Swapping from Upper case to Lower Case: tHE TEXT IS hello python
Partitioning a piece of text from the string: ('The text is HELLO ', 'PYTHON', '')
Stripping characters from the word "PYTHON": The text is HELLO PYT
Comparing whether the string is lower: False
Comparing whether the string is Upper: False
10 | P a g e
2020 - 21

Comparing whether the string is space: False


Comparing whether the string is alphabetic: False

PROGRAM: 7
#program to create a list
#performs slicing along with built in function.

list1=[]
n=int(input("Enter the number of element of the list : "))
i=0
while i<n:
x=int(input("Enter the element of the list : "))
list1.append(x)
i=i+1
print('The list elements are:',list1)
print('The list Slicing is:',list1[2:5])
print('The length of the list is:',len(list1))
print('The Maximum Value from the list is:',max(list1))
print('The Maximum Value from the list is:', min(list1))
print('The total sum of the values of the list is:',sum(list1))

OUTPUT:

Enter the number of element of the list : 7


Enter the element of the list : 5
Enter the element of the list : 3
Enter the element of the list : 2
Enter the element of the list : 4
Enter the element of the list : 6
Enter the element of the list : 9
Enter the element of the list : 8
The list elements are: [5, 3, 2, 4, 6, 9, 8]
The list Slicing is: [2, 4, 6]
The length of the list is: 7
The Maximum Value from the list is: 9
The Maximum Value from the list is: 2
The total sum of the values of the list is: 37

11 | P a g e
2020 - 21

PROGRAM: 8

#program to create a tuple and perform tuple slicing.

tup=(1,2,3,4,5,6)
t=(7,8,9,)

print('The tuple is:',tup)


print('The values starting from 0:',tup[0:])
print('The values between 2 to 5:',tup[2:5])

print('The length of tuple:',len(tup))


print('The maximum value from tuple is:',max(tup))
print('The minimum value from tuple is:',min(tup))
L1=[1,2,45,65]
print('The creation of tuple from the list[1,2,45,65]:',tuple(L1))

OUTPUT:

The tuple is: (1, 2, 3, 4, 5, 6)


The values starting from 0: (1, 2, 3, 4, 5, 6)
The values between 2 to 5: (3, 4, 5)
The length of tuple: 6
The maximum value from tuple is: 6
The minimum value from tuple is: 1
The creation of tuple from the list[1,2,45,65]: (1, 2, 45, 65)

12 | P a g e
2020 - 21

PROGRAM: 9

#Program to find the square root of the numbers


#Create a list of numbers

number=[1,2,3,4,5,6,7,8,9,10]
squarednumber=()
print ('The squared numbers are:\n')
for number in number:
squarednumber=(number**2)
print('The square of ',number,' is ',squarednumber)

OUTPUT:

The squared numbers are:

The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100

13 | P a g e
2020 - 21

PROGRAM: 10
#Program to find the area and circumference of the circle
#Program to find the area and perimeter of the rectangle
#use of functions for circle and rectangle operation

Circle
import math
defar_circle(r):
returnmath.pi*r*r
defcir_circle(r):
return 2*math.pi*r

Rectangle
defar_rect(l,b):
return l*b
defper_rect(l,b):
return 2*(l+b)

Main Program
import circle
import rectangle
import math

defmainmenu():
print('Menu')
print('1. Area of circle')
print('2. Area of Rectangle')
print('3. Circumference of Circle')
print('4. Perimeter of Circle')
print('5. Quit')
while True:
choice=int(input("Enter your Choice:"))
if(choice==1):
r=float(input("Enter the radius:"))
print ('The area of the Circle is:',circle.ar_circle(r))
print('\n')
mainmenu()
elif(choice==2):
l=float(input("Enter the length:"))
b=float(input("Enter the width:"))
print ('The area of the Rectangle is:',rectangle.ar_rect(l,b))
print('\n')
mainmenu()
elif(choice==3):
14 | P a g e
2020 - 21

r=float(input("Enter the radius:"))


print ('The circumference of the Circle is:',circle.cir_circle(r))
print('\n')
mainmenu()
elif(choice==4):
l=float(input("Enter the length:"))
b=float(input("Enter the width:"))
print ('The perimeter of the Rectangle is:',rectangle.per_rect(l,b))
print('\n')
mainmenu()
elif(choice==5):
print("Program is exiting!!")
break
else:
print("ERROR!!!")
break
exit

mainmenu()

OUTPUT:

Menu
1. Area of circle
2. Area of Rectangle
3. Circumference of Circle
4. Perimeter of Circle
5. Quit
Enter your Choice:1
Enter the radius:5
The area of the Circle is: 78.53981633974483

Enter your Choice:2


Enter the length:5
Enter the width:3
The area of the Rectangle is: 15.0

Enter your Choice:3


Enter the radius:5
The circumference of the Circle is: 31.41592653589793

Enter your Choice:4


Enter the length:5
Enter the width:3
The perimeter of the Rectangle is: 16.0

Enter your Choice:5


Program is exiting!!

15 | P a g e
2020 - 21

PROGRAM: 11

# Program of to find the Factorial of a given number using recursion

defrecurfactorial(n):
if n==1:
return n
else:
return n*recurfactorial(n-1)
num = int(input("Enter a number:"))

if num<0:
print ("The factorail of negative number cannot exist")
elif num==0:
print("The factorial of 0 is 1")
else:
print('The factorial of',num,'is',recurfactorial(num))

OUTPUT:

Enter a number:5
The factorial of 5 is 120

16 | P a g e
2020 - 21

PROGRAM: 12 (1)
# Program to read the text file
#program to implement text file operators.

f=open("test.txt",'r+')
print ("The file that is read is:")
print (f)
print ("File name: ",f.name)
print ("File Mode: ",f.mode)
print ("The file is closed: ",f.closed)
print ("\n")

g=open("test.txt",'r')
print ("The data(only two characters)that is in the file are: ")
data=g.read(2)
print(data)
print ("\n")

h=open("test.txt",'r')
print ("The data that is in the 1st line is: ")
data=h.readline()
print(data)
print ("\n")

i=open("test.txt",'r')
print ("The all data: ")
data=i.readlines()
for line in data:
print(line)

f.close()
print ("The file is closed: ",f.closed)

OUTPUT:

The file that is read is:


<_io.TextIOWrapper name='test.txt' mode='r+' encoding='cp1252'>
File name: test.txt
File Mode: r+
The file is closed: False
The data(only two characters)that is in the file are: Hi
The data that is in the 1st line is: Hi Hello!!!
The all data:

17 | P a g e
2020 - 21

Hi Hello!!!
How r you this morning?
How's Life?
The file is closed: True

PROGRAM: 12 (2)
# Program to write the text file
#program to implement write and append file operators.

f=open("test1.txt",'w')
x=100
f.write("It is the text that is written to the test.txt file.")
f.write("\nThe character size is:")
f.write(str(x))
print ("Text is added to the file successfully!!!!")

line=["\nComputer\n","Information Technology\n","Informatic Practices\n"]


f.writelines(line)
print ("list is added to the file successfully!!!!")
f.close()

g=open("test1.txt",'a')
g.write("\n\nIt is the data that is appended to the text file.")
print ("The data is appended")
g.close()

with open("test1.txt",'a') as h:
h.write("\n\nIt is the data that is appended to the text file using with statement.")
print ("The data is appended using with statement")
g.close()

OUTPUT:

Text is added to the file successfully!!!!


list is added to the file successfully!!!!
The data is appended
The data is appended using with statement

18 | P a g e
2020 - 21

PROGRAM: 13

# Program to write (dump) the binary file


# Program to read (load) the binary file

import pickle

defbndump():
list=[10,20,30,40,50]
f=open('test2.dat','wb')
pickle.dump(list,f)
print("Data added to the binary file")
f.close()
bndump()

defbnload():
g=open('test2.dat','rb')
data=pickle.load(g)
print("\n")
print("The data in the binary file is")
print(data)
g.close()
bnload()

OUTPUT:

Data added to the binary file

The data in the binary file is

[10, 20, 30, 40, 50]

19 | P a g e
2020 - 21

PROGRAM: 14

# Program to copy the content from a file and write on the other.

importos
deffilecopy(file1,file2):
f1=open(file1,'r')
f2=open(file2,'w')
for line in f1:
f2.write(line)
f1.close()
f2.close()

def main():
filename1=input('enter the source file name:')
filename2=input('enter the destination file name:')
filecopy(filename1,filename2)

main()

OUTPUT:

enter the source file name:one.txt


enter the destination file name:second

20 | P a g e
2020 - 21

PROGRAM: 15

#function to capitalize the first 'n' letter of sentence.

defcapitalize_sentence():
f1=open('test_reports.txt','r')
f2=open('file1.txt','w')
while 1:
line=f1.readline() #read a line
if not line:
break # encounter eof
#strip of the new line character and any white space on the right
line=line.rstrip()
linelength=len(line)
str='' #string to concatenate all characters from line
str=str+line[0].upper()
i=1
#loop to check a line to connect uppercase
while i <linelength:
str=str+line[i]
i=i+1
if i>=linelength:
break
str=str+line[i]
i=i+1
f2.write(str)
print ('Conversion done')
else:
print('source file does not exist')
f1.close()
f2.close()

capitalize_sentence()

OUTPUT:

21 | P a g e
2020 - 21

Conversion done
Conversion done

PROGRAM: 16

#sum of 'n' natural number


#to find the time taken using simple method of sum

import time
def sum_n_2(n):
start = time.time() #starting time
sum=0
for i in range (1,n+1):
sum = sum+1
end = time.time() #Ending time
t=end-start #actual time taken
print ('The sum is ',sum,' and time taken is :',t,'seconds')

sum_n_2(100000)

#program to computer sum of 'n' integers


#to find the time taken using (for loop) recursion

import time
start=time.time()
def sum_n_2(n):
return(n+(n+1))/2

end=time.time()
t=end-start
print('The sum is ',(sum_n_2(100000)),' and the time taken is:',t,'seconds')

22 | P a g e
2020 - 21

OUTPUT:
The sum is 100000 and time taken is : 0.0 seconds
The sum is 100000.5 and the time taken is: 0.0 seconds

PROGRAM: 17

#program to add, delete and display the records of an Employee using list
#implementation of stack

Employee=[ ]
c="y"
while (c=="y"):
print ("1. Push")
print("2. Pop")
print("3. Display")
choice= int(input("Enter your choice: "))
if (choice==1):
e_id=input("Enter Employee no.:")
ename=input ("Enter the Employee name :")
emp=(e_id, ename)
Employee.append(emp)
elif (choice==2):
if (Employee==[ ]):
print ("Stack empty")
else:
e_id, ename=Employee.pop()
print("Deleted element is:",e_id, ename)
elif (choice==3):
i=len(Employee)
while i> 0:
print(Employee[i-1])
i=i-1
else:
print("Wrong Input")
c= input("Do you want to continue or not?")

23 | P a g e
2020 - 21

OUTPUT:

1. Push
2. Pop
3. Display
Enter your choice: 1
Enter Employee no.:101
Enter the Employee name :AAAA
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 1
Enter Employee no.:102
Enter the Employee name :BBBB
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 3
('102', 'BBBB')
('101', 'AAAA')
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 2
Deleted element is: 102 BBBB
Do you want to continue or not?y
1. Push
2. Pop
3. Display
Enter your choice: 3
('101', 'AAAA')
Do you want to continue or not?n

24 | P a g e
2020 - 21

PROGRAM: 18

#program to add, delete and display the records of an Employee using list
#implementation of Queue

Library=[ ]
c="y"
while (c=="y"):
print ("1.Insert")
print("2. Delete")
print("3. Display")
choice= int(input("Enter your choice: "))
if (choice==1):
book_id=input("Enter book_id.:")
bname=input("Enter the book name:")
lib=(book_id,bname)
Library.append(lib)
elif (choice==2):
if (Library==[ ]):
print ("Queue empty")
else:
print("Deleted element is:",Library.pop(0))
elif (choice==3):
i=len(Library)
for i in range (0, i):
print(Library[i])
else:
print("Wrong Input")
c= input("Do you want to continue or not?")

25 | P a g e
2020 - 21

OUTPUT:

1.Insert
2. Delete
3. Display
Enter your choice: 1
Enter book_id.:101
Enter the book name:AAAA
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 1
Enter book_id.:102
Enter the book name:BBBB
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 3
('101', 'AAAA')
('102', 'BBBB')
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 2
Deleted element is: ('101', 'AAAA')
Do you want to contunue or not?y
1.Insert
2. Delete
3. Display
Enter your choice: 3
('102', 'BBBB')
Do you want to contunue or not?n

26 | P a g e
2020 - 21

PROGRAM: 19

#python program to calculate the area of regular polygon

from math import tan,pi

nosides=int(input("Enter number of sides: "))


sidelength=float(input("Enter the length of the sides: "))
polyarea=nosides*(sidelength**2)/(4*tan(pi/nosides))
print("The area of the polygon is: ",polyarea)

OUTPUT:
Enter number of sides: 8
Enter the length of the sides: 3
The area of the polygon is: 43.45584412271571

27 | P a g e
2020 - 21

PROGRAM: 20

#program to find the roots of a quadratic equation

from math import sqrt

print("The quadratic equation is: (a*x**2)+b*x+c")


a=float(input("a: "))
b=float(input("b: "))
c=float(input("c: "))

r=b**2-4*a*c
if r>0:
num_roots=2
x1=(((-b)+sqrt(r))/(2*a))
x2=(((-b)-sqrt(r))/(2*a))
print("The two roots are: ",x1, "and",x2)
elif r==0:
num_roots=1
x=(-b)/2*a
print("There is on root:",x)
else:
num_roots=0
print("noroots,discriminant<0")

28 | P a g e
2020 - 21

OUTPUT:
The quadratic equation is: (a*x**2)+b*x+c
a: 2
b: 3
c: 1
The two roots are: -0.5 and -1.0

PROGRAM: 21

#python program to calculate arc length of an angle

import math

defarclength(): #user defined function


diameter=float(input("The diameter of circle:"))
angle=float(input("Angle measure:"))
if angle>=360:
print("The angle is not possible")
return
arc_length=(math.pi*diameter)*(angle/360)
print("The arclength is:",arc_length)

arclength()

29 | P a g e
2020 - 21

OUTPUT:
The diameter of circle:50
Angle measure:90
The arclength is: 39.269908169872416

PROGRAM: 22

#python program to convert a binary number to decimal number


import math
b_num=list(input("Enter binary number:"))
value=0

for i in range(len(b_num)):
digit=b_num.pop()
if digit=="1":
value=value+math.pow(2,i)
print("The decimal value of the number is:",value)

OUTPUT:
Enter binary number:1100
The decimal value of the number is: 12.0

30 | P a g e
2020 - 21

PROGRAM: 23

#python program that takes a list of words and return the length of the longest

def find_longest_word(words_list):
word_len=[]
for n in words_list:
word_len.append((len(n),n))
word_len.sort()
returnword_len[-1][1]

print(find_longest_word(['JSP','Computer','Python3']))

OUTPUT:

31 | P a g e
2020 - 21

Computer

PROGRAM: 24

#python program to capitalize first and last letter of


#each word of a given string

defcapitalize_first_last_letter(str1):
str1=result=str1.title()
result= ""
for word in str1.split():
result+=word[:-1]+word[-1].upper()+ " "
return result[:-1]

print(capitalize_first_last_letter("python string library functions"))


print(capitalize_first_last_letter("implementation"))

32 | P a g e
2020 - 21

OUTPUT:
PythoNStrinGLibrarYFunctionS
ImplementatioN

PROGRAM: 25

#program to swap each character of a given string from lowercase to uppercase


#and vice versa

defswap_case_string(str1):
result_str=""
for item in str1:
ifitem.isupper():
result_str+=item.lower()
else:
result_str+=item.upper()
returnresult_str
print(swap_case_string("String Module in"))
print(swap_case_string("Python"))
print(swap_case_string("Matplotlib Library"))

33 | P a g e
2020 - 21

OUTPUT:
sTRINGmODULE IN
pYTHON
mATPLOTLIBlIBRARY

PROGRAM: 26

#reading a specific line from a file


line_number=4
fo=open("testfile.txt",'r')
currentline=1
for line in fo:
if (currentline==line_number):
print(line)
break
currentline=currentline+1

OUTPUT:
How are you
34 | P a g e
2020 - 21

PROGRAM: 27

#program to read an entire file

filename="testfile.txt"
filehandle=open(filename,'r')
filedata=filehandle.read()
print(filedata)

OUTPUT:

Hello World
35 | P a g e
2020 - 21

Hello Ppython
Good Morning
How are you

PROGRAM: 28
#program for inserting a record in a binary file-student.dat
import pickle
record=[]
while True:
roll_no=int(input("Enter student roll no:"))
name=input("Enter student name:")
marks=int(input("Enter student marks:"))
data=[roll_no,name,marks]
record.append(data)
choice=input("Wish to enter more records(Y/N)?:")
ifchoice.upper() == "N":
break
f=open("D:/student","wb")
pickle.dump(record,f)
print("record added")
f.close()

OUTPUT:

36 | P a g e
2020 - 21

Enter student roll no:101


Enter student name:AAAA
Enter student marks:98
Wish to enter more records(Y/N)?:y
Enter student roll no:102
Enter student name:BBBB
Enter student marks:75
Wish to enter more records(Y/N)?:n
record added

PROGRAM: 29

#program to read record from a file "student.dat"

import pickle
f=open("D:/student",'rb')
stud_rec=pickle.load(f) #to read the object from the opened file
print("Contents of the student file are")
#reading hte field from file
for R in stud_rec:
roll_no=R[0]
name=R[1]
marks=R[2]
print(roll_no,name,marks)
f.close()

37 | P a g e
2020 - 21

OUTPUT:
Contents of the student file are
101 AAAA 98
102 BBBB 75

PROGRAM: 30

#program to read record from a file "student.dat" using search method by roll no

import pickle
f=open("D:/student",'rb')
stud_rec=pickle.load(f) #to read the object from the opened file
found=0
rno=int(input("Enter rollno to search:"))

for R in stud_rec:
roll_no=R[0]
print("Successful search",R[1],"found !")
found=1
break
if found==0:
print("sorry,record not found")
38 | P a g e
2020 - 21

f.close()

OUTPUT:
Enter rollno to search:101
Successful search AAAA found !

PROGRAM: 31

#Program to implement data inserts, modify, search, display and delete


#using dictionary (menu Driven)

Import os
import pickle

#accepting data for dictionary


definsertRec():
rollno=int(input("enter the roll num:"))
name=input("enter the name:")
marks=int(input("enter the marks:"))

#creating the dictionary


rec={"Rollno":rollno,"Name":name,"Marks":marks}
#writing the dictionary
39 | P a g e
2020 - 21

f=open("student.dat","ab")
pickle.dump(rec,f)
f.close()

#reading the records


defreadRec():
f=open("student.dat","rb")
while True:
try:
rec=pickle.load(f)
print("Roll Num:",rec['Rollno'])
print("Nmae:",rec['Name'])
print("Marks:",rec['Marks'])
exceptEOFError:
break
f.close()

#searching the record based on rollno


defsearchRollNo(r):
f=open("student.dat","rb")
flag=False
while True:
try:
rec=pickle.load(f)
if rec['Rollno']==r:
print("Roll Num:",rec['Rollno'])
print("Name:",rec['Name'])
print("Marks:",rec['Marks'])
flag=True
exceptEOFError:
break
if flag==False:
print("no record found")
f.close()

#marks modification for a rollno


40 | P a g e
2020 - 21

defupdateMarks(r,m):
f=open("student.dat","rb")
reclst=[]
while True:
try:
rec=pickle.load(f)
reclst.append(rec)
exceptEOFError:
break
f.close()
for i in range(len(reclst)):
ifreclst[i]['Rollno']==r:
reclst[i]['Marks']=m
f=open("student.dat","wb")
for x in reclst:
pickle.dump(x,f)
f.close()

#deleting a record based on rollno


defdeleteRec(r):
f=open("student.dat","rb")
reclst=[]
while True:
try:
rec=pickle.load(f)
reclst.append(rec)
exceptEOFError:
break
f.close()
f=open("student.dat","wb")
for x in reclst:
if x['Rollno']==r:
continue
pickle.dump(x,f)
f.close()

41 | P a g e
2020 - 21

while True:
print("1: Insert rec")
print("2: Display rec")
print("3: Search rec")
print("4: Update rec")
print("5: Delete rec")
print("Enter your choice 0 to exit")
choice=int(input("Enter your choice:"))
if choice == 0:
break
elif choice == 1:
insertRec()
elif choice == 2:
readRec()
elif choice == 3:
r=int(input("Enter a rollno to search:"))
searchRollNo(r)
elif choice == 4:
r=int(input("Enter a rollno:"))
m=int(input("Enter new marks:"))
updateMarks(r,m)
elif choice == 5:
r=int(input("Enter the rollno:"))
deleteRec(r)

OUTPUT:
1: Insert rec
2: Display rec
3: Search rec
4: Update rec
5: Delete rec
Enter your choice 0 to exit
Enter your choice:1
enter the roll num:101
enter the name:AAA
enter the marks:98
42 | P a g e
2020 - 21

Enter your choice:2


Roll Num: 101
Nmae: AAA
Marks: 98

Enter your choice:3


Enter a rollno to search:101
Roll Num: 101
Name: AAA
Marks: 98

Enter your choice:4


Enter a rollno:101
Enter new marks:75

Enter your choice:5


Enter the rollno:101
Enter your choice:0

PROGRAM: 32

#python program to count the number of record present in "student.csv" File

import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f)#csv_reader is the reader obeject
columns = next(csv_reader)
c=0;
#Reading the student file record by record
for row in csv_reader :
c=c+1
print("No.of record are:",c)

43 | P a g e
2020 - 21

OUTPUT:
No.of record are: 5

PROGRAM: 33

#python program to print record in the form of


#comma separated values

import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f) #csv_reader is the reader obeject
for row in csv_reader:
print(','.join(row))

f.close()

44 | P a g e
2020 - 21

OUTPUT:
Roll,name,Class
101,AA,10
102,BB,9
103,CC,10
104,DD,11
105,EE,12

PROGRAM: 34

#python program to search record for given student


#name from csv file

import csv
f=open("E:\py pr/student.csv",'r')
csv_reader=csv.reader(f) #csv_reader is the reader obeject
name=input("Enter the name to be searched:")
for row in csv_reader:
if(row[0]==name):
print(row)

45 | P a g e
2020 - 21

OUTPUT:

Enter the name to be searched:101


['101', 'AA', '10']

PROGRAM: 35

#Program to write student data onto a csv file


#importing the csv module

import csv
#Field names
fields =['Name', 'class', 'Year', 'Percent']
#data row of csv file
rows = [
['Rohit', 'XII','2003','92'],
['Shaurya','XI','2004','52'],
46 | P a g e
2020 - 21

['Deep', 'XII', '2002','85'],


['Prerna', 'XI, 2006','35'],
['Lakshya', 'XII', '2005','72']
]
#name of csv file
filename ="E:\py pr/marks.csv"
#writing to csv file
with open(filename,'w',newline='') as f:
#By default, newline is '\r\n'
#creating a csv writer object
csv_w=csv.writer (f, delimiter=',')
#writing the fields (the column heading) once
csv_w.writerow(fields)
for i in rows:
#writing the data row-wise
csv_w.writerow (i)
print ("File created")

OUTPUT:
File created

PROGRAM: 36

#Program to write student data onto a csv file


#importing the csv module

import csv
#Field names
fields =['Name', 'class', 'Year', 'Percent']
#data row of cav file
rows = [
['Rohit', 'XII','2003','92'],
47 | P a g e
2020 - 21

['Shaurya','XI','2004','52'],
['Deep', 'XII', '2002','85'],
['Prerna', 'XI, 2006','35'],
['Lakshya', 'XII', '2005','72']
]
#name of csv file

filename ="E:\py pr/newmarks.csv"


#writing to csv file
with open(filename,'w',newline='') as f:
#By default, newline is '\r\n'
#creating a csv writer object
csv_w =csv.writer (f, delimiter=',')
#writing the fields (the column heading) once
csv_w.writerow(fields)
#writing the data row-wise
csv_w.writerow (rows)
print ("All rows written in one go")

OUTPUT:

All rows written in one go

PROGRAM: 37

# to start a new and check the python database connectivity.


importmysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", password="sjvs")
print (mydb)

Output:
<mysql.connector.connection.MySQLConnection object at 0x02DAFBF0>

48 | P a g e
2020 - 21

# To create a new database 'demodatabase' and show from python to mysql


importmysql.connector
mydb=mysql.connector.connect (host="localhost", user="root", password="sjvs")
mycursor =mydb.cursor()
mycursor.execute("CREATE DATABASE demodatabase")
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)

Output:
('information_schema',)
('computer',)
('demodatabase',)
('mysql',)

#to create a table and show the description using python-mysql connectivity.
importmysql.connector
mydb=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database="demodatabase")
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE student(rollnoint(3) Primary key,snamevarchar(15),age
int(3),city char(8))")
mycursor.execute("DESC student")
for x in mycursor:
print(x)

Output:
('rollno', 'int(3)', 'NO', 'PRI', '', '')
('sname', 'varchar(15)', 'YES', '', None, '')
('age', 'int(3)', 'YES', '', None, '')
('city', 'char(8)', 'YES', '', None, '')

PROGRAM: 38
# Program to demonstrate four major operations
#performed on a table through MY-SQL connectivity

def menu():
c='y'
while (c =='y'):
print ('1. add record')
print('2. update record')
49 | P a g e
2020 - 21

print('3. delete record')


print('4. display record')
print('5. Exiting')
choice=int(input("Enter your choice:"))
if choice == 1:
adddata ()
elif choice == 2:
updatedata()
elif choice == 3:
deldata()
elif choice == 4:
fetchdata()
elif choice == 5:
print ("Exiting")
break
else:
print("Wrong input")
c= input("Do you want to contunue or not?")
deffetchdata():
importmysql.connector
try:
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database='computer')
mycursor =db.cursor()
mycursor.execute("select * FROM student")
for x in mycursor:
print(x)
except:
print("Error: unable to fetchdata")

defadddata():
importmysql.connector
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database="computer")
mycursor =db.cursor()
mycursor.execute("INSERT INTO student VALUES('Ritu',4000,'science',354,'B',11)")
mycursor.execute("INSERT INTO student VALUES('Akush',6000,'commerce',256,'A',12)")
mycursor.execute("INSERT INTO student VALUES('Pihu',3566,'Humanities',458,'C',11)")
mycursor.execute("INSERT INTO student VALUES('Tinku',8900,'science',457,'A',12)")
db.commit()
print("Records added")

50 | P a g e
2020 - 21

defupdatedata():
importmysql.connector
try:
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database='computer')
mycursor =db.cursor()
sql=("update student set stipend=5000 where name='Ritu'")
mycursor.execute(sql)
print ("Record Updated")
db.commit()
except Exception as e:
print (e)

defdeldata():
importmysql.connector
db=mysql.connector.connect (host="localhost", user="root",
password="sjvs",database='computer')
mycursor =db.cursor()
sql=("delete FROM student where name='Ritu'")
mycursor.execute(sql)
print ("Record Deleted")
db.commit( )

menu()

OUTPUT:

Do you want to contunue or not?y


1. add record
2. update record
3. delete record
4. display record
51 | P a g e
2020 - 21

5. Exiting
Enter your choice:1
Records added

Enter your choice:2


Record Updated

Enter your choice:3


Record Deleted

Enter your choice:4


('Akush', 6000, 'commerce', 256, 'A', 12)
('Pihu', 3566, 'Humanities', 458, 'C', 11)
('Tinku', 8900, 'science', 457, 'A', 12)
Enter your choice:5
Exiting

52 | P a g e

You might also like