You are on page 1of 94

Practical file

Of
Computer science

SESSION 2020-21
BY- AMAN KUMAR

UNDER THE GUIDANCE OF


MR. N. CHANDRASHEKHAR

FOR THE PARTIAL FULLFILMENT


CLASS- 12 CBSE

SUBMITTED TO
JAWAHARLAL NEHRU SCHOOL
BHEL, BHOPAL

1|Page
CERTIFICAT
E
This is to certify that Aman Kumar has
successfully completed the Practical File with the
help of Python programming language and
MySQL under my guidance.

I am satisfied with his initiatives and efforts for the


completion of this Project File as a part of CBSE
class 12 examination.

Date: / /
Place: Bhopal

_______________ _________________
Signature of internal Signature of external
Examiner Examiner
2|Page
Acknowledgement

I would like to present my special thanks of


gratitude to the principal of our school Mr. N.
Chandrasekhar sir for providing me her
precious guidance.

I would also thanks to Mr. N Chandrashekhar


sir for this wonderful and joyous collaborative
work. Without his guidance I would not be
able to complete me file.

At last, I would present my hearty regards to


my Dear Parents for supporting me in my
work and last to my Best Friend for motivating
me to do my work properly.

~AMAN KUMAR

3|Page
4|Page
Term-1
Python

CONTENTS
5|Page
Section A- Python
1. Bubble sort.
2. Insert Sort.
3. Check whether the given sting is Palindrome or
not.
4. Conversion of Octal no. to Decimal, Binary and
Hexadecimal number.
5. To print A.P. of 4 terms.
6. Capitalizing first letter in the paragraph.
7. Conversion to nearest integer.
8. Encrypting String.
9. Read a poem prints its size in bytes and number
of lines.
10.Store Roll number, Name and Marks with in
marks.txt.
11.Copy source source.txt to target.txt barring the
lines starting with # symbol.
12.To print a string in backward direction.
13.To use a recursive function to calculate ab.
14.To binary search in an array.
15.To linear search in an array.
16.Insert an element from a linear list.
17.Delete an element from a linear list.
18.Creating a csv fie by suppressing the EOL
transition.
19.Reading and displaying the contents of a file.

DOCUMENTATION
6|Page
Name of the
program: Program-1
Description of the program: Sorting an
unsorted list using bubble sort feature in
python

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def
bubble_sort(list1):

7|Page
for i in
range(0,len(list1)-1):
for j in
range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1

list1 = [5, 3, 8, 6, 7, 2]

print("Unsorted list: ", list1)


print("Sorted list: ",
bubble_sort(list1))

OUTPUT

8|Page
DOCUMENTATION
Name of the
program: Program-2

9|Page
Description of the program: Sorting an
unsorted list using insertion sort feature
in python

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def
insertionsort(arr):
for i in
range(1,len(arr)):
key=arr[i]
j=i-1 while j>=0
and key < arr[j]:

arr[j+1]=arr[j]
10 | P a g e
j=-1
arr[j+1]=key

arr=[12,10,3,17,30]
insertionsort(arr)

