[go: up one dir, main page]

0% found this document useful (0 votes)
523 views65 pages

Prcatical File - Aditi Mahale XII C

This program writes instances of a Student class to a file. It defines a Student class with roll number and name attributes. It then uses the pickle module to write Student object instances to a file called "student.log".

Uploaded by

Aditi Mahale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
523 views65 pages

Prcatical File - Aditi Mahale XII C

This program writes instances of a Student class to a file. It defines a Student class with roll number and name attributes. It then uses the pickle module to write Student object instances to a file called "student.log".

Uploaded by

Aditi Mahale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Academic Year: 2020-21

Name of the candidate: Aditi Suyog Mahale


Class: XII
Roll no.:
1|Page
CERTIFICATE

This is to certify that Aditi Mahale of class XII-C has


successfully completed this computer science practical
file prescribed by Mrs Gargy Dam, during the academic
session 2020-2021 as per the guidelines issued by
Central Board of Secondary Examination.

Signature of internal examiner Signature of external examiner

Signature of principal with school stamp

2|Page
INDEX

SrNo. Programs Signature Pg. No

1 Program to enter the number of terms and create a 6-7


Fibonacci series.

2 Program to display ASCII code of a character and 8-9


vice versa.

3 Create a dictionary whose keys are month and 10-11


values are number of days in corresponding
months.
a) Ask the user to enter a month name and use the
dictionary to:
b) Print all keys in alphabetical order
c) Print all months with 31 days
d) Print out key: value pairs sorted by number of
days in each month.

4 Program to input a number and check if a number 12-13


is Armstrong number or not

5 To create a pie chart for sequence, con = 14-15


[23.4,17.8,25,34,40] for zones = [East, West, North,
South, Central].
a) Show north zones value exploded
b) Display percentage contribution for each zone
c) Pie chart should be circular
d) Assign colours to every zone
e) Give a suitable title

6 Program to create multiple bar charts 16-18

3|Page
7 Program to create a line chart using NumPy 19-20

8 Program to perform read an append operation with 20-21


csv file.

9 Program to write instances of class Student onto a 23-25


file namely student.log

10 Program to read instances of class Student from a file 26-28


student.log

11 Program to reads a file containing integers sorted in 29-31


ascending order and then asks the user to enter
integers to search for

12 Program to execute bubble sort function 32-33

13 Program to implement all stack operations 34-38

14 Program to implement all queue operations 39-44

15 Program to write a function that takes two numbers 45-46


and returns the number that has minimum one's
digit 

16 Program to write a function that receives an octal 47-48


number and prints the equivalent number in other
number bases, i.e., decimal, binary and hexadecimals
equivalents

17 Program that generates 4 terms of an AP by providing 49-50


initial and step values to a function that returns first
four terms of the series

4|Page
18 Program, to create a module length conversion.py 51-52
that stores function for various length conversion, i.e.,
mile to km, inch to ft, etc. It should store constant
values and help() should display proper information

19 Program that inputs a main string and then creates 53-54


an encrypted string by embedding a short symbol-
based string after each character. The program
should also be able to produce the decrypted string
from the encrypted string

20 Program to create a module shape.py and find area 55-56


of circle, rectangle and cylinder

21 Program to create a table in SQL using python 57

22 Program to insert data into a table in SQL using 58-59


python

23 Program to display selected data from a table in 60-61


SQL using python

24 Program to update data in a table in SQL using 62-63


python

25 Program to delete data from a table in SQL using 64-65


python

5|Page
Program 1
Source code:

# program to enter number of term and create Fibonacci series.

No1=1
No2=2
print(‘’,+No1)
print(‘\n’,+No2)
x=1
while (x<=10):
No3=No1+No2
No1=No2
No2=No3
print(‘\n’,+No3)
x=x+1

6|Page
Output:

7|Page
Program 2
Source code:

# program to display ASCII code of a character and vice versa

var=True
while var:
choice=int(input(“Press – 1 to find the ordinal value of a character \n
Press – 2 to find a character of a value \n”))
if choice==1:
character=input(“Enter a character: ”)
print(ord(character))
elif choice==2:
value=int(input(“Enter an integer: ”))
print(chr(value))
else:
print(“You have entered wrong choice”)

print(“Do you want to continue? Y/N”)


option=input()
if option==‘Y’ or option==‘y’:
var=True
else:
var=False

8|Page
Output:

