You are on page 1of 64

Name : Suramya

Singh
Class : 12
Section : D
Roll No. : 30
PROGRAM
FILE
Q1.Write functions in python to:
a.Find HCF OR GCD of two numbers passed as arguments.

def hcf(a,b):
s=min(a,b)
gcd=1
for x in range(s,1,-1):
if a%x==0 and b%x==0:
gcd=x
break
return gcd

a=int(input("Enter number 1\n"))


b=int(input("Enter number 2\n"))
print(hcf(a,b))
b.Check if the number passed as argument is prime or not.

def isPrime(n):
for x in range(2,n//2+1):
if n%x==0:
return False
return True

n=int(input("Enter any number\n"))


if isPrime(n):
print("Prime")
else:
print("Not Prime")
c.Print reverse of a string passed a argument.

def reverse(s):
r=""
for x in s:
r=x+r
print(f"Reverse of {s} is {r}")

s=input("Enter any string\n")


reverse(s)
d.Checks whether the passed string is palindrome or not.

def isPalindrome(s):
r=""
for x in s:
r=x+r
if r==s:
return True
return False

s=input("Enter any string\n")


if isPalindrome(s):
print("Palindrome")
else:
print("Not Palindrome")
e.Function that takes a list and returns a new list with unique elements
of the first.

def unique(l):
u=[]
d=[]
for x in range(0,len(l)):
if l[x] not in d:
if l.count(l[x])==1:
u.append(l[x])
else:
d.append(l[x])
return u

l=eval(input("Enter a list\n"))
print(unique(l))
Q2.Write a program in python to search for a given number in a list
using :
a.Linear Search

l=eval(input("Enter a List\n"))
n=int(input("Enter item to search\n"))
f=False
for x in l:
if x==n:
print(f"{n} found")
f=True

if f==False:
print("Not found")
b.Binary Search
l=eval(input("Enter a List\n"))
n=int(input("Enter item to search\n"))
l.sort()
s=0
e=len(l)
if n in l:
for x in range(s,e):
m=(s+e)//2
if n==l[m]:
print(f"{n} found")
break
elif n>l[m]:
s=m+1
else:
e=m
else:
print("Not found")
Q3.Define a function SIMINTEREST() in python to demonstrate the use
of:
a.Positional/Required arguments
b.Default arguments
c.Keyword/Named arguments
d.Multiple arguments

def SIMINTEREST1(p,r,t): #Positional arguments


return p*r*t/100
print("Positional arguments SI :",SIMINTEREST1(2000,5,5))
def SIMINTEREST2(p=2000,r=4,t=5): #Default arguments
return p*r*t/100
print("Default arguments SI :",SIMINTEREST2(r=5,t=5))
def SIMINTEREST3(p,r,t): #Keyword arguments
return p*r*t/100
print("Keyword arguments SI :",SIMINTEREST3(p=2000,r=5,t=5))
print("Multiple arguments SI :",SIMINTEREST2(2000,r=5,t=5)) #Multiple
arguments
Q4.Write a program in python to sort a list of numbers in Ascending
order using Insertion sort.

l=eval(input("Enter a List\n"))
length=len(l)
for x in range(1,length):
k=l[x]
y=x-1
while k<l[y] and y>=0:
l[y+1]=l[y]
y=y-1
l[y+1]=k
print("Sorted list :",l)
Q5.Define a function in python to sort a list of numbers in descending
order using Insertion sort.

def desc(l,length):
for x in range(1,length):
k=l[x]
y=x-1
while k>l[y] and y>=0:
l[y+1]=l[y]
y=y-1
l[y+1]=k
return l

L=eval(input("Enter a List\n"))
length=len(L)
print("Sorted list :",desc(L,length))
Q6.Define a function that accepts a sentence and calculates the
number of uppercase letters and lowercase letters.
def countCase():
s=input("Enter any sentence\n")
cu=0
cl=0
for x in s:
if x.isupper():
cu+=1
elif x.islower():
cl+=1
print("Uppercase letters :",cu)
print("Lowercase letters :",cl)

countCase()
Q7.Define a function that accepts two strings as input ,concatenates
them and prints the result.

def Concatenate(a,b):
s=a+b
print(s)

a=input("Enter first string\n")


b=input("Enter second string\n")
Concatenate(a,b)
Q8.Define a function which can generate and print a list where the
values are square numbers between 1 and 20 (both included).

def square1to20():
L=[]
for x in range(1,21):
L.append(x*x)
print(L)

square1to20()
Q9,With a given tuple (1,2,3,4,5,6,7,8,9,10),define a function to print the
first half in one line and the second half in another line.

def printHalf():
t=(1,2,3,4,5,6,7,8,9,10)
print(t[:len(t)//2])
print(t[len(t)//2:])

printHalf()
Q10.Create a function showEmployee() in such a way that it should
accept employee name,and it’s salary and display both,and if the salary
is missing in the function call it should show it as 30000.

def showEmployee(name,salary=30000):
print("Name :",name)
print("Salary :",salary)

name=input("Enter name of employee\n")


salary=int(input("Enter salary\n"))
showEmployee(name,salary)
showEmployee(name)
Q11.Read a text file line by line and display each word separated by a #.
f=open("file1.txt",'r')
l=f.readlines()
for x in l:
ol=x.split()
for y in ol:
print(y,"#",sep='',end='')

f.close()
Q12.Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters present in the
file.
f=open("File1.txt",'r')
uc=0
lc=0
cn=0
v=0
data=f.read()

for x in data:
if x.islower():
lc+=1
if x.lower() in "aeiou":
v+=1
if x.isupper():
uc+=1
if x.lower() in "bcdfghjklmnpqrstvwxyz":
cn+=1

print("Uppercase :",uc)
print("Lowercase :",lc)
print("Consonants :",cn)
print("Vowel :",v)
f.close()
Q13.Take a sample of 10 phishing e-mails(or any text file) and find the
most commonly occurring word(s) used.
f=open("File1.txt",'r')
data=f.read()
data=data.lower()
l=data.split()
nl=[]
r=[]
for x in l:
if x not in r:
n=l.count(x)
nl.append(n)
r.append(x)

m=max(nl)
i=nl.index(m)
print(l[i],"is the most occuring word")
f.close()
Q14.Remove all the lines that start with character ‘I’ or ‘i’ in a file and
write it to another file.
f1=open("File1.txt",'r')
data=f1.readlines()
f2=open("File2.txt",'w')
for x in data:
if x[0]=='I' or x[0]=='i':
continue
f2.write(x)
f1.close()
f2.close()
Q15.Create a binary file with name and roll number and marks of
students(represented by dictionary).Write a complete menu driven
program to perform following operations(define a function for each
operation).

import pickle

def insertRec():
rno=int(input("Enter roll no. : "))
name=input("Enter name : ")
marks=int(input("Enter marks : "))
r={"Name":name,"Rollno":rno,"Marks":marks}
f=open("StudentRecords.dat",'ab')
pickle.dump(r,f)
f.close()

def readRec():
f=open("StudentRecords.dat",'rb')
while True:
try:
r=pickle.load(f)
print("Name :",r["Name"])
print("Roll no. :",r["Rollno"])
print("Marks :",r["Marks"])
except EOFError:
break
f.close()

def searchRec(rs):
f=open("StudentRecords.dat",'rb')
found=False
while True:
try:
r=pickle.load(f)
if r["Rollno"]==rs:
print("Name :",r["Name"])
print("Roll no. :",r["Rollno"])
print("Marks :",r["Marks"])
found=True
except EOFError:
break
if found==False:
print("No record found")
f.close()

def updateRec(rno,marks):
f=open("StudentRecords.dat",'rb')
rl=[]
while True:
try:
r=pickle.load(f)
rl.append(r)
except EOFError:
break
f.close()

for x in range(len(rl)):
if rl[x]["Rollno"]==rno:
rl[x]["Marks"]=marks
f=open("StudentRecords.dat",'wb')
for x in rl:
pickle.dump(x,f)
f.close()
def deleteRec(rno):
f=open("StudentRecords.dat",'rb')
rl=[]
while True:
try:
r=pickle.load(f)
rl.append(r)
except EOFError:
break
f.close()
f=open("StudentRecords.dat",'wb')
for x in rl:
if x['Rollno']==rno:
continue
pickle.dump(x,f)
f.close()

while True:
print('Type 1 to insert record\nType 2 to display record\nType 3 to
search record\nType 4 to update record\nType 5 to delete
record\nEnter 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:
rs=int(input("Enter roll number to search : "))
searchRec(rs)
elif choice==4:
rno=int(input("Enter roll number : "))
marks=int(input("Enter new marks : "))
updateRec(rno,marks)
elif choice==5:
rno=int(input("Enter roll number : "))
deleteRec(rno)
else:
print("Invalid choice")
Q16.Create a binary file Book(represented using a list) containing
Bnumber , Btitle and Bprice. Write a program to input a title of the book
and update the price.

import pickle
f=open("Book.dat",'wb')
d={}
n=int(input("Enter number of entries\n"))
for x in range(n):
bn=int(input("Enter book no.\n"))
l=[]
bt=input("Book Title : ")
l.append(bt)
bp=int(input("Book Price : "))
l.append(bp)
d[bn]=l
pickle.dump(d,f)
f.close()

f=open("Book.dat",'rb+')
data=pickle.load(f)
btitle=input("Enter book title to upgrade price : ")
price=int(input("Upgraded price : "))
for x in data:
if data[x][0].lower()==btitle.lower():
data[x][1]=price
f.seek(0)
pickle.dump(data,f)
f.close()
Q17.Write definitions to :
a.Create a binary file ‘Flight’ that stores the records of flights
containing Flight no, Airline Name , Departure , Arrival-destination
details and displays them one by one .
b.Display all the details of flights which would arrive in ‘Dubai’.

import pickle
f=open("Flight.dat",'wb')
d={}
n=int(input("Enter number of entries\n"))
for x in range(n):
fln=int(input("Enter flight no.\n"))
l=[]
an=input("Airline Name : ")
l.append(an)
dr=input("Departure : ")
l.append(dr)
ar=input("Arrival : ")
l.append(ar)
d[fln]=l
pickle.dump(d,f)
f.close()

f=open("Flight.dat",'rb')
data=pickle.load(f)
dubai={}
found=False
for x in data:
print("\nFlight number :",x)
print("Airline Name :",data[x][0])
print("Departure :",data[x][1])
print("Arrival :",data[x][2])
if data[x][2].lower()=='dubai':
dubai[x]=data[x]
found=True

print("\nFlights arriving in DUBAI")


if found==True:
for x in dubai:
print("\nFlight number :",x)
print("Airline Name :",data[x][0])
print("Departure :",data[x][1])
print("Arrival :",data[x][2])
else:
print("No such flights found")

f.close()
Q18.Write a user-defined functions to perform different functions on a
csv file ‘Product’ containing Prod_ID,Prod_Name,Prod_Qty,Prod_Price
to:
a.Write each record one by one onto the csv file.

import csv
def write(c,r):
fileName="Product.csv"
with open(fileName,'w',newline='') as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.writerow(c)
for x in r:
csv_w.writerow(x)

fields=['Prod_ID','Prod_Name','Prod_Qty','Prod_Price']
rows=[]
n=int(input("Enter number of products\n"))
for x in range(n):
print(f"\n{x+1}")
pid=input("Product ID : ")
pn=input("Product Name : ")
pq=input("Product quantity : ")
ppr=input("Product price : ")
l=[pid,pn,pq,ppr]
rows.append(l)

write(fields,rows)
b.Display the contents of the csv file.

import csv

f=open("Product.csv",'r')
csv_reader=csv.reader(f)
for x in csv_reader:
print(x)

f.close()
Q19.Write a program to display the records stored in the above csv file
-Product in the form of comma separated values instead of lists.
import csv
f=open("Product.csv",'r')
csv_reader=csv.reader(f)
for x in csv_reader:
print(','.join(x))

f.close()
Q20.Write a random number generator that generates random
numbers between 1 to 6 (stimulates a dice).

import random
n=random.randint(0,6)
print(n)
Q21. Write a menu driven program to implement a stack of integers
,floating point numbers and strings using a list data structure. (Push
,Pop and display)

stack=[]
while True:
c=input("\n1. Push\n2. Pop\n3. Display\nEnter your choice (0-
Exit)\n")
if c=='0':
break
elif c=='1':
i=input("Enter value to be stacked\n")
stack.append(i)
elif c=='2':
if stack==[]:
print("Stack empty")
else:
e=stack.pop()
print("Element deleted :",e)
elif c=='3':
for x in range(len(stack)-1,-1,-1):
print(stack[x])
else:
print("Incorrect input")
continue
Q22.Write a menu driven program to implement a stack of employees
containing Eno, Ename and Esalary.(Push, Pop and Display)

Employee=[]
while True:
c=input("\n1. Push\n2. Pop\n3. Display\nEnter your choice (0-
Exit)\n")
if c=='0':
break
elif c=='1':
Eno=input("Enter Employee number :\n")
Ename=input("Enter Employee name :\n")
Esalary=input("Enter Employee salary :\n")
emp=(Eno,Ename,Esalary)
Employee.append(emp)
elif c=='2':
if Employee==[]:
print("Stack empty")
else:
Eno,Ename,Esalary=Employee.pop()
print("Element deleted :",Eno,Ename,Esalary)
elif c=='3':
for x in range(len(Employee)-1,-1,-1):
print(Employee[x])
else:
print("Incorrect input")
continue
Q23.Write the definition of a function POP_PUSH(Pop,LPush,N) in
python.
The function should pop out the last N elements of the list LPop and
push them into the list LPush.
Note: If the value of N is more than the number of elements present in
LPop, then display the message “Pop not possible”.

def POP_PUSH(LPop,LPush,N):
if N>len(LPop):
print("Pop not possible")
else:
for x in range(N):
LPush.append(LPop.pop())
print("LPop :",LPop)
print("LPush :",LPush)

POP_PUSH([10,15,20,30],[],2)
Q24. Create an EMPLOYEE table and insert 5 records into it.Implement
the following SQL commands on the employee table.
a.Alter table to add new attributes/modify data type/drop attribute
b.Update table to modify data
c.Order By to display data in ascending/descending order.
d.Delete to remove tuple(s)
e.Group By and find min, max, sum, count and average.
Q25.Create a database Library. Then create a table BOOK with the
following fields: BCODE, BNAME, QTY, PRICE
Write SQL commands:
a.to add constraint PRIMARY KEY to the field BCODE.
b.to add a field Author to the table BOOK.
c.to display details of all the books.
d.to display the total cost of books which is product of quantity*price.
Q26.Write SQL queries to do the tasks from (i) to (iv) based on the
tables given below:
MOBILE_MASTER
M_id M_company M_name M_Price M_Mf_Date
MB001 Samsung Galaxy 4500 2013-02-12
MB003 Nokia N1100 2250 2011-04-15
MB004 Micromax Unite3 4500 2016-10-17
MB005 Sony XperiaM 7500 2017-11-20
MB006 Oppo SelfieEx 8500 2010-08-21

MobileStock
S_Id M_id M_qty M_supplier
S001 MB004 450 New Vision
S002 MB003 250 Praveen Gallery
S003 MB001 300 Classic Mobile
S004 MB006 150 A_one mobiles
S005 MB003 150 The Mobile
S006 MB006 50 Mobile Center

(i)Display the mobile company, name and price in descending order of


their manufacturing date.
(ii)List the details of mobile whose name starts with “S” or ends with
“a”.

(iii)Display the mobile supplier & quantity of all mobiles except


“MB003”.

(iv)List showing the name of mobile company having price between


3000 & 5000.
Q27.Consider the table SHOPPE given below. Write commands in MySql
for (i) to (vi) and output for (vii) to (ix)
SHOPPE
Code Item Company Qty City Price
102 Biscuit Hide & Seek 100 Delhi 10.00
103 Jam Kissan 110 Kolkata 25.00
101 Coffee Nestle 200 Kolkata 55.00
106 Sauce Maggi 56 Mumbai 55.00
107 Cake Britannia 72 Delhi 10.00
104 Maggi Nestle 150 Mumbai 10.00
105 Chocolate Cadbury 170 Delhi 25.00

(i)To display names of the items whose name starts with ‘C’ in
ascending order of Price.

(ii)To display code, item name and city of the products whose quantity
is less than 100.
(iii)To count distinct Company from the table.

(iv)To insert a new row in the table SHOPPE


‘110’,’Pizza’,’Papa Johns’,120,’Kolkata’,50.00

(v)To make code as Primary key.

(vi)To display count of products in each city.

(vii)Select item from SHOPPE where item IN(“Jam”,”Coffee”);


(viii)Select Count(distinct(City)) from SHOPPE;

(ix)Select MIN(Qty) from SHOPPE where City=”Mumbai”;


Q28. Consider a table EXAM given below. Write commands in MySql for
(i) to (vi) and output for (vii) to (ix).
Table : EXAM
No Name Stipend Subject Average Division
1 Karan 400 English 68 FIRST
2 Aman 680 Mathematics 72 FIRST
3 Javed 500 Accounts 67 FIRST
4 Bishakh 200 Informatics 55 SECOND
5 Sughandha 400 History 35 THIRD
6 Suparna 550 Geography 45 THIRD

(i)To list the names of those students,who have obtained Division as


FIRST in the ascending order of Name.

(ii)To display a report listing Name , subject and annual stipend


received considering that the stipend column has monthly stipend.
(iii)To count number of students , who have either Mathematics or
English as subject.

(iv)To insert a new row in the table EXAM :


(6,”Mohan”,500,”English”,73,”Second”)

(v)To change the datatype of the field subject from char to varchar.

(vi)To print sum of stipend of each division.

(vii)SELECT AVG(Stipend) FROM EXAM WHERE DIVISON=”THIRD”;


(viii)SELCT COUNT(DISTINCT Subject) FROM EXAM;

(ix)SELECT MIN(Average) FROM EXAM WHERE Subject=”English”;


Q29.Write the python code to establish a connection with database
Travel and display complete details of all records in separate lines.

import mysql.connector.

mydb=mysql.connector.connect(host="localhost",user="root",passwor
d="ccdeeghnppq",database="TRAVEL")
mycursor=mydb.cursor()
mycursor.execute("Select * from Passengers")
myrecords=mycursor.fetchall()
for x in myrecords:
print(x)
Q30. Consider the table Faculty with field names as:
F_ID, F_NAME, HIRE_DATA, SALARY, COURSE
Write the python code to insert the following records in the table
Faculty and display the details of the faculty drawing a salary greater
than 50000.
101 STEVEN 14-10-2006 45000 COMMUNICATION TECHNOLOGIES
105 DAVID 07-12-2010 50000 ADVANCED PYTHON
107 STANLEY 09-08-2012 60000 ADVANCED PYTHON

import mysql.connector

mydb=mysql.connector.connect(host="localhost",user="root",passwor
d="ccdeeghnppq",database="PF31")
mycursor=mydb.cursor()
mycursor.execute("INSERT INTO FACULTY VALUES(101,'STEVEN','2006-
10-14',45000,'COMMUNICATION TECHNOLOGIES')")
mycursor.execute("INSERT INTO FACULTY VALUES(105,'DAVID','2010-12-
07',50000,'ADVANCED PYTHON')")
mycursor.execute("INSERT INTO FACULTY VALUES(107,'STANLEY','2012-
08-09',60000,'ADVANCED PYTHON')")
mydb.commit()
mycursor.execute("SELECT * FROM FACULTY WHERE SALARY>50000")
myrecords=mycursor.fetchall()
for x in myrecords:
print(x)

You might also like