CH 3 - CH 8 Answers
CH 3 - CH 8 Answers
PRACTICE QUESTIONS
2 MARKS/3 MARKS
1. Refer Class Work for theory
2. def execmain():
x = int(input("Enter a number:"))
if abs(x) == x:
print("You entered a positive number")
else:
x *= -1
print("Number made positive:", x)
execmain()
3. (1)def
(2) Global
(3) x, y = y, x
(4) 10 30 100 50
(5) fun
4. 250 @ 150
250 @ 100
130 @ 100
5. Correct code is:
def Fun():
G = (i for i in range(5, 15, 3))
print(list(G))
Fun()
O/P:
[5, 8, 11, 14]
6. a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
7. 100 0
L=[2,4,6,10,15,12,20]
a,b=DIVI_LIST(L)
print("D_2 is:",a)
print("D_5 is:",b)
9. 100 $ 1060 % 6
30 $ 19 # 55
50 $ 1220 % 11
10. 5#5
11. def countNow(PLACES):
for place_id, place_name in PLACES.items():
if len(place_name) > 5:
print(place_name.upper(), end=" ")
fun()
18. def sum(arg1, arg2):
total = arg1 + arg2;
print("Total:", total)
return total
sum(10, 20)
print("Total:", total) # total is not defined outside the function, so it
will raise an error
19. ['MDU', 'MS', 'CGL', 'TBM']
# Example usage:
Array = [100, 200, 300, 40, 50, 60]
SwapHalfList(Array)
print(Array)
Alternative code:
def SwapHalfList(Array):
first_half_sum, second_half_sum = 0, 0
for i in range(len(Array)//2):
first_half_sum += Array[i]
second_half_sum += Array[i + len(Array)//2]
if first_half_sum > second_half_sum:
for i in range(len(Array)//2):
Array[i]= Array[i + len(Array)//2]
Array[i + len(Array)//2] = Array[i]
print(Tot(3))
29. 5#8#5#4#
30. 3%6%
31. def sumcube(L):
for i in L:
P=0
S = str(i)
for j in S:
P += int(j) ** len(S)
if P == i:
print(P)
wlist = list("aaaaabbbbcccdde")
result = letter_freq(wlist)
print(result)
47. [100, 212, 310]
[20.0, 42.4, 62.0, 3, 10.4]
48. [25, 32, 17]
49. def Shift(Lst):
L= []
for i in range(len(Lst)):
next_index = i + 1
if next_index < len(Lst):
L.append(Lst[next_index])
else:
L.append(Lst[i])
return L
# Example usage:
Lst = [2, 4, 1, 6, 5, 7, 9, 2, 3, 10]
result = Shift(Lst)
print(result)
6@
7@
8@
9@
25 @
11 @
0@
6@
7@
8@
9@
0@
6@
7@
S = "Computer"
indexList = INDEX_LIST(S)
print(indexList)
Count()
2. def Count():
with open("Poem.txt", 'r') as F:
S = F.readlines()
K=0
for i in S:
C = 0 #Reset vowel count for each line
for j in i:
if j.lower() in "aeiou":
C += 1
K += 1 # Line count
print("The Number of vowels in Line", K, "is:", C)
Count()
BIGLINES()
4. def COUNTTEXT():
with open("poem.txt", 'r') as F:
words = []
S=F.read()
W=S.split()
for i in W:
if len(i) > 3 or i[0] in 'Aa':
words.append(i)
print(words)
COUNTTEXT()
5. F1 = open("input.txt", 'r')
F2 = open("output.txt", "w")
S = F1.readlines()
for i in S:
F2.write(i[::-1])
F1.close()
F2.close()
6. def COUNT_CHAR():
F = open("Math.txt", 'r')
a=b=c=d=0
S = F.read()
for i in S:
if i == '+':
a += 1
elif i == '-':
b += 1
elif i == '*':
c += 1
elif i == '/':
d += 1
if a == b == c == d == 0:
print("There are no +,-,*,/ characters in the file")
else:
print("The number of + is:", a)
print("The number of - is:", b)
COUNT_CHAR()
7. def V_COUNT():
F = open("poem.txt", 'r')
S = F.readlines()
c=0
for i in S:
if i[0] in 'aeiouAEIOU' and i[-2] in 'aeiouAEIOU':
c += 1
print(c)
F.close()
V_COUNT()
8. def Count():
F = open("Report.txt", 'r')
S = F.readlines()
c=0
for i in S:
if i[0]=='M' or i[0]=='S':
c += 1
print(c)
F.close()
Count()
9. def DISPLAYWORDS():
with open("Poem.TXT", 'r') as file:
S=file.read()
words = S.split()
for word in words:
if len(word) < 4:
print(word)
DISPLAYWORDS()
stats()
11. def countdigits():
F=open("poem.txt")
S=F.read()
c=0
for i in S:
if i.isdigit():
c=c+1
print("Total number of digits in the file:",c)
countdigits()
12. def Count():
with open("STORY.txt", 'r') as F:
S = F.readlines()
C=0
for i in S:
if i[0] == "A":
C += 1
print("The Number of Lines starting with 'A' are:", C)
Count()
13. def SHOWLINES():
with open("TESTFILE.txt",'r')as F:
S=F.readlines()
for i in S:
if 'ke' not in i:
print(i,end='')
SHOWLINES()
RainCount()
15. def SHOWWORD():
with open("STORY.TXT", 'r') as file:
for line in file:
words = line.split()
for word in words:
if len(word) < 5:
print(word)
SHOWWORD()
16. def Count():
with open("Para.txt", 'r') as F:
S = F.readlines()
C=0
for i in S:
if i[0] == "H":
C += 1
print("The Number of Lines starting with 'H' are:", C)
Count()
17. def Count():
F=open("STORY.txt","r")
S=F.read()
W=S.split()
for i in W:
if 's' or 'S' in i:
print(i)
Count()
COUNTLINES()
BINARY FILE [3/5 MARKS]
1. import pickle
def countrec():
C=0
try:
with open("STUDENT.DAT", 'rb') as F:
while True:
S = pickle.load(F)
if S[2] > 75:
print(S)
C += 1
except EOFError:
pass
print("Number of students scoring above 75%:", C)
countrec()
2. import pickle
def CreateFile():
try:
with open("Book.dat", 'ab') as file:
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = (BookNo, Book_Name, Author, Price)
pickle.dump(record, file)
def CountRec(Author):
count = 0
try:
with open("Book.dat", 'rb') as file:
while True:
record = pickle.load(file)
if record[2] == Author:
count += 1
except EOFError:
pass
return count
CreateFile()
Au_name = input("Enter Author name to count books: ")
print("Number of books by", author_name, ":", CountRec(Au_name))
3. import pickle
def CreateFile():
try:
with open("Toy.dat", 'ab') as file:
TID = int(input("Enter Toy ID: "))
Toy = input("Enter Toy Name: ")
Status = input("Enter Status: ").upper()
MRP = float(input("Enter MRP: "))
record = (TID, Toy, Status, MRP)
except Exception as e:
print("Error:", e)
def OnOffer():
try:
with open("Toy.dat", 'rb') as file:
while True:
record = pickle.load(file)
if record[2] == "ON OFFER":
print(record)
except EOFError:
pass
CreateFile()
OnOffer()
4. import pickle
def search_comedy_movies():
try:
with open("CINEMA.DAT", 'rb') as file:
while True:
record = pickle.load(file)
if record['MTYPE'] == "Comedy":
print(record)
except EOFError:
pass
search_comedy_movies()
expensiveProducts()
(ii)
(a)
import csv
def add():
F=open("EMP.csv",'a',newline='')
W=csv.writer(F)
H=['EId','EName','Esal']
W.writerow(H)
Id=input("Enter Employee ID:")
Name=input("Enter Employee Name:")
Sal=input("Enter Employee Salary:")
L=[Id,Name,Sal]
W.writerow()
F.close()
add()
Example:
F=open("story.txt")
F.seek(10)
S=F.read(5)
print(S)
(b)
import csv
def add_book():
with open("book.csv", 'a', newline='') as file:
writer = csv.writer(file)
book_no = input("Enter book number: ")
name = input("Enter book name: ")
author = input("Enter author name: ")
writer.writerow([book_no, name, author])
def search_book():
author_name = input("Enter author name to search: ")
with open("book.csv", 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[2] == author_name:
print(row)
add_book()
search_book()
(b)
import csv
def add_rating():
with open("product.csv", 'a', newline='') as file:
writer = csv.writer(file)
product_name = input("Enter product name: ")
rating = input("Enter rating: ")
writer.writerow([product_name, rating])
def display():
with open("product.csv", 'r') as file:
reader = csv.reader(file)
for row in reader:
if int(row[1]) > 10:
print(row)
add_rating()
display()
def insertData():
with open('customers.csv', 'a', newline='') as file:
writer = csv.writer(file)
cname = input("Enter customer name: ")
mobno = input("Enter mobile number: ")
DOP = input("Enter date of purchase: ")
item_purchased = input("Enter item purchased: ")
writer.writerow([cname, mobno, DOP, item_purchased])
def Frequency(name):
count = 0
F=open("customers.csv")
reader = csv.reader(file)
for row in reader:
if row[0] == name:
count += 1
F.close()
return count
insertData()
name = input("Enter customer name to check frequency: ")
print("Frequency of", name, ":", Frequency(name))
5. (a)
def createcsv():
data = [['1', 'Anil', '40', '34', '90', ''],
['2', 'Sohan', '78', '34', '90', ''],
['3', 'Kamal', '40', '45', '9', '']]
with open('result.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
def Pop():
if S==[]:
print("Underflow")
else:
print("The deleted Element is:",S.pop())
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
S=[]
Push()
Pop()
4. def Push():
for i in N:
if i%2 and i%5==0:
S.append(i)
print(S)
def Pop():
if S==[]:
print("Underflow")
else:
print("The deleted Element is:",S.pop())
def Pop():
if S==[]:
print("Stack is Empty")
else:
print("The deleted Element is:",S.pop())
N=[2, 131, 34, 56, 21, 379, 98, -22, 35, 38]
S=[]
Push()
Pop()
6. def POP_PUSH(LPop, LPush, N):
if len(LPop) < N:
print("Pop not possible")
else:
for i in range(N):
k = LPop.pop()
LPush.append(k)
LPop=[10,15,20,30]
LPush=[ ]
N=2
POP_PUSH(LPop, LPush, N)
print("LPop:", LPop)
print("LPush:", LPush)
def Pop_element():
if Status==[]:
print("Stack is Empty")
else:
print("The deleted element is:",Status.pop())
Push_element()
Pop_element()
9. def Push(stack,SItem):
for i in range(len(SItem)):
if SItem[1]<(SItem[4]-(SItem[4]*0.1)):
stack.append(SItem[3])
def Disp():
if stack==[]:
print("Underflow")
else:
top=len(stack)-1
for i in range(top,-1,-1):
print(stack[i])
Push()
Pop()
12. KItem = {"Spoons": 116, "Knife": 50, "Plates": 180, "Glass": 60}
S=[]
def Push(KItem):
Total=0
for i in KItem:
if KItem[i]<100:
S.append(i)
Total=Total+KItem[i]
print("The Stack is:",S[::-1])
print("The average price of an item is",Total/len(S))
Push(KItem)
def Pop_na():
if Lnameage==[]:
print("underflow")
else:
name, age = Lnameage.pop()
print("The output of first execution of pop_na() is ")
print("The name removed is:",name)
print("The age of person is:",age)
14. Univ=[]
def Push_element():
Course=input("Enter your course:")
Fees=int(input("Enter the Course Fees:"))
Duration=int(input("Enter the Duration of the course:"))
University=[Course,Fees,Duration]
for i in University:
if i[1]>100000:
Univ.append(i)
def Pop_element():
if Univ==[]:
print("Underflow")
else:
print(Univ.pop())
Push_element()
Pop_element()
stu={1:56,2:45,3:78,4:65,5:35,6:90}
16. Stu_stk=[]
def Push_elements(Stu_stk,Stu_dict):
for i in stu_dict:
if Stu_dict[i][2]>=80:
Stu_stk.append(i)
def pop_elements(Stu_stk):
if Stu_stk ==[]:
print("Underflow")
else:
try:
while True:
print(Stu_stk.pop())
except:
print("Stack empty")
Push_elements(Stu_stk,Stu_dict)
Pop_elements(Stu_stk)
*********************************************************************
3 - MARKS
1. (i) Client_ID
(ii) 42
(iii) UPDATE CLIENT SET Qtr2 = 200, Qtr3 = 600,
Total=Qtr1+Qtr2+Qtr3+Qtr4 WHERE Client_ID = 'C660';
(OR)
(iii) (a) DELETE FROM CLIENT WHERE Total BETWEEN 500
AND 900;
(b) ALTER TABLE CLIENT ADD RATINGS INT CHECK
(RATINGS BETWEEN 1 AND 5);
(OR)
8. (a)C_ID
(b) Cardinality: 4 Degree: 7
(c) Write the statements to:
(i) DELETE FROM COMPANY WHERE C_ID = 'C24';
(ii) UPDATE COMPANY SET Fee = Fee - 500;
9. (i) UPDATE PERSONAL SET Salary = SALARY*(Salary -0.05)
WHERE Allowance IS NOT NULL;
(ii) SELECT Name, (Salary + Allowance) AS "Total Salary"
FROM PERSONAL;
(iii) DELETE FROM PERSONAL WHERE Salary > 25000;.
10 (i) Candidate Keys: ADNO, ROLLNO
(ii) Cardinality:4, Degree: 8
(iii) UPDATE RESULT SET SEM2 = SEM2 +(SEM2*0.03)
WHERE SEM2 BETWEEN 70 AND 100;
************************************************************************
(b)
(a)
10+ QTY
13
PRICE*QTY
(b) 55.00
75.80
(iii) (iv)
7. (i)
(ii)
(iii)
8. (a)
SUM(DISCOUNT)
29
(b)
MAX(DATEOFPURCHASE)
19-Jul-21
(c)
FID NAME DATEOFPURCHASE COST DISCOUNT
T006 CONSOLE 17-NOV-2019 15000 12
TABLE
(d)
DATEOFPURCHASE
10-Mar-2020
17-Nov-2019
9. (a) SELECT DEPTNAME, AVG(SALARY) FROM EMPLOYEE
E,DEPARTMENT D WHERE E.DEPTID=D.DEPTID GROUP
BY DEPTNAME;
(b) SELECT NAME, DEPTNAME FROM EMPLOYEE E
,DEPARTMENT D E.DEPTID = D.DEPTID
WHERE SALARY > 50000;
(c) SELECT NAME FROM EMPLOYEE WHERE SALARY IS NULL
ORDER BY NAME;
(d) SELECT DISTINCT DEPTID FROM EMPLOYEE;
(b)
17. 1.
2.
(b)
i.
ii.
iii.
iv.
19. (a) UPDATE FLIGHT SET FARE = 6000 WHERE FNO = 'F104';
(b) SELECT GENDER, COUNT(*) FROM PASSENGER GROUP BY
GENDER;
(c) SELECT NAME, FARE, F_DATE FROM PASSENGER P
FLIGHT F WHERE F P.FNO = F.FNO AND START = 'DELHI';
(d) DELETE FROM FLIGHT WHERE END = 'MUMBAI';
(ii)
MAX(DATE_OF_JOIN) MIN(DATE_OF_JOIN)
2021-09-05 2017-03-24
(iii)
NAME SALARY DEPARTMENT PLACE
Saman 20000 History Ahmedabad
Samira 40000 History Ahmedabad
Shyam 30000 History Ahmedabad
(iv)
NAME PLACE
Saman Ahmedabad
Samira Ahmedabad
Shalakha Jaipur
22. (a)
ALTER TABLE STUDENT DROP CONSTRAINT AGE;
(or)
ALTER TABLE STUDENT DROP INDEX AGE;
(b) (i)
SNAME STREAM
Charudharshan BS
Diwahar BS
Jiffin PCMB
Karthikeyan BS
(iii)
AGE STREAM
15 BS
15 BS
(iv)
ROLLNO STREAM
A04 PCMB
(iii)
COUNT(DISTINCT(CLASS))
3
TABLE: TRAINER
TABLE: COURSE
(i)
TID TNAME
101 SUNAINA
102 ANAMIKA
104 MEENAKSHI
105 RICHA
(ii)
TID
101
102
103
104
105
(iv)
COUNT(*) SUM(FEES)
4 65000
25. (i)
BRAND_NAME FLAVOUR
LAYS TOMATO
UNCLE CHIPS SPICY
HALDIRAM TOMATO
(ii)
BRAND_NAME FLAVOUR PRICE QUANTITY
HALDIRM TOMATO 25 30
(iii)
BRAND_NAME
LAYS
(iv)
COUNT( DISTINCT (BRAND_NAME))
3
(v)
PRICE PRICE*1.5
10 15
(vi)
DISTINCT(BRAND_NAME)
UNCLE CHIPS
LAYS
HALDIRM
(ii)
MAX(DOB) MIN(DOB)
08-12-1995 07-05-1993
(iii)
NAME GENDER
Sanal F
Store M
(iv)
DISTINCT Class
X
XII
XI
**********************************************************
So, while it returns a list, the elements of that list are tuples.
14. (a) sql module
except:
pass
con.close()
3. import mysql.connector as q
def Write():
con=q.connect(host='localhost',user='root',
password='admin',database='ORGANIZATION')
try:
if con.is_connected():
cur=con.cursor()
Q1="CREATE TABLE EMP(ENO INT PRIMARY
KEY,ENAME VARCHAR(20), EDEPT
VARCHAR(20), SAL INT)”
user='root',password='Admin',database='MYPROJEC
T'
2. 3->1->4->2
3. RAVI KUMAR
NISHANT JAIN
DEEPAK PRAKASH
4. ("Die to Live",78127873915)
("Again?",23686286243)
("Ushakaal",12678987036)
("Ushakiran",42568987036)
5. 240000
**************************************************************