Program 3
9|Page
Source code:

# create a dictionary whose keys are months and values are number
of days in the corresponding month

Dm={‘January’:31, ‘February’:28, ‘March’:31, ‘April’:30, ‘May’:31,


‘June’:30,
‘July’:31, ‘August’:30, ‘September’:31, ‘October’:30,
‘November’:31, ‘December’:30}
#a)
month=input(“Enter month: ”)
print(“Number of days in”, month, “are”, Dm[month])
print(“**********************”)
#b)
for i in sorted(Dm.keys()):
print(i)
print(“***********************”)
#c)
for i in Dm:
if Dm[i]=31:
print(i)
print(“************************”)
#d)
for i in sorted(Dm,key=Dm.get):
print(I,Dm[i])
10 | P a g e
Output:

Program 4
11 | P a g e
Source code:

#program to check if the number is an Armstrong number or not

# take input from the user


num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

12 | P a g e
Output:

Program 5
13 | P a g e
Source code:

# program to create a pie chart for sequence, con =


[23.4,17.8,25,34,40] for zones = [East, West, North, South, Central]

import matplotlib.pyplot as pl
con = [23.4,17.8,25,34,40]
zones = [‘East’, ‘West’, ‘North’, ‘South’, ‘Central’]

ex = [0,0,0.2,0,0]
col = [‘r’, ‘b’, ‘g’, ‘y’, ‘p’]

pl.axis(“equal”)
pl.title(“Zones”)

pl.pie(con, labels = zones, explode = ex, autopct = “%5d”)


pl.show()

14 | P a g e
Output:

Program 6
15 | P a g e
Source code:

# program to create multiple bar charts

import numpy as np
import matplotlib.pyplot as plt

#set width of bar


barwidth = 0.25

#set height of bar


bar1 = [12, 30, 1, 8, 22]
bar2 = [28, 6, 16, 5, 10]
bar3 = [29, 3, 24, 12, 36]

#set position of bar on x-axis


r1 = np.arange(len(bar1))
r2 = [x+barwidth for x in r1]
r3 = [x+barwidth for x in r2]

#make the plot

16 | P a g e
plt.bar(r1, bar1, colour = 'r', width = barwidth, edgecolor = 'white',
label = 'var1')
plt.bar(r2, bar2, colour = 'y', width = barwidth, edgecolor = 'white',
label = 'var2')
plt.bar(r3, bar3, colour = 'b', width = barwidth, edgecolor = 'white',
label = 'var2')

#add sticks on the middle of the group bars


plt.xlabel('group', fontweight = 'bold')
plt.title("Multiple bar charts", fontweight = 'bold')
plt.xticks([r+barwidth for r in range(len(bar1))],['A', 'B', 'C', 'D', 'E'])

#create legend and show graphic


plt.legend()
plt.show()

17 | P a g e
Output:

Program 7

18 | P a g e
Source code:

# program to create a line chart using NumPy

import matplotlib.pyplot as pl
import numpy as np

x = np.arange(0, 10, 0.1)


a = np.cos(x)
b = np.sin(x)

pl.plot(x, a, 'x', linestyle = 'dashed', linewidth = 0.5)


pl.plot(x, b, 'b', linestyle = 'dashed', linewidth = 3)

pl.show()

19 | P a g e
Output:

Program 8
20 | P a g e
Source code:

# program to perform read and append operation with csv file

import csv
def readcsv():
with open(‘data1.csv’, ‘r’) as f:
data = csv.reader(f) #reader function to generate a
reader object
for row in data:
print(row)

def appendcsv():
with open(‘data1.csv’, ‘a’) as file:
append = csv.writer(file, delimiter = ‘,’)
#write new record in file
append.writerow([321, “Aman”, “Arts”])
file.close()

print(“Press -1 to read data and Press -2 to add data: ”)


a=int(input())
if a==1:
readcsv()
elif a==2:

21 | P a g e
appendcsv()
else:
print(“Invalid value”)

Output:

Program 9
22 | P a g e
Source code:

#program to write instances of class Student onto a file namely


student.log

import pickle
class Student:
def __init__(self, rno, name =""):
self.rollNo = rno
self.name = name
self.marks1, self.marks2, self.marks3 = 0.0 ,0.0 ,0.0

def readMarks(self):
print("Enter marks of three subjects")
self.marks1 = float(input("Subject1: "))
self.marks2 = float(input("Subject2: "))
self.marks3 = float(input("Subject3: "))