print("Sorted
array is:") for i in
range(len(arr)):
print("%d"%arr[i])

OUTPUT

11 | P a g e
DOCUMENTATION

Name of the
program: Program-3

12 | P a g e
Description of the program: Checking
whether the given string is same while
writing in backward direction or not, i.e.,
to check whether the given string is
palindrome or not using python
programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def
ispalindrome(s
): return
s==s[::-1]

13 | P a g e
s="malayalam"
ans=ispalindrome(s)

if ans:

print("
Yes")
else:
print("
No")

OUTPUT

14 | P a g e
DOCUMENTATION

Name of the
program: Program-4
15 | P a g e
Description of the program: Converting
an octal number in
a decimal, binary and a hexadecimal
number using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
# Conversion of octal to
decimal def OctToDec(n):
return int(n, 8);
if __name__ ==
'__main__': n=
"345";

16 | P a g e
print(OctToDec(n))
;

# Conversion of octal to
hexadecimal octnum = "345"
decnum = int(octnum, 8)
hexadecimal =
hex(decnum).replace("0x", "")
print(hexadecimal)

# Conversion of octal to
binary def
OctToBin(octnum):
binary = ""
while
octnum != 0:
d = int(octnum
% 10) if d == 0:
binary = "".join(["000", binary])
elif d == 1:
binary = "".join(["001",
binary]) elif d == 2:
binary = "".join(["010",
binary]) elif d == 3:
binary = "".join(["011", binary])
elif d == 4:

17 | P a g e
binary = "".join(["100",
binary]) elif d == 5:
binary = "".join(["101",
binary]) elif d == 6:
binary =
"".join(["110",binary]) elif d
== 7:
binary = "".join(["111",
binary]) else:
binary = "Invalid
Octal Digit" break
octnum = int(octnum / 10)
return binary

octnum = 345 bin =


"" +
OctToBin(octnum)
print(bin)

OUTPUT

18 | P a g e
DOCUMENTATION

19 | P a g e
Name of the
program: Program-5
Description of the program: Writing an A.P.
of 4 terms
having first term and common difference
of our own choice using python
programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
a=int(input("Enter the first
term:")) d=int(input("Enter the
common difference:")) n=int
20 | P a g e
(input("Enter the number of
terms:"))

m=1

while m<=n:
T=a+
(m-1)*d
m=m+1
print(T)

OUTPUT

21 | P a g e
DOCUMENTAION

Name of the
program: Program-6

22 | P a g e
Description of the program: Capitalizing
the first letter in the paragraph using
python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

name="""a Teacher is a great source of


Knowledge, Prosperity and
Enlightenment by which anybody can be

23 | P a g e
Benefited and without Teachers it is
almost Impossible to Imagine Growth in
our Life whether Educationally, Mentally
or Intellectually."""

print(name.capitalize())

OUTPUT

24 | P a g e
DOCUMENTATION

Name of the
program: Program-7

25 | P a g e
Description of the program: Converting a
rational number
to the nearest integer using python
programming

Operating system:
Windows 10
Version of Python IDLE:
3.9.6

CODING
valueA =
3.14159265359
valueB =
1845.7409947
valueC = -100.95
valueD = 9.5432
valueE =
34.49953
26 | P a g e
roundA =
round(valueA) roundB
= round(valueB)
roundC =
round(valueC) roundD
= round(valueD)
roundE =
round(valueE)

print("Value:".ljust(15), "Rounded:")
print(str(valueA).ljust(15), roundA)
print(str(valueB).ljust(15), roundB)
print(str(valueC).ljust(15), roundC)
print(str(valueD).ljust(15), roundD)
print(str(valueE).ljust(15), roundE)

OUTPUT

27 | P a g e
DOCUMENTATION

Name of the
program: Program-8
Description of the program: Encrypting a
string using python programming

28 | P a g e
Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

encrypt = "Vaibhav" dict = {"a":


"0", "e": "1", "i": "2", "o": "2", "u":
"3"}
num = encrypt[::-1]
for i in dict:
num = num.replace(i, dict[i])
print(f"{num}aca")

29 | P a g e
OUTPUT

30 | P a g e
DOCUMENTATION
Name of the program:
Program-9

Description of the program: Reading a poem from


a text file and printing its size and number of lines
using python programming

31 | P a g e
Version of Python
IDLE: 3.9.6

CODING
def counter(fname): num_lines = 0
num_charc = 0 with open(fname, 'r')
as f: for line in f:
num_lines += 1 word = 'Y'
for letter in line: for i in
letter: if(i !=" " and i !

32 | P a g e
="\n"): num_charc
+= 1 print("Number of lines in text
file:", num_lines) print('Size of the
text file:', num_charc, 'bytes')

if __name__ == '__main__':
fname =
'file.txt'
try:
counter(fnam
e) except:
print('File not found')

OUTPUT

33 | P a g e
DOCUMENTATION

Name of the
program: Program-10

34 | P a g e
Description of the program: Storing roll
number, name and marks in marks.txt file
using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

import csv fh =
open("marks.csv", "w")
stuwriter = csv.writer(fh)

35 | P a g e
stuwriter.writerow(['Rollno',
'Name', 'Marks'])

for i in range(4):
print("Student
record", (i+1)) rollno =
int(input("Enter rollno:
")) name =
input("Enter name: ")
marks =
float(input("Enter marks:
")) s = [rollno, name,
marks]
stuwriter.writerow(s)

fh.close()
OUTPUT

36 | P a g e
DOCUMENTATION
37 | P a g e
Name of the
program: Program-11
Description of the program: Copying
source.txt file to target.txt file barring the
lines starting with # symbol using python
programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def copyfiles():

s=open("source.txt","
38 | P a g e
r")
t=open("target.txt","
w") while True:

d=s.readline()
if len(d)==0:

break
if
d[0]=='#':
continue
t.write(d)
s.close()
t.close()

OUTPUT

39 | P a g e
DOCUMENTATION
40 | P a g e
Name of the
program: Program-12
Description of the program: Printing a
string in backwards
direction using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

41 | P a g e
def
reverse(str)
: str =
str[::-1]
return str

s = "Vaibhav"

print ("Original string: ",s) print ("Reversed


string: ",reverse(s))

OUTPUT

42 | P a g e
DOCUMENTATION

43 | P a g e
Name of the
program: Program-13
Description of the program: Using a
recursive function to
calculate ab using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

44 | P a g e
def power(N,
P): if P
== 0:
return 1
elif P == 1:
return N
else:
return (N*power(N, P-1))

N=5
P=2

print(power(N, P))

OUTPUT
45 | P a g e
DOCUMENTATION

Name of the
program: Program-14

46 | P a g e
Description of the program: Searching in
an array using binary search function in
python

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def binary_search(arr, low, high, x):
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
return mid elif
arr[mid] > x:
return binary_search(arr, low, mid - 1, x)
else:

47 | P a g e
return binary_search(arr, mid + 1, high, x)
else:
return -1

arr = [ 2, 3, 4, 10, 40 ] x = 10 result =


binary_search(arr, 0, len(arr)-1, x) if result != -
1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")

OUTPUT

48 | P a g e
DOCUMENTATION

49 | P a g e
Name of the
program: Program-15
Description of the program: Searching in
an array using linear search function in
python

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING
def
linear_Search(arr, n,
key): for i in
50 | P a g e
range(0, n):
if (arr[i] == key):
return i
return -1

arr = [10, 30, 50, 40, 70,


90] key = 70

n = len(arr) result =
linear_Search(arr, n,
key)

if(result == -1):
print("Element not
found") else:
print("Element found at index", result)

OUTPUT

51 | P a g e
DOCUMENTATION
52 | P a g e
Name of the
program: Program-16
Description of the program: Inserting an
element in a sorted
a list using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

53 | P a g e
def
findpos(ar,item
):
size=len(ar)
if item<ar[0]:
return 0
else:
pos=-1 for i in
range(size-1): if
(ar[i]<=item and item<ar[i+1]):
pos=i+1
break if(pos==-1
and i<=size-1):
pos=size
return pos

def shift(ar,pos):
ar.append(None)
size=len(ar)
i=size-1

54 | P a g e
while i>=pos:
ar[i]=ar[i-1]
i=i-1

mylist=[10,20,30,40,50,60,70,80,90]
print("List in sorted order") print(mylist)
item=int(input("\nEnter new element to
be inserted: "))
position=findpos(mylist,item)
shift(mylist,position)
mylist[position]=item print("\nList after
inserting new element") print(mylist)

55 | P a g e
OUTPUT

56 | P a g e
DOCUMENTATION

Name of the
program: Program-17
Description of the program: Deleting an
element in a sorted
a list using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

57 | P a g e
def deleteElement(arr, n, key):
pos = binarySearch(arr, 0, n -
1, key) if (pos == -1):
print("Element not
found") return n
for i in range(pos,n - 1):
arr[i] = arr[i + 1] return n -
1

def binarySearch(arr, low,


high, key): if (high <
low): return -
1 mid = (low + high)
// 2 if (key ==
arr[mid]):
return mid if (key >
arr[mid]):
return binarySearch(arr, (mid + 1),
high, key) return binarySearch(arr, low,
(mid - 1), key)

58 | P a g e
arr = [3, 10, 12,
17, 30] n =
len(arr) key = 3

print("Array before
deletion") for i in
range(n):

print(arr[i],end=" ") n
= deleteElement(arr,
n, key)

print("\n\nArray after
deletion") for i in range(n):
print(arr[i],end=" ")

59 | P a g e
OUTPUT

60 | P a g e
DOCUMENTATION

Name of the
program: Program-18
Description of the program: Creating a
csv file by suppressing the EOL translation
using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

61 | P a g e
import csv fh =
open("student.csv", "w",
newline= '') ewwriter =
csv.writer(fh) empdata = [
['Rollno','Name','Sex','Subject'],
['12129','Kushagra','M','PCM+CS'],
['12136','Rishabh','M','PCM+CS'],
['12141','Someshwar','M','PCM+CS'],
['12145','Vaibhav','M','PCM+CS'],
]
ewwriter.writerows(empdata)
print("File successfully created")
fh.close()

OUTPUT
62 | P a g e
Rollno Name Sex Subject
12129 Kushagra M PCM+CS
12136 Rishabh M PCM+CS
12141 Someshwar M PCM+CS
12145 Vaibhav M PCM+CS

DOCUMENTATION

63 | P a g e
Name of the
program: Program-19
Description of the program: Reading and
displaying the contents of an already
created file in Program-18
“student.csv” using python programming

Operating system:
Windows 10
Version of Python
IDLE: 3.9.6

CODING

64 | P a g e
import csv with
open("student.csv","r") as fh:
ereader = csv.reader(fh)
print("File student.csv
contains :") for rec in
ereader:
print(rec)

OUTPUT

65 | P a g e
Term-2
66 | P a g e
Python +
MySQL

Contents
1.Implementation of stack Operations.
2.Implementation of Queue Operations.
3.Implementation of CircularQ.
4.Program on Recursive Function.

67 | P a g e
5.Program on Radomization of a number.
6.Establish connectivity of Python and MySQL.
7.Add a record in SQL Table.
8.Update record in SQL Table.
9.Delete a record from SQL Table
10.Demo of Python and SQL.
(a) Add
(b) Update
(c) Delete
(d) Display

DOCUMENTATION

Name of the Program:


Program-20

68 | P a g e
Description of the program: Implementation of
Stack Operations.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

Coding
#Menu Driven Program to implement

#Stack Operations Using LIst.

def isEmpty(stk):

if stk==[]: #Or if len(stk)==0

return True

else:

return False

69 | P a g e
def Push(stk,elt):

stk.append(elt)

print("Element inserted...")

print(stk)

def Pop(stk):

if isEmpty(stk):

print("Stack is Empty...Underflow Case...")

else:

print("Deleted Element is:",stk.pop())

def Peek(stk):

if isEmpty(stk):

print("Stack is Empty....")

else:

print("Element at Top of the Stack:",stk[-1])

def Display(stk):

a=stk[::-1]

print(a)

Stack=[]

while True:

print("........STACK OPERATIONS.......")

print("1.PUSH")

print("2.POP")

print("3.PEEK")

print("4.DISPLAY")

print("5.EXIT")

ch=int(input("Enter your choice:"))

if ch==1:

element=int(input("Enter the element which you want to push:"))

Push(Stack,element)

if ch==2:

Pop(Stack)

if ch==3:

Peek(Stack)

70 | P a g e
if ch==4:

Display(Stack)

elif ch==5:

break

Output

71 | P a g e
DOCUMENTATION

72 | P a g e
Name of the program:
Program-21
Description of the Program: Implementation of
Queue Operations.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

Coding
#Menu Driven Program to implement
#Queue Operations Using List.

73 | P a g e
def isEmpty(q):
if q==[]: #OR len(q)==0
return True
else:
return False
def Enqueue(q,elt):
q.append(elt)
print("Element inserted in a queue...")
def Dequeue(q):
if isEmpty(q):
print("Underflow Case....Queue is Empty....")
else:
print("Element deleted from the Queue:",q.pop(0))
def Peek(q):
if isEmpty(q):
print("Queue is Empty...")
else:
print("Element at Front=",q[0])
def Display(q):
if isEmpty(q):
print("Queue is Empty...")
else:
for i in range(len(q)):
print(q[i],end=' ')
print()
Queue=[]
while True:
print(".......QUEUE OPERATIONS......")
print(" 1. ENQUEUE")

74 | P a g e
print(" 2. DEQUEUE")
print(" 3. PEEK")
print(" 4. DISPAY")
print(" 5. EXIT")
ch=int(input("Enter your choice:"))
if ch==1:
element=int(input("Enter element to be inserted:"))
Enqueue(Queue,element)
elif ch==2:
Dequeue(Queue)
elif ch==3:
Peek(Queue)
elif ch==4:
Display(Queue)
elif ch==5:
break
else:
print("Incorrect Choice...")

output

75 | P a g e
DOCUMENTATION
76 | P a g e
Name of the program: Program-22
Description of the Program: Implementation of
Circular Queue.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

Coding
# Python3 program for insertion and

77 | P a g e
# deletion in Circular Queue

# Structure of a Node

class Node:

def __init__(self):

self.data = None

self.link = None

class Queue:

def __init__(self):

front = None

rear = None

# Function to create Circular queue

def enQueue(q, value):

temp = Node()

temp.data = value

if (q.front == None):

q.front = temp

else:

q.rear.link = temp

q.rear = temp

q.rear.link = q.front

# Function to delete element from

# Circular Queue

def deQueue(q):

if (q.front == None):

print("Queue is empty")

return -999999999999

# If this is the last node to be deleted

value = None # Value to be dequeued

if (q.front == q.rear):

value = q.front.data

q.front = None

q.rear = None

else: # There are more than one nodes

78 | P a g e
temp = q.front

value = temp.data

q.front = q.front.link

q.rear.link = q.front

return value

# Function displaying the elements

# of Circular Queue

def displayQueue(q):

temp = q.front

print("Elements in Circular Queue are: ",end = " ")

while (temp.link != q.front):

print(temp.data, end = " ")

temp = temp.link

print(temp.data)

# Driver Code

if __name__ == '__main__':

# Create a queue and initialize

# front and rear

q = Queue()

q.front = q.rear = None

# Inserting elements in Circular Queue

enQueue(q, 14)

enQueue(q, 22)

enQueue(q, 6)

# Display elements present in

# Circular Queue

displayQueue(q)

# Deleting elements from Circular Queue

print("Deleted value = ", deQueue(q))

print("Deleted value = ", deQueue(q))

# Remaining elements in Circular Queue

displayQueue(q)

79 | P a g e
enQueue(q, 9)

enQueue(q, 20)

displayQueue(q)

Output

80 | P a g e
DOCUMENTATION

Name of the Program: Program-23

81 | P a g e
Description of the program: Program on Recursive
Function.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

Coding
# Program to print the fibonacci series upto n_terms
# Recursive function
def recursive_fibonacci(n):

82 | P a g e
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) +
recursive_fibonacci(n-2))
n_terms = 10
# check if the number of terms is valid
if n_terms <= 0:
print("Invalid input ! Please input a positive value")
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))

output

83 | P a g e
DOCUMENTAION

84 | P a g e
Name of the Program: Program-24
Description of the Program: Program on
Randomisation of a number.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

coding
# Python code to demonstrate the working of

85 | P a g e
# choice() and randrange()

# importing "random" for random operations


import random

# using choice() to generate a random number from a


# given list of numbers.
print("A random number from list is : ", end=" ")
print(random.choice([1, 4, 8, 10, 3]))

# using randrange() to generate in range from 20


# to 50. The last parameter 3 is step size to skip
# three numbers when selecting.
print("A random number from range is : ", end=" ")
print(random.randrange(20, 50, 3))

output

86 | P a g e
DOCUMENTATION

87 | P a g e
Name of the program: Program-25
Description of the program: Establish connectivity
of Python and MySQL.

Operating System: Windows 10


Version of Python IDLE: 3.9.6

CODING
#inserts data in the table.

import mysql.connector as c

con=c.connect(host="localhost",

88 | P a g e
user="root",

passwd="jns",

database="abcd")

cursor=con.cursor()

while True:

code=int(input("Enter Code:"))

name=input("Enter Name:")

salary=int(input("Enter Salary:"))

query="Insert into emp values({},'{},'{})".format(code,name,salary)

cursor.execute(query)

con.commit()

print("Data Inserted Successfully..")

x=int(input("1->Enter More\n2->Exit\nEnter Choice:"))

if x==2:

break

OUTPUT

89 | P a g e
90 | P a g e
91 | P a g e
92 | P a g e
93 | P a g e
94 | P a g e

You might also like