Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
311 views

Computer Science With Python Practical File

This document contains a practical file submitted by Sneha Chaudhary for the subject Computer Science with Python as per CBSE guidelines. It includes 27 Python programs on various topics like functions, loops, conditions, lists, tuples, dictionaries, files handling etc. It also contains SQL queries and a Python program for database connectivity. The teacher's signature is required on the completed programs.

Uploaded by

Sneha Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
311 views

Computer Science With Python Practical File

This document contains a practical file submitted by Sneha Chaudhary for the subject Computer Science with Python as per CBSE guidelines. It includes 27 Python programs on various topics like functions, loops, conditions, lists, tuples, dictionaries, files handling etc. It also contains SQL queries and a Python program for database connectivity. The teacher's signature is required on the completed programs.

Uploaded by

Sneha Chaudhary
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

2020-21

PRACTICAL FILE
AS PER CBSE GUIDELINES

THIS PRACTICAL FILE SUBMITTED FOR FULFILMENT OF SUBJECT

COMPUTER SCIENCE WITH


PYTHON

SUBMITTED BY: SUBMITTED BY:

NAME : Sneha Chaudhary Ms. Ekta


Taneja
CLASS : XII-E PGT
Computer
ROLL NO : Science
SUB CODE : 083
SNEHA CHAUDHARY Page 1
SNEHA CHAUDHARY Page 2
CERTIFICATE

This is to certify that SNEHA


CHAUDHARY of class XII-E (PCM
WITH COMPUTER SCIENCE) has
satisfactorily completed the laboratory
work in COMPUTER SCIENCE(083)
Python laid down in the regulations of
CBSE for the purpose of AISSCE
Practical Examination 2020-21.

TEACHER’S SIGNATURE:

.........................................

SNEHA CHAUDHARY Page 3


CONTENTS
S.No. PROGRAMS TEACHER’S
SIGNATURE
PROGRAMMING IN PYTHON
1 Write a program in python to create four function calculator
2 Write a program to generate the table of a given number using
loop.
3 Write a program to generate the table of a given number using
loop.
4 Write a program to calculate factorial of a inputted number by
using function
5 Write a program to check whether number is Armstrong or not.
6 Write a program to check whether number is perfect or not.
7 Write a program to generate Fibonacci series in a tuple.
8 Write a program to input a string and count the number of
uppercase and lower case letters.
9 Write a program to find the maximum ,minimum and mean
value from the inputted list.
10 Write a program to store student’s information like admission
number,roll number,name and marks in a dictionary.And
display information on the basis of admission number.
11 Write a program for bubble sort by using function.
12 Write a program for insertion sort by using function.
13 Write a Python program by using function that prints the first n
rows of Pascal’s triangle.
14 Write a program to remove duplicate characters of a given
string.
15 Write a python program to find the highest 3 value in a
dictionary.
16 Write a python program to count number of items in a
dictionary value that is list.

SNEHA CHAUDHARY Page 4


17 Write a python program to sort a list alphabetically in a
dictionary.
18 Write a python program to sort a dictionary by key.
19 Write a Program to check whether number is palindrome or
not by using function
20 Write a python program to print reverse of string and check
Whether string is palindrome or not.
21 W22rite a python program by using method to find and display
the prime numbers between 2 to N.Pass N as argument to the
method.
22 Write a python program by using function named
zeroending(scores) to add all those values in the list of
scores,which are ending with zero(0) and display the sum.

For eg,score=[200,456,300,100,234,678]

The sum should be displayed as 600.

23 Write a program to calculate the volume and area of a sphere