def display(self):
print("Student details are: ")
print("Roll number: ", self.rollNo)
print("Name: ", self.name)
23 | P a g e
print("Marks in 3 subjects: ", self.marks1, self.marks2,self.marks3)

stud1 = Student(13, "Rohan") #object created


stud2 = Student(15, "Nitya") #object created
stud1.readMarks()
stud2.readMarks()

file1=open("Student.log","wb")

pickle.dump(stud1 ,file1)
pickle.dump(stud2, file1)

file1.close()

Output:

24 | P a g e
Program 10
Source code:
25 | P a g e
#program to read instances of class Student from a file student.log

import pickle
class Student:
def __init__(self,rno = 0, name = ""):
self.rollNo = rno
self.name = name
self.marks1, self.marks2, self.marks3 = 0, 0, 0

def readMarks(self):
print("Enter marks of three subjects: ")
self.marks1 = float(input("Subject1: "))
self.marks2 = float(input("Subject2: "))
self.marks3 = float(input("Subject3: "))

def display(self):
print("Student details are: ")
print("Roll number: ", self.rollNo)
print("Name: ", self.name)
print("Marks in 3 subjects: ", self.marks1, self.marks2, self.marks3)

26 | P a g e
stud1 = Student()
file1 = open("Student.log","rb")
try:
while True:
stud1 = pickle.load(file1)
stud1.display()
except EOFError:
file1.close()

Output:

27 | P a g e
Program 11
Source code:

28 | P a g e
# program to reads a file containing integers sorted in ascending
order and then asks the user to enter integers to search for

#binary search program

def binary_search (arr,low,high,x):

#check base case


if high >= low:

mid = (high+low)//2

#if element is present at middle itself


if arr[mid] == x:
return mid

#if element is smaller than mid, then it can only be present in left sub
array
elif arr[mid] > x:
return binary_search (arr,low,mid-1,x)

#else the element can only be present in right sub array


else:

29 | P a g e
return binary_search (arr,mid+1,high,x)

else:
#element is not present in the array
return -1
#input array

arr = [2,3,1,10,40,54,67,86]
x = int(input("Enter the searched element: "))

#function call for binary search

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 found in array")

Output:

30 | P a g e
Program 12
Source code:

31 | P a g e
#program to execute bubble sort function
#bubble sort function

def bubble_sort(lst):

#transverse through all list elements


for i in range (1, len(lst)):

#transverse the list from 0th index till lenght-1


for j in range (0, len(lst)-i):

#transverse the list from 0 to size of list-i-1


#swap if the element is greater than the next element
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]

#driver code to test above


lst = [3,2,1,5,4]
bubble_sort (lst) #calling bubble sort function

print ("Sorted list is: ", lst)

Output:

32 | P a g e
Program 13
Source code:

33 | P a g e
#program to implement all stack operations

def isEmpty(stack):
if stack==[]:
return True
else:
return False

def push(stack,x): #function to add element at the end


of the list
stack.append(x)
top=len(stack)-1m

def pop(stack): #function of remove last element from


the list
if isEmpty(stack): #calling function isEmpty
return "Underflow"
else:
item=stack.pop()
if len(stack)==0:
top=None
else:
top=len(stack)-1

def display(stack): #function to display stack


34 | P a g e
if isEmpty(stack): #calling function isEmpty
print("Stack empty.........Nothing to display")
else:
top=len(stack)-1
print(stack[top],"<-----top")
for i in range(top-1,-1,-1):
print(stack[i],end="\n")

def peek(stack):
if isEmpty(stack): #calling function isEmpty
return "Underflow"
else:
top=len(stack)-1
return stack[top]

#main program starts from here


stack=[] #initially stack is empty
top=None
choice=0
while (choice!=5):
print("\n******STACK MENU******")
print("1.Push(INSERT)")
print("2.Pop(DELETE)")
print("3.Display Stack")

35 | P a g e
print("4.Peek")
print("5.EXIT")
choice=int(input("Enter your choice: "))

if (choice==1):
value=int(input("Enter value: "))
push(stack,value) #calling push function

if (choice==2):
item=pop(stack) #calling pop function
if item=="Underflow":
print("Underflow! Stack is empty")
else:
print("Popped item is", item)

if (choice==3):
display(stack) #calling display function

if (choice==4):
item=peek(stack) #calling peek function
if item=="Underflow":
print("Underflow! Stack is empty")
else:
print("Topmost item is: ", item)

36 | P a g e
if (choice==5):
print("You have selected to close this program")

Output:

37 | P a g e
Program 14
38 | P a g e
Source code:

#program to implement all queue operations

def isEmpty(Qu):
if Qu==[]:
return True
else:
return False

#function to add item to queue


def Enqueue(Qu,item):
Qu.append(item)
if len(Qu)==1:
front=rear=0
else:
rear=len(Qu)-1

#function to delete item from stack


def Dequeue(Qu):
if isEmpty(Qu):
return "Underflow"
else:
item=Qu.pop()

39 | P a g e
if len(Qu)==0:
front=rear=None
return item

#function to see item from queue


def Peek(Qu):
if isEmpty(Qu):
return "Underflow"
else:
front=0
return Qu[front]

#function to display queue


def Display(Qu):
if isEmpty(Qu):
print("Queue empty!")
elif len(Qu)==1:
print(Qu[0], "<==front,rear")
else:
front=0
rear=len(Qu)-1
print(Qu[front], "<-front")
for a in range(1,rear):
print(Qu[a])

40 | P a g e
print(Qu[rear],"<-rear")

#main program
queue=[] #intially queue is empty
front=None
while True:
print("*****Queue Menu*****")
print("1.Add element")
print("2.Delete element")
print("3.Peek")
print("4.Display queue")
print("EXIT")
ch=int(input("Enter your choice"))

if ch==1:
item=int(input("Enter value: "))
Enqueue(queue,item)
input("Press Enter to continue...")

elif ch==2:
item=Dequeue(queue)
if item=="Underflow":
print("Underflow! Queue is empty")

41 | P a g e
else:
print("Dequeued item is: ",item)
input("Press Enter to continue...")

elif ch==3:
item=Peek(queue)
if item=="Underflow":
print("Queue is empty")
else:
print("Foremost item is: ",item)
input("Press Enter to continue...")

elif ch==4:
Display(queue)
input("Press Enter to continue...")

elif ch==5:
break

else:
print("Invalid choice")
input("Press Enter to continue...")

Output:
42 | P a g e
43 | P a g e
44 | P a g e
Program 15
Source code:

#program to write a function that takes two numbers and returns


the number that has minimum one's digit 

#function to take two numbers and returns the number that has
minimum one's digit
def min(x , y ) :
a = x % 10
b = y % 10
if a < b :
return x
else :
return y

#main program
first = int(input("Enter first number = "))
second = int(input("Enter second number = "))

print ( "Minimum one's digit number = " , min( first , second ) )

45 | P a g e
Output:

46 | P a g e
Program 16
Source code:

#program to write a function that receives an octal number and


prints the equivalent number in other number bases, i.e., decimal,
binary and hexadecimals equivalents

#function to convert octal number into decimal, binary and


hexadecimal
def oct2others(n):
print("Passed octal number: ",n)
numString=str(n)
decNum=int(numString,8)

print("Number in decimal: ", decNum)


print("Number in binary: ",bin(decNum))
print("Number in hexadecimal: ",hex(decNum))

#main program
num=int(input("Enter an octal number: "))
oct2others(num)

47 | P a g e
Output:

48 | P a g e
Program 17
Source code:

#program that generates 4 terms of an AP by providing initial and


step values to a function that returns first four terms of the series

#function to generate AP series


def retSeries(init,step):
return init, init+step, init+2*step, init+3*step

#main program
ini=int(input("Enter initial value of the AP series: "))
st=int(input("Enter step value of the AP series: "))

print("Series with initial value", ini, "& step value", st, "goes as: ")

t1,t2,t3,t4 = retSeries(ini,st)

print(t1,t2,t3,t4)

49 | P a g e
Output:

50 | P a g e
Program 18
Source code:

#program, to create a module length conversion.py that stores


function for various length conversion, i.e., mile to km, inch to ft,
etc. it should also store constant values and help() should display
proper information.

#lenghtconversion.py
"""This module stores various conversion functions to convert
distances into different lengths"""

def miletokm(d):
"""Returns miles converted to kilometres"""
return d*one_mile

def kmtomile(d):
"""Returns kilometres converted to miles"""
return d/one_mile

def feettoinches(ln):
"""Returns feet converted to inches"""
return ln*one_feet