inside separate modules and import them in one complete
package
Volume=4/3𝜋𝑟3 𝑎𝑛𝑑 surfacearea=4πr2
24 Write a program to read a text file line by line and display each
word separated by a #
25 Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
26 Create a binary file with name and roll number. Search for a
given roll number and display the name, if not found display
appropriate message.
27 Create a binary file with roll number, name and marks. Input a
roll number and update the marks.
28 Remove all the lines that contain the character `a' in a file and
write it to another file

SNEHA CHAUDHARY Page 5


29 Write a program to read and display content of file from end to
beginning.
30 .Write a program to read a file ‘story.txt’ and create another
file,storing an index of story.txt,telling which line of the file
each word appears in.If word appears more than once,then
index should show all the line numbers containing the word.
31 A file sports.dat contains information in following format:

Event-Participants

Write a function that would read contents from the file


sports.dat and create a file name Atheletic.dat copying only
those records from sports.dat where the event name is
“Athletics

32 Write a program that Illustrate the working of deleting the


record from binary file
33 Create a CSV file that store the information of roll num ,name
and marks in three subjects of student
34 Write a random number generator that generates random
numbers between 1 and 6 simulates a dic
35 Implement a Python program to add ,delete and display the
records of an Employee through Stack.
36 Write a python program to display unique vowels present in
the given word using Stack.

SQL QUERIES
37 LOANS table queries
38 COMPANY & MODEL table queries
39 STOCK & DEALER table queries
40 PRODUCTS & SUPPLIERS table queries
41 SHOP & ACCESSORIES table queries

SNEHA CHAUDHARY Page 6


Python with database connectivity
programs
42 ABC Infotech Pvt. Ltd. needs to store, retrieve and delete the
records of its employees. Develop an interface that provides
front-end interaction through Python, and stores and updates
records using MySQL.
The operations on MySQL table “emp” involve reading,
searching, updating and deleting records of employees

SNEHA CHAUDHARY Page 7


PROGRAMMING

IN
PYTHON

PROGRAM 1:
Write a program in python to create four
function calculator.
SNEHA CHAUDHARY Page 8
CODING
result=0
val1=float(input("Enter value 1:"))
val2=float(input("Enter value 2:"))
op=input("Enter any of the operator(+,-,*,/):")
if op=="+":
result=val1+val2
elif op=="-":
if val1>val2:
result=val1-val2
else:
result=val2-val1
elif op=="*":
result=val1*val2
elif op=="/":
if val2==0:
print("Please enter a value other than 0")
else:
result=val1/val2
else:
print("Please enter any one of the operator (+,-,*,/):")
print("The result is:",result)

OUTPUT
SNEHA CHAUDHARY Page 9
PROGRAM 2:
Write a program to generate the table of a
given number using loop.
SNEHA CHAUDHARY Page 10
CODING

num=4
for i in range (1,11):
print (num,'x',i,'=',num*i)

OUTPUT

PROGRAM 3:
Write a program to print cubes of number in
the range 10 to 18.

SNEHA CHAUDHARY Page 11


CODING

for i in range(10,18):
print("Cube of number",i,end='')
print("is:",i**3)

OUTPUT

PROGRAM 4:
Write a program to calculate factorial of a
inputted number by using function.

SNEHA CHAUDHARY Page 12


CODING
def fact(num):
if num==1:
return num
else:
return num*fact(num-1)
n=int(input("ENTER NUMBER YOU WANT TO FIND
FACTORIAL OF:"))
result=fact(n)
print("THE FACTORIAL OF A NUMBER IS:",result)

OUTPUT

PROGRAM 5:
Write a program to check whether number is
Armstrong or not.
SNEHA CHAUDHARY Page 13
CODING
num=int(input("Enter 3 digit number:"))
f=num
sum=0
while(f>0):
a=f%10
f=int(f/10)
sum=sum+(a**3)
if(sum==num):
print("It is an Armstrong number:",num)
else:
print("It is not an Armstrong number:",num)

OUTPUT

PROGRAM 6:
Write a program to check whether a number
is Perfect or not.
SNEHA CHAUDHARY Page 14
CODING
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")

OUTPUT

PROGRAM 7:
Write a program to generate Fibonacci series
in a tuple.
SNEHA CHAUDHARY Page 15
CODING
nterms=int(input("Fibonacci sequence up to:"))
n1=0
n2=1
count=0
tup=()
if nterms<=0:
print("Please enter a positive integer")
elif nterms==1:
("Fibonacci sequence up to",nterms,":")
print(n1)
else:
print("Fibonacci sequence up to",nterms,":")
while count<nterms:
tup=tup+(n1,)
nth=n1+n2
n1=n2
n2=nth
count+=1
print(tup)

OUTPUT

SNEHA CHAUDHARY Page 16


PROGRAM 8:

SNEHA CHAUDHARY Page 17


Write a program to input a string and count
the number of uppercase and lowercase
letters.

CODING
str1=input("Enter the string:")
print(str1)
uprcase=0
lwrcase=0
i=0
while i<len(str1):
if str1[i].islower()==True:
lwrcase+=1
if str1[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)

OUTPUT

SNEHA CHAUDHARY Page 18


PROGRAM 9:
SNEHA CHAUDHARY Page 19
Write a program to find the maximum,
minimum and mean value from the inputted
list.
CODING
list1=[]
n=int(input("Enter the elements of the list:"))
i=0
while i<n:
x=int(input("Enter the elements in the list:"))
list1.append(x)
i=i+1
print(list1)

maximum=max(list1)
minimum=min(list1)
mean=sum(list1)/len(list1)
print("Maximum value is =",maximum)
print("Minimum value is =",minimum)
print("Mean value is =",mean)

OUTPUT

SNEHA CHAUDHARY Page 20


PROGRAM 10:
SNEHA CHAUDHARY Page 21
Write a program to store student’s information
like admission number, roll number, name and
marks in a dictionary, and display information on
the basis of admission number.
CODING
SCL=dict()
i=1
flag=0
n=int(input("Enter number of entries:"))
while i<=n:
Adm=input("\nEnter admission no of a student:")
nm=input("Enter nameof the student:")
section=input("Enter class and section:")
per=float(input("Enter percentage of a student:"))
b=(nm,section,per)
SCL[Adm]=b
i=i+1
l=SCL.keys()

for i in l:
print("\nAdmno-",i,":")
z=SCL[i]
print("Name\t","class\t","per\t")
for j in z:
print(j,end="\t")

SNEHA CHAUDHARY Page 22


OUTPUT

PROGRAM 11:
SNEHA CHAUDHARY Page 23
Write a program for bubble sort by using
function.

CODING
def main():
l=[64,53,12,78,43,98]
n=len(l)
print("Original List:",l)
for i in range (n-1):
for j in range (n-i-1):
if l [j] > l [j+1]:
l [j], l[j+1]= l[j+1], l[ j]
print("List after sorting is:",l)

OUTPUT

PROGRAM 12:
SNEHA CHAUDHARY Page 24
Write a program for insertion sort by using
function.

CODING
a=[70,54,89,32,54,12,98]
print("Original List:",a)
for i in a:
j=a.index(i)
while j>0:
if a [j-1] > a [j]:
a[j-1], a[j]= a[j], a[ j-1]
else:
break
j=j-1
print("List after sorting is:",a)

OUTPUT

PROGRAM 13:
SNEHA CHAUDHARY Page 25
Write a Python program by using function
that prints the first n rows of Pascal’s
triangle.
CODING
def pascal_triangle():
n = int(input("Enter the number: "))
trow=[1]
y=[0]
for x in range (max(n,0)):
print(trow)
trow=[l+r for l,r in zip (trow+y,y+trow)]
return n>=1

OUTPUT

PROGRAM 14:
SNEHA CHAUDHARY Page 26
Write a program to remove duplicate
characters of a given string.

CODING
s=input("Enter a String:")
i=0
s1=" "
for x in s:
if s.index(x)==i:
s1+=x
i+=1
print (s1)

OUTPUT

PROGRAM 15:
SNEHA CHAUDHARY Page 27
Write a python program to find the highest 3
value in a dictionary.

CODING
# By using nlargest.heapq() function
from heapq import nlargest
my_dict = {'T': 23, 'U': 22, 'P': 21,'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
print(val, " : ", my_dict.get(val))

OUTPUT

PROGRAM 16:
SNEHA CHAUDHARY Page 28
Write a python program to count number of
items in a dictionary value that is list.
CODING
def main():
d = {'A' : [1, 2, 3, 4, 5, 6, 7, 8, 9],
'B' : 34,
'C' : 12,
'D' : [7, 8, 9, 6, 4] }
# using the in operator
count = 0
for x in d:
if isinstance(d[x], list):
count += len(d[x])
print(count)
# Calling Main
if __name__ == '__main__':
main()

OUTPUT

PROGRAM 17:
SNEHA CHAUDHARY Page 29
Write a python program to sort a list
alphabetically in a dictionary.
CODING
dict={'d1': [2, 3, 1], 'd2': [5, 1, 2], 'd3': [3, 2, 4]}
print("\nBefore Sorting:")
for x in dict.items():
print (x)
print("\nAfter Sorting:")
for i,j in dict.items():
sorted_dict={i:sorted(j)}
print (sorted_dict)

OUTPUT

PROGRAM 18:
SNEHA CHAUDHARY Page 30
Write a python program to sort a dictionary
by key.

CODING
a = {'5':'Riya' ,'4':'Priya' ,'6':'Siya' ,'1':'Anisha' ,'3':'Nisha' ,'2':'Isha' }
print(sorted(a.keys()))
print(sorted(a.items()))

OUTPUT

PROGRAM 19:

SNEHA CHAUDHARY Page 31


Write a Program to check whether number is
palindrome or not by using function.
CODING
def rev(temp):
remainder = 0
reverse = 0
while(temp != 0):
remainder = temp % 10
reverse = reverse * 10 + remainder
temp = int(temp / 10)
return reverse

#main() function
n = int(input("Enter the number: "))
temp = n
res = rev(temp)
if (res == n):
print("Palindrome")
else:
print("Not a Palindrome")

OUTPUT

SNEHA CHAUDHARY Page 32


PROGRAM 20:
SNEHA CHAUDHARY Page 33
Write a python program to print reverse of
string and check whether string is
palindrome or not.
CODING
str=input(("Enter a string:"))
reversedString=[]
index = len(str) {#Reverse program}

while index > 0:


reversedString += str[ index - 1 ]
index = index - 1 print(reversedString)

if (str==str[::-1]): {#palindrome program}

print("The string is a palindrome")


else:
print("Not a palindrome")

OUTPUT

PROGRAM 21:
SNEHA CHAUDHARY Page 34
Write a python program by using method to find
and display the prime numbers between 2 to N.
Pass N as argument to the method.
CODING

start = 2
n = int(input("ENTER THE NUMBER UPTOWHICH YOU WANT
PRIME NUMBERS:"))
for val in range(start, n + 1):
if val > 1:
for j in range(2, val//2 + 2):
if (val % j) == 0:
break
else:
if j == val//2 + 1:
print(val)

OUTPUT

PROGRAM 22:
SNEHA CHAUDHARY Page 35
Write a python program by using function
named zeroending(scores) to add all those
values in the list of scores,which are ending
with zero(0) and display the sum.
For eg,score=[200,456,300,100,234,678]
The sum should be displayed as 600.

CODING
def ZeroEnding( SCORES):
s=0
for i in SCORES:
if i%10==0:
s=s+i
print (s)

OUTPUT

PROGRAM 23:
SNEHA CHAUDHARY Page 36
Write a program to calculate the volume and
area of a sphere inside separate modules
and import them in one complete package.
Volume=4/3 π r ∧¿surfacearea=4πr2
3

CODING
#CREATING DIRECTORY

import os
os.mkdir("geometry")

#CREATING MODULES IN GEOMETRY PACKAGE

#area module
def sphere_area(r):
return 4*3.14*r**2

#volume module
def sphere_volume(r):
return 4/3*3.14*r**3

#CREATING __init__.py File:

SNEHA CHAUDHARY Page 37


#_init_.py file
from area_module import sphere_area
from volume import sphere_volume

#IMPORTING PACKAGE AND USING ATTRIBUTES

from geometry import area_module,volume


print(area_module.sphere_area(6))
print(volume.sphere_volume(10))

OUTPUT

#Creating directory

#area module inside geometry package

SNEHA CHAUDHARY Page 38


#volume module inside geometry package

#Creating __init__.py file:

#Importing package and using attributes

SNEHA CHAUDHARY Page 39


SNEHA CHAUDHARY Page 40
PROGRAM 24:
Write a program to read a text file line by
line and display each word separated by a #.

CODING
file=open("python.txt","r")
lines=file.readlines()
for line in lines:
print(line)

file=open('python.txt','r')
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()

SNEHA CHAUDHARY Page 41


OUTPUT

PROGRAM 25:
SNEHA CHAUDHARY Page 42
Read a text file and display the number of
vowels/ consonants/ uppercase/ lowercase
characters in the file.

CODING
file=open("python.txt","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if(ch in['a', 'e', 'i', 'o', 'u','A','E','I','O','U']):
vowels+=1
elif(ch in ['q','w','r','t','y','p','s','d','f','g','h','j','k','l','z','x','c', 'v','b','n','m',
'Q','W','R','T','Y','P','S','D','F','G','H', 'J',
'K','L','Z','X','C','V','B','N','M']):
consonants+=1
file.close()

SNEHA CHAUDHARY Page 43


print("VOWELS ARE:",vowels)
print("CONSONANTS ARE:",consonants)
print("LOWER CASE LETTERS ARE:",lower_case_letters)
print("UPPER CASE LETTERS ARE:",upper_case_letters)

OUTPUT

PROGRAM 26:
SNEHA CHAUDHARY Page 44
Create a binary file with name and roll
number. Search for a given roll number and
display the name, if not found display
appropriate message.
CODING
import pickle
import sys
dict={}
def write_in_file():
file=open("student.dat","ab")
no=int(input("Enter number of students:"))
for i in range (no):
print("Enter student",i+1,"details")
dict["roll"]=int(input("Enter the roll number:"))
dict["name"]=input("Enter the name:")
pickle.dump(dict,file)
file.close()
def display():
file=open("student.dat","rb")
try:
while True:
stud=pickle.load(file)
print(stud)
except EOFError:
SNEHA CHAUDHARY Page 45
pass
file.close()
def search():
file=open("student.dat","rb")
r=int(input("Enter the roll number to search"))
found=0
try:
while True:
data=pickle.load(file)
if data["roll"]==r:
print("Record found successfully...")
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("Record not found...")
file.close()

#main program
while True:
print("Menu \n 1-Write in a file \n 2-Display \n 3-Search \n 4-Exit \
n")
ch=int(input("Enter your choice:"))

SNEHA CHAUDHARY Page 46


if ch==1:
write_in_file()
if ch==2:
display()
if ch==3:
search()
if ch==4:
print("Thank you😊")
sys.exit()

OUTPUT

SNEHA CHAUDHARY Page 47


SNEHA CHAUDHARY Page 48
SNEHA CHAUDHARY Page 49
PROGRAM 27:
Create a binary file with roll number, name
and marks. Input a roll number and update
the marks.

CODING
f=open('s1','w+b')
n=int(input('Enter number of students:'))
for i in range(n):
name=input('Enter name of student:')
rollno=input('Enter rollno:')
marks=input('Enter marks:')
bname=bytes(name,encoding='utf-8')
brollno=bytes(rollno,encoding='utf-8')
bmarks=bytes(marks,encoding='utf-8')
f.write(brollno)
f.write(bname)
f.write(bmarks)
f.write(b'\n')

f.seek(0)
data=f.read()

SNEHA CHAUDHARY Page 50


f.seek(0)
sk=input('Enter the roll no whose marks need updatation :')
bsk=bytes(sk,encoding='utf-8')
l=len(bsk)
loc=data.find(bsk)
if loc<0:
print('Details not present')
else:
f.seek(loc+l,0)
i=0
while f.read(1).isalpha():
i=i+1
f.seek(-1,1)
marksu=input('Enter updated marks:')
bmarksu=bytes(marksu,encoding='utf-8')
f.write(bmarksu)
print("Entire content of file after updation is :")
f.seek(0)
udata=f.read()
print(udata.decode())

SNEHA CHAUDHARY Page 51


OUTPUT

SNEHA CHAUDHARY Page 52


PROGRAM 28:
Remove all the lines that contain the
character `a' in a file and write it to another
file.
CODING
file=open("python.txt","r")
lines=file.readlines()
file.close()