def inchestofeet(ln):
"""Returns inches converted to feet"""
return ln/one_feet

#constant
one_mile=1.6093
one_feet=12
51 | P a g e
#main program
import lenghtconversion as pl
help(pl)

Output:

52 | P a g e
Program 19
Source code:

#program that inputs a main string and then creates an encrypted


string by embedding a short symbol-based string after each
character.

def encrypt(sttr,enkey):
return enkey.join(sttr)

def decrypt(sttr,enkey):
return sttr.split(enkey)

#main program
mainString=input("Enter main string: ")
encryptStr=input("Enter encryption key: ")

enStr=encrypt(mainString,encryptStr)
deLst=decrypt(enStr,encryptStr)

#deLst is in the form of a list, converting it to string below

deStr="".join(deLst)

53 | P a g e
print("The encrypted string is: ", enStr)
print("String after decryption is: ", deStr)

Output:

54 | P a g e
Program 20
Source code:

# Program to create a module shape.py and find area of circle, rectangle


and cylinder

#this is a module shape.py


def areacircle(r):
return 3.14*r*r
def arearectangle(a,b):
return a*b
def areacylinder(r,h):
return 2*3.14*r*(r+h)

#main program
import shape
x=int(input("Input radius: "))
print("Area of circle is: ")
print(shape.areacircle(x))

l=int(input("Enter length: "))


h=int(input("Enter height: "))
print("Area of rectangle is: ")
print(shape.arearectangle(l,h))

55 | P a g e
r=int(input("Enter radius: "))
h=int(input("Enter height: "))
print("Area of cylinder is: ")
print(shape.areacylinder(r,h))

Output:

56 | P a g e
Program 21
Source code:

#program to create a table in SQL using python

import mysql.connector as sql


mydb = sql.connect(host="localhost", user="root",
passwd="aditi123", database="practical_file")
mycursor = mydb.cursor()
mycursor.execute("create table STUDENT(Rollno int, Name
varchar(20), Class varchar(3), City varchar(20), Marks int)")
mydb.close()

Output:

57 | P a g e
Program 22
Source code:

import mysql.connector as sql


mydb = sql.connect (host = "localhost", user = "root", passwd =
"aditi123", database ="practical_file")

mycursor = mydb.cursor()

endata = "insert into STUDENT(Rollno, Name, Class, City, Marks)


values(%s, %s, %s, %s, %s)"

val = [(1,'Nanda','X','Agra',550), (2,'Saurabh','XII','Mumbai',489),


(3,'Sanal','XI','Delhi',398), (4,'Trisha','XII','Delhi',356),
(5,'Neha','XII','Jaipur',231)]

mycursor.executemany(endata,val)

mydb.commit()

print(mycursor.rowcount, "rows were inserted")

58 | P a g e
Output:

59 | P a g e
Program 23
Source code:

#program to display selected data from a table in SQL using python

import mysql.connector as sql


mydb = sql.connect(host = "localhost", user = "root", passwd =
"aditi123", database = "practical_file")

mycursor = mydb.cursor()

mycursor.execute("select * from student order by Name")


rows = mycursor.fetchall()

c = mycursor.rowcount
print("Total number of rows: ",c)

for row in rows:


print(row)
mydb.close()

60 | P a g e
Output:

61 | P a g e
Program 24
Source code:

#program to update data in a table in SQL using python

import mysql.connector as sql


mydb = sql.connect(host = "localhost", user = "root", passwd = "aditi123",
database = "practical_file")
mycursor = mydb.cursor()

mycursor.execute("update student set Name='{}', City='{}' where


Rollno={}".format('Arya','Allahabad',3))

mycursor.execute("select * from student")


rows = mycursor.fetchall()
c = mycursor.rowcount
for row in rows:
print(row)
print("Total number of rows: ",c)

mydb.commit()
mydb.close()

62 | P a g e
Output:

63 | P a g e
Program 25
Source code:

#program to delete data from a table in SQL using python

import mysql.connector as sql


mydb = sql.connect(host = "localhost", user = "root", passwd = "aditi123",
database = "practical_file")
mycursor = mydb.cursor()

mycursor.execute("delete from student where Rollno=1")


mycursor.execute("select * from student")
rows = mycursor.fetchall()
c = mycursor.rowcount
for row in rows:
print(row)

mydb.commit()
mydb.close()

64 | P a g e
Output:

65 | P a g e

You might also like