file=open("python.txt","w")
file1=open("py.txt","w")
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("All line that contains a character a has been removed from
python.txt file.")
print("All line that contains a character a has been saved in py.txt
file.")
file.close()
file1.close()

SNEHA CHAUDHARY Page 53


OUTPUT

SNEHA CHAUDHARY Page 54


PROGRAM 29:
Write a program to read and display content
of file from end to beginning.
CODING
f=open("test.txt","r")
data=f.read()
print(data)
f.close

OUTPUT
#Text document

SNEHA CHAUDHARY Page 55


PROGRAM 30:
Write a program to read a file ‘story.txt’ and
create another file,storing an index of
story.txt,telling which line of the file each
word appears in.If word appears more than
once,then index should show all the line
numbers containing the word.

CODING
def f(u):
t=open("story.txt","r")
y=open("ss.txt","a")
c=t.readlines()
line=""
for i in c:
if u in i.split():
line+="Line "+str(c.index(i))+','
k=u+" "*10+line
y.write(k+'\n')
t.close()
y.close()

SNEHA CHAUDHARY Page 56


u=open("test.txt","r")
c=u.read()
c=c.split()
c=list(set(c))
for i in c:
f(i)
print("Done successfully")
u.close()

OUTPUT

#text file

SNEHA CHAUDHARY Page 57


SNEHA CHAUDHARY Page 58
SNEHA CHAUDHARY Page 59
PROGRAM 31:
A file sports.dat contains information in
following format:
Event-Participants
Write a function that would read contents
from the file sports.dat and create a file
name Atheletic.dat copying only those
records from sports.dat where the event
name is “Athletics”.

CODING
f1=open("sports.dat","r")
f2=open("Atheletic.dat","w")
s=" "
while s:
s=f1.readline()
s1=s.split('-')
if s1[0].lower()=='Atheletic':
f2.write(s+'\n')
print("Done successfully")
f1.close()
f2.close()
SNEHA CHAUDHARY Page 60
OUTPUT
#sports.dat file in txt form

SNEHA CHAUDHARY Page 61


PROGRAM 32:
Write a program that Illustrate the working of
deleting the record from binary file.
CODING
import os
import pickle
roll=int(input("Enter roll to be deleted"))
f=open("student.dat","rb")
f1=open("temporary.dat","wb")
try:
while True:
s=pickle.load(f)
if s[0]!=roll:
pickle.dump(s,f1)
except:
f1.close()
f.close()
os.remove("binary.dat")
os.rename("temporary.dat","binary.dat")

OUTPUT

SNEHA CHAUDHARY Page 62


PROGRAM 33:
Create a CSV file that store the information
of roll num, name and marks in three
subjects of students
CODING
import csv
f=open("E12_CSV.csv","a")
csv_write=csv.writer(f)
ans='y'
while ans=='Y' or ans=='y':
l=[]
roll=int(input("Enter roll number:"))
l.append(roll)
name=input("Enter name:")
l.append(name)
marks=[]
for i in range(0,3):
x=float(input("Enter marks:"))
marks.append(x)
l.append(marks)
csv_write.writerow(l)
ans=input("ENTER Y/y to continue:")
f.close()

SNEHA CHAUDHARY Page 63


f=open("E12_CSV.csv","r")
csv_reader=csv.reader(f)
for line in csv_reader:
print(line)
f.close()

OUTPUT

SNEHA CHAUDHARY Page 64


E12_CSV.csv file

SNEHA CHAUDHARY Page 65


PROGRAM 34:
Write a random number generator that
generates random numbers between 1 and 6
simulates a dice.
CODING
import random
n=random.randrange(1,(6+1),1)
print('the number between 1 between 6 is:',n)

OUTPUT

SNEHA CHAUDHARY Page 66


PROGRAM 35:
Implement a Python program to add, delete
and display the records of an Employee
through Stack.

CODING
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:

SNEHA CHAUDHARY Page 67


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?")

OUTPUT

SNEHA CHAUDHARY Page 68


SNEHA CHAUDHARY Page 69
PROGRAM 36:
Write a python program to display unique
vowels present in the given word using Stack.
CODING
vowels=['a','e','i','o','u','A','E','I','O','U']
word=input("Enter the word to search for vowels:")
Stack=[]
for letter in word:
if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print("The number of different vowels present
in",word,"is",len(Stack))

OUTPUT

SNEHA CHAUDHARY Page 70


SQL
QUERIES

SNEHA CHAUDHARY Page 71


PROGRAM 37:
Consider a database with the following table:
Table: LOANS

Answer the following questions.


1. Display the sum of all Loan Amount whose Interest rate is
greater than 10.
CODING
Select sum(Loan_Amount)FROM loans where Interest>10;
OUTPUT

2. Display the Maximum Interest Rate from Loans table.


CODING
select Max(Interest)from loans;

SNEHA CHAUDHARY Page 72


OUTPUT

3. Display the count of all loan holders whose name ends


with ‘Sharma’.
CODING
Select count(*) from loans where Cust_Name
like'%Sharma';
OUTPUT

4. Display the count of all loan holders whose Interest is


NULL.
CODING
Select count(*) from loans where Interest is NULL;
OUTPUT

SNEHA CHAUDHARY Page 73


5. Display the Interest-wise details of Loan Account Holders.
CODING
Select*from loans Group By Interest;
OUTPUT

6. Display the Interest-wise details of Loan Account Holders


with at least 10 installments remaining.
CODING
Select*from loans Group By Interest Having
Instalmaents>=10;
OUTPUT

SNEHA CHAUDHARY Page 74


PROGRAM 38:
Consider the following tables: COMPANY &
MODEL
Table: COMPANY

Note:
 Comp_ID is the Primary Key.
Table: MODEL

Note:
 Model_ID is the Primary Key.
 Comp_ID is the Foreign Key referencing
Comp_ID of Company table.

SNEHA CHAUDHARY Page 75


1. To display the details of all models in the Model table in
ascending order of DateOfManufacture.
CODING
select*from model order by DateOfManufacture;
OUTPUT

2. To display the details of those models manufactured in


2011 and whose Cost is below 2000.
CODING
select*from model where year(DateOfManufacture)=2011
and cost<2000;
OUTPUT

SNEHA CHAUDHARY Page 76


3. To decrease the cost of all the models in Model table by
15%.
CODING
update model set cost=cost-0.15*cost;
OUTPUT

OUTPUT FOR THE FOLLOWING QUESTIONS

4. Select COUNT(Distinct CompHO)from Company;


OUTPUT

SNEHA CHAUDHARY Page 77


5. Select CompName, contact(‘Mr.’,ContactPerson)from
Company where CompName ends with ‘a’;
OUTPUT

SNEHA CHAUDHARY Page 78


PROGRAM 39:
Consider a database with the following table:
STOCK and DEALER.
Table: Stock

Note:
 ItemNo is the Primary Key.
 Dcode is the Foreign Key refrencing Dcode of
Dealer table.
Table: Stock

Note:
 Dcode is the Primary Key.

SNEHA CHAUDHARY Page 79


a.Write SQL commands for the following
statements.
1. To display details of all the items in the Stock table in
ascending order of StockDate.
CODING
select*from stock order by stockdate;
OUTPUT

2. To display the ItemNo and Item name of those items from


Stock table whose UnitPrice is more than Rs 10.
CODING
select ItemNo,Item from STOCK where UnitPrice>10;
OUTPUT

SNEHA CHAUDHARY Page 80


3. To display details of those items whose dealer code
(Dcode) is 102 or Quantity in Stock(Qty) is more than 100
from the table Stock.
CODING
select*from stock where Dcode=102 or Qty>100;
OUTPUT

4. To display Maximum UnitPrice of items for each dealer


individually as per Dcode from the table Stock.
CODING
select Dcode,max(UnitPrice) from stock group by Dcode;
OUTPUT

SNEHA CHAUDHARY Page 81


b.Give the output of the following SQL queries:

1. select count(distinct Dcode) from stock;


OUTPUT

2. select Qty*UnitPrice from stock where ItemNo=5006;


OUTPUT

3. select min(StockDate) from stock;


OUTPUT

SNEHA CHAUDHARY Page 82


PROGRAM 40:
Consider a database with the following table:
PRODUCTS and SUPPLIERS.
Table: PRODUCTS

Table: SUPPLIERS

a.Write SQL commands for the following


statements.

1. To arrange and display all the records of table Products on


the basis of product name in the ascending order.
CODING
select*from products order by SNAME;

SNEHA CHAUDHARY Page 83


OUTPUT

2. To display product name and price of all those products


whose price is in the range of 10000 and 15000 (both)
CODING
select SNAME,PRICE from PRODUCTS where PRICE>=10000
and PRICE<=15000;
OUTPUT

3. To display the price, product name and quantity of those


products which have quantity more than 100.
CODING
select PRICE,SNAME,QTY from PRODUCTS where QTY>100;
OUTPUT

SNEHA CHAUDHARY Page 84


4. To display the names of those suppliers who are either
from DELHI or from CHENNAI.
CODING
select SNAME from SUPPLIERS where CITY="DELHI" or
CITY="CHENNAI";
OUTPUT

5. To display the names of the companies and the names of


the products in descending order of company names.
CODING
select COMPANY,SNAME from PRODUCTS order by
COMPANY desc;
OUTPUT

SNEHA CHAUDHARY Page 85


6.Give the output of the following SQL queries:

6.1 select distinct SUPCODE from PRODUCTS;


OUTPUT

6.2 select max(PRICE),min(PRICE) from PRODUCTS;


OUTPUT

6.3 select PRICE*QTY AMOUNT from PRODUCTS where


PID=104;
OUTPUT

SNEHA CHAUDHARY Page 86


PROGRAM 41:
Consider a database with the following table:
SHOP and ACCESSORIES.
Table: SHOP

Table: ACCESSORIES

a.Write SQL commands for the following


statements.
1. To display Name and Price of all the Accessories in
ascending order of their Price.
CODING
select Name,Price from ACCESSORIES ORDER BY Price;
SNEHA CHAUDHARY Page 87
OUTPUT

2. To display Id, SName of all shops located in Nehru Place.


CODING
select ID,SName from SHOP where Area='NehruPlace';
OUTPUT

3. To display Minimum and Maximum Price of all the


accessories;
CODING
select count(distinct AREA) from SHOP;
OUTPUT

SNEHA CHAUDHARY Page 88


b.Give the output of the following SQL queries:

4. select distinct NAME from ACCESSORIES where


PRICE>=5000;
OUTPUT

5. select AREA,count(*)from SHOP group by AREA;


OUTPUT

6. select count(distinct AREA)


from SHOP;
OUTPUT

SNEHA CHAUDHARY Page 89


Python
With
Database
Connectivity
Programs
PROGRAM 42:
ABC Infotech Pvt. Ltd. needs to store,
SNEHA CHAUDHARY Page 90
retrieve and delete the records of its
employees. Develop an interface that
provides front-end interaction through
Python, and stores and updates records
using MySQL.
The operations on MySQL table “emp”
involve reading, searching, updating and
deleting records of employees
(a)Program to read and fetch all the records
from “emp” table having salary is equal to
62000.
(b)Program to delete the records on the
basis of inputted salary .
#database name is ABCinfo.

CODING
#program to read and research record of employees having
salary is equal to 62000
SNEHA CHAUDHARY Page 91
import mysql.connector as mycon
db1=mycon.connect(host="localhost",user="root",passwor
d="sanchita",database="ABCinfo")
mycursor=db1.cursor()

sql="SELECT * FROM emp WHERE SALARY=62000;"


mycursor.execute(sql)
myrecords=mycursor.fetchall()
for x in myrecords:
print(x)

db1.close()

OUTPUT

CODING
import mysql.connector as mycon
con=mycon.connect(host="localhost",user="root",password
="sanchita",database="ABCinfo")

SNEHA CHAUDHARY Page 92


if (con.is_connected()):
print("connection done successfully")
mycursor=con.cursor()
ns=input("Enter the salary whose record is to be deleted")
try:
sql="delete from emp where salary=%s"
mycursor.execute(sql,(ns,))
con.commit()
print(mycursor.rowcount,"record(s) deleted")
except:
print('error')
con.rollback()
mycursor.close()
con.close()

OUTPUT

SNEHA CHAUDHARY Page 93


Thank
you for
your
attention
…..
SNEHA CHAUDHARY Page 94

You might also like