0% found this document useful (0 votes)
701 views60 pages

CH 3 - CH 8 Answers

The document contains examples and practice questions on working with functions in Python. It includes questions related to defining and calling functions, passing arguments to functions, returning values from functions, scope of variables etc. The questions cover basic to intermediate level concepts related to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
701 views60 pages

CH 3 - CH 8 Answers

The document contains examples and practice questions on working with functions in Python. It includes questions related to defining and calling functions, passing arguments to functions, returning values from functions, scope of variables etc. The questions cover basic to intermediate level concepts related to functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

CHAPTER 3 – WORKING WITH FUNCTIONS

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

APPAN RAJ D PGT- CS/IP 1


8. def DIVI_LIST(NUM_LST):
D_2 = []
D_5 = []
for num in NUM_LST:
if num % 2 == 0:
D_2.append(num)
if num % 5 == 0:
D_5.append(num)
return D_2, D_5

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

PLACES = {1: "Delhi", 2: "London", 3: "Paris", 4: "New York", 5:


"Doha"}
countNow(PLACES)
12. The output would be:
UnboundLocalError: local variable 'c' referenced before
assignment
This error occurs because when Python encounters the
assignment c = c + 2 inside the function add(), it assumes that c
is a local variable. However, since c hasn't been assigned any
value locally, referencing it before assignment raises an
UnboundLocalError.

APPAN RAJ D PGT- CS/IP 2


13. Area=60
14. ['c++', 'java', '', 'JAVASCRIPT']
15. def lenWords(STRING):
lengths = ()
for word in STRING.split():
lengths += (len(word),)
return lengths

result = lenWords("Come let us have some fun")


print(result)
16. 201 @ 101
201 @ 302
201 @ 101
403 @ 202
605 @ 403
403 @ 403
17. import math
def fun():
x = int(input("Enter a number: "))
for i in range(x):
if math.fabs(x) % 2 == 0:
print("Hi")
else:
print("Number is odd")

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']

APPAN RAJ D PGT- CS/IP 3


20. def SwapHalfList(Array):
mid = len(Array) // 2
if sum(Array[:mid]) > sum(Array[mid:]):
Array[mid:], Array[:mid] = Array[:mid], Array[mid:]

# 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]

Array = [100, 200, 300, 40, 50, 60]


SwapHalfList(Array)
print(Array)
21. 9$14$19$5$
22. (None, None)

APPAN RAJ D PGT- CS/IP 4


23. def FindWord(STRING, SEARCH):
count = 0
words = STRING.split()
for word in words:
if word == SEARCH:
count += 1
print("The word", SEARCH ,"occurs", count, "times.")

STRING = "Learning history helps to know about history with


interest in history"
SEARCH = 'history'
FindWord(STRING, SEARCH)
(OR)
Alternative Logic:
def FindWord(STRING, SEARCH):
count = STRING.count(SEARCH)
print("The word", SEARCH ,"occurs", count, "times.")

STRING = "Learning history helps to know about history with


interest in history"
SEARCH = 'history'
FindWord(STRING, SEARCH)
24. def swap(d):
n = {}
values = d.values()
keys = list(d.keys())
k=0
for i in values:
n[i] = keys[k]
k += 1
return n

result = swap({'a': 1, 'b': 2, 'c': 3})


print(result)

APPAN RAJ D PGT- CS/IP 5


25. SCHOOLbbbbCOM
26. 3$3
3#3
6$4
6
27. def Interchange(num):
for i in range(0, len(num)-1, 2):
num[i], num[i+1] = num[i+1], num[i]
print("After Rearrangement num =", num)

num = [5, 7, 9, 11, 13, 15]


print("Original List:")
print("num =", num)
Interchange(num)
28. def Tot(Number):
Sum = 0
for C in range(1, Number + 1):
Sum += C
return Sum

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)

L = [67, 153, 311, 96, 370, 405, 371, 955, 407]


sumcube(L)

APPAN RAJ D PGT- CS/IP 6


32. cCICKEe
33. 54 @ 54 @ 21 @ 32 @
34. [20, 10, 40, 30, 60, 50]
35. def listchange(Arr, n):
for i in range(n):
if Arr[i] % 2 == 0:
Arr[i] *= 2
else:
Arr[i] *= 3

Arr = [10, 20, 30, 40, 12, 11]


n=6
listchange(Arr, n)
print("Arr =", Arr)
36. False # True # True % False %
37. 49#25#
38.
39. 5#5
40. Python Is Great
Python is funny
41. Refer Q.No 20
42. Global x= 3
Local x = 7
y= 8
z= 2
43. def LShift(Arr, n):
n = n % len(Arr)
Arr[:] = Arr[n:] + Arr[:n]

Arr = [10, 20, 30, 40, 12, 11]


n=2
LShift(Arr, n)
print("Arr =", Arr)

APPAN RAJ D PGT- CS/IP 7


44. Output is 190
45. gO OhA
46. def letter_freq(my_list):
freq_dict = {}
for letter in my_list:
if letter not in freq_dict:
freq_dict[letter] = my_list.count(letter)
return freq_dict

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)

APPAN RAJ D PGT- CS/IP 8


50. 4
3
51. 10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
52. def SwitchOver(Val):
for i in range(0, len(Val), 2):
if i+1 < len(Val):
Val[i], Val[i + 1] = Val[i + 1], Val[i]

Numbers = [25, 17, 19, 13, 12, 15]


SwitchOver(Numbers)
print(Numbers)
53. def ZeroEnding(SCORES):
total = 0
for score in SCORES:
if score % 10 == 0:
total += score
return total
SCORES = [200, 456, 300, 100, 234, 678]
result = ZeroEnding(SCORES)
print("Sum of scores ending with zero:", result)
54. Correct Code is:
def determine(s):
d = {"UPPER": 0, "LOWER": 0}
for c in s:
if c.isupper():
d["UPPER"] += 1
elif c.islower():
d["LOWER"] += 1
else:
pass
print("Original String:", s)
print("Upper case count:", d["UPPER"])
print("Lower case count:", d["LOWER"])
determine("These are HAPPY Times")
O/P is:
Original String: These are HAPPY Times
Upper case count: 7
Lower case count: 11

APPAN RAJ D PGT- CS/IP 9


55. def Display(lst, size):
for i in range(size):
if lst[i] % 2 == 0:
lst[i] //= 2
else:
lst[i] *= 2

lst = [5, 6, 7, 16, 9]


size = len(lst)
Display(lst, size)
print(lst)
56. 1 # 12
1#3
57. def INDEX_LIST(L):
indexList = []
for i in range(len(L)):
if L[i] != 0:
indexList.append(i)
return indexList

L = [12, 4, 0, 11, 0, 56]


indexList = INDEX_LIST(L)
print(indexList)
58. New String is: i

APPAN RAJ D PGT- CS/IP 10


59. 0@

6@

7@

8@

9@

25 @

11 @

0@

6@

7@

8@

9@

0@

6@

7@

60. def INDEX_LIST(S):


indexList = []
vowels = "aeiouAEIOU"
for i in range(len(S)):
if S[i] in vowels:
indexList.append(i)
return indexList

S = "Computer"
indexList = INDEX_LIST(S)
print(indexList)

APPAN RAJ D PGT- CS/IP 11


61. def INDEX_LIST(L):
indexList = []
for i in range(len(L)):
if L[i] % 10 % 2 == 0:
indexList.append(i)
return indexList

L = [12, 4, 15, 11, 9, 56]


indexList = INDEX_LIST(L)
print(indexList)
*********************************************************

APPAN RAJ D PGT- CS/IP 12


CHAPTER – 4 FILE HANDLING

[TEXT FILE, BINARY FILE AND CSV FILE]

PREDICT THE OUTPUT OF THE FOLLOWING QUESTIONS


1. 4
2. 2
3. God one God you
4. record = pk.load(file1) # statement-1: to read record
pk.dump(record, file2) # statement-2: to write record
5. 0#Think
6. rec = pickle.load(fobj) # Statement 1
if rec[2] > 80: # Statement 2
TEXT FILE (3 – MARKS)
1. def Count():
F=open("INDIA.txt",'r')
S=F.read()
W=S.split()
C=0
for i in W:
if i=="India": #if i.lower()=="india"
C=C+1
print("Occurences of 'India'is:",C)

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()

APPAN RAJ D PGT- CS/IP 13


3. def BIGLINES():
with open("poem.txt", 'r') as file:
for line in file:
if len(line) > 20:
print(line, end='')

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)

APPAN RAJ D PGT- CS/IP 14


print("The number of * is:", c)
print("The number of / is:", d)

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()

APPAN RAJ D PGT- CS/IP 15


10. def stats():
F=open("poem.txt")
S=F.readlines()
L=[]
for i in S:
L.append(len(i))
for j in S:
if len(j)==max(L):
print("The longest line in the file is:",j,end='')
F.close()

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()

APPAN RAJ D PGT- CS/IP 16


14. def RainCount():
with open("TESTFILE.TXT", 'r') as file:
content = file.read().lower()
count = content.count("rain")
print("Rain -", count)

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()

APPAN RAJ D PGT- CS/IP 17


18. def COUNTLINES():
F=open("STORY.txt")
S=F.readlines()
C=0
for i in S:
if i[0].lower()==i[-2].lower():
C=C+1
print(C)

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)

APPAN RAJ D PGT- CS/IP 18


print("Record added successfully!")
except Exception as e:
print("Error:", e)

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)

APPAN RAJ D PGT- CS/IP 19


pickle.dump(record, file)
print("Record added successfully!")

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()

APPAN RAJ D PGT- CS/IP 20


5. import pickle
def CountRec(author):
try:
count = 0
with open("Book.dat", 'rb') as file:
while True:
record = pickle.load(file)
if record['Author'] == author:
count += 1
except EOFError:
return count

au_name = input("Enter Author Name:")


count_books = CountRec(au_name)
print("Number of books written by",au_name,count_books)
6. import pickle
def expensiveProducts():
try:
total_expensive_products = 0
with open("INVENTORY.DAT", 'rb') as file:
while True:
product = pickle.load(file)
if product[3] > 1000:
print("Product ID:", product[0])
total_expensive_products += 1
except EOFError:
print("Total expensive products:", total_expensive_products)

expensiveProducts()

APPAN RAJ D PGT- CS/IP 21


CSV FILE [5 MARKS]
1. (i)
Function Description Input Data Format
writerow Writes a single row of Iterable containing
data to a CSV file. values for each column.

writerows Writes multiple rows of Iterable of iterables


data to a CSV file. representing rows.

(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()

(b) search() - To display the records of the Employee whose


Salary is more than 10000.
def search():
with open("EMP4.csv", 'r') as file:
s= csv.reader(file)
next(s) # To skip column name
for row in s:
if int(row[2]) > 10000:
print(row)
search()

APPAN RAJ D PGT- CS/IP 22


2. (a)
The seek() function in Python is used to change the position of the
file pointer within a file. It's commonly used to move to a specific
byte position within the file.
Syntax: file_object.seek(offset, Reference_Point)

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()

APPAN RAJ D PGT- CS/IP 23


3. (a)
To open a file using the with statement in Python, you can use the
following syntax:
with open("filename.txt", "mode") as file:
# Perform operations on the file
(or)
F=open("Filname.txt","mode")

(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()

APPAN RAJ D PGT- CS/IP 24


4. import csv

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)

APPAN RAJ D PGT- CS/IP 25


(b)
def copycsv():
F1=open("result.csv",'r')
F2=open("final.csv",'w',newline='')
S = csv.reader(F1)
w = csv.writer(F2)
for i in S:
Total = int(i[2]) + int(i[3]) + int(i[4])
i[5] = str(Total) # Convert total to string
w.writerow(i)
6. def maxsalary():
F=open("record.csv",'r')
S=csv.reader(F)
max_salary=0
for row in S:
salary = int(row[2])
if salary > max_salary:
max_salary = salary
L= row
print(L)
*********************************************************************

APPAN RAJ D PGT- CS/IP 26


COMPLETE THE PROGRAM BY WRITING THE MISSING LINES
[4 – MARKS]
1. FindWords()
(i) ‘r’
(ii) read()
(iii) line.split()
iv) len(c)<4
(v) file.close()
(vi) readline()
2. (i) import pickle
(ii) f=open("emp.bin",'rb')
(iii) pos=f.tell()
(iv) pickle.dump(e,file)
3. (a) csv
(b) 'w' or 'a'
(c) reader()
(d) close()
4. (a) The required Python library is pickle.
(b) Fill_Line2A: open("Mydata.dat", "wb")
Fill_Line2B: open("Mydata.dat", "rb")
(c) pickle.dump(sqlist, fout)
(d) mylist = pickle.load(fin)
5. (a) open("student_data.dat", "wb")
(b) pickle.dump(Stul, fh)
(c) open("student_data.dat", "rb")
(d) Rstu = pickle.load(fin)
6. (i) import pickle #Statement 1
(ii) f1 = open("items.dat", "rb") #Statement 2
(iii)
f2 = open("new_items.dat", "wb") # Statement 3
item_detail = pickle.load(f1) # Statement 4
(iv)
item_detail[key][0] != 101 # Statement 5
pickle.dump(item_detail[key], f2) # Statement 6

APPAN RAJ D PGT- CS/IP 27


7. (i) import pickle
(ii) Statement 2: fblock = open("blocked.dat", 'wb')
Statement 3: funblock = open("unblocked.dat", 'wb')
(iii) pickle.load(fin)
(iv) Statement 5: pickle.dump(rec, fblock)
Statement 6: pickle.dump(rec, funblock)
8. a) import csv # Statement 1
b) csvwriter.writerows(d) # Statement 2
c) head = next(csvreader) # Statement 3
d) csvreader # Statement 4
*****************************************************************

APPAN RAJ D PGT- CS/IP 28


CHAPTER 5 – INTRODUCTION TO STACK
PRACTICE QUESTIONS

OBJECTIVE TYPE MCQ


1. (b) STACK
2. (d) LIFO
3. (b)Last in First Out
4. (c)Persons buying movie tickets from a counter
5. (b) Top
6. (c)PUSH and POP
7. (a) peak operation
8. (a) Simulation of recursion
9. (c) Push
10. (d) Pop
11. (d) Overflow
12. (d) Top
13. (b) Overflow
14. (c) Underflow
15. (b) Top ==len(st)-1
16. (d) IndexError: pop from empty list
17. (a) 8 5 2 5 1
18. 1. Stack = [] 2. len(list_all) 3. Stack.append(i)
4. print(Stack) 5. len(Stack) == 0 6. Stack.pop()
3- MARKS
1. stack = []
def PUSH(Arr):
for num in Arr:
if num % 5 == 0:
stack.append(num)
if len(stack) > 0:
print("Stack contents:")
for item in stack:
print(item)
else:
print("Error: Stack is empty.")
# Example usage:
arr = [10, 15, 20, 25, 30, 35]
PUSH(Arr)

APPAN RAJ D PGT- CS/IP 29


2. def POP(Arr):
if Arr==[]:
print("Stack is Empty")
else:
print(Arr.pop())
3. def Push():
for i in N:
if i%2==0:
S.append(i)
print(S)

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())

L = [5, 15, 21, 30, 45, 50, 60, 75]


S=[]
Push()
Pop()

APPAN RAJ D PGT- CS/IP 30


5. def Push():
for i in N:
if 10<= abs(i)<=99:
S.append(i)
print(S)

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)

APPAN RAJ D PGT- CS/IP 31


7. Status=[]
def Push_element():
doc_id = input("Enter Doctor ID: ")
doc_name = input("Enter Doctor Name: ")
pno= input("Enter Phone Number: ")
specialization = input("Enter Specialization: ")
L=[doc_id,doc_name,phone_number,pno,specialization)
if specialization=="Anesthesia ":
status.append(L)

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])

APPAN RAJ D PGT- CS/IP 32


10. Stack=[]
def message(string):
for i in string:
if i.isupper():
Stack.append(i)
def Pop():
if Stack==[]:
print("Stack is empty")
else:
print(Stack.pop())
11. R={"OM":76,"JAI":45,"BOB":89,"ALI":65,"ANU":90,"TOM":82}
STU_NAME=[]
def Push():
for i in R:
if R[i]>75:
STU_NAME.append(i)
def Pop():
if STU_NAME==[]:
print("Underflow")
else:
print(STU_NAME.pop())

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)

APPAN RAJ D PGT- CS/IP 33


13. def Push_na():
for i in range(len(Lname)):
if Lage[i] > 50:
Lnameage.append((Lname[i], Lage[i]))

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)

Lname = ['narender', 'jaya', 'raju', 'ramesh', 'amit', 'anu']


Lage = [45, 23, 59, 34, 51, 43]
Lnameage = []
Push_na()
print("Lnameage stack is ",Lnameage)
Pop_na()

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()

APPAN RAJ D PGT- CS/IP 34


15. stack_roll=[]
stack_mark=[]
def Push_stu():
for i in stu:
if stu[i]>60:
stack_roll.append(i)
stack_mark.append(stu[i])
def Pop_stu():
if stack_roll==[] and stack_mark==[]:
print("Underflow")
else:
print("The deleted roll no,marks are:")
print(stack_roll.pop())
print(stack_mark.pop())

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)
*********************************************************************

APPAN RAJ D PGT- CS/IP 35


CHAPTER 6 – INTRODUCTION TO DBMS AND ITS CONCEPTS

OBJECTIVE TYPE QUESTIONS


1. (a) Relational Database Management System
2. (b) tuple
3. (a) 13,8
4. A database can have only one table(True/False)
5. (d)Data Redundancy
6. (c) view
7. (d)5, 3
8. (a) Degree
9. (b) Cardinality
10. (c) Alternate Key
11. (b) Relations
12. (b)Foreign Key
13. (b) Tuple
14. (d) Street
15. (b) Primary
16. (d) yyyy-mm-dd
17. 8,15
18. (a) 1
19. (c) More than two

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);

APPAN RAJ D PGT- CS/IP 36


2. (i) ALTER TABLE INFANT ADD PRIMARY KEY (Itemcode);
(ii) ALTER TABLE INFANT DROP COLUMN DISCOUNT;
(iii) (a) DESCRIBE INFANT; (or) DESC INFANT;
(b) Cardinality: 5 Degree: 5

(OR)

(iii) (a) INSERT INTO INFANT VALUES (106, 'BathTub',


'2015-10-22', 1500);
(b) SELECT ITEM, UNITPRICE FROM INFANT ORDER BY
UNITPRICE DESC;
3. (i) Candidate key(s): EMP_NO, ACCT_NO
Primary Key: EMP_NO
(ii). Cardinaliry: 7, Degree: 8
(iii)
(a) INSERT INTO SALES_DONE VALUES (106, 'Venkatesh
Gour', 256489, 200, 300);
(b) UPDATE SALES_DONE SET NAME = 'Sri Nikethan' WHERE
EMP_NO = 104;
(OR)
(iii)
(a) ALTER TABLE SALES_DONE ADD Total_sales INT NOT
NULL;
(b) UPDATE SALES_DONE SET Total_sales = Jan + Feb;
4. (i) Bookno
(ii) Cardinality: 7, Degree: 4
(iii) UPDATE COLLECTIONS SET Quantity=Quantity+20
WHERE Qty < 50;
(iv) (a) DELETE FROM Collections;

5. (i) SELECT * FROM ITEM WHERE Category IN ('Kitchen',


'Living') ORDER BY Price DESC;
(ii) SELECT Type, AVG(Price) FROM ITEM GROUP BY Type;
(iii)
(a) SELECT MAX(Stockdate) FROM ITEM;
(b) SELECT ITEMNAME FROM ITEM WHERE ITEMNAME
LIKE '%S';
(or)
(a) DELETE FROM ITEM WHERE PRICE < 10000;
(b) UPDATE ITEM SET PRICE = 1000 WHERE PRICE IS NULL;

APPAN RAJ D PGT- CS/IP 37


6. (a) ItemNo
(b) INSERT INTO ITEMS VALUES (2010, 'Notebook', 23, 155);
(c)
(i) DROP TABLE STORE;
(ii) DESC INTEMS;
(OR)
(i) ALTER TABLE STORE ADD PRICE DECIMAL(10,2);
(ii) ALTER TABLE STORE DROP COLUMN PRICE;
7. (i) We cannot take Primary key, Even We cannot take
ROLL_NO column. Because it contains Duplicate Roll
number 103 as last record.
(ii) Cardinality: 6, Degree: 8
(iii) Write the statements to:
a. INSERT INTO your_table_name VALUES (108, 'Aaditi', 470,
444, 475, 'I');
b. UPDATE RESULT SET SUB2 = SUB2+(SUB2 * 0.03)
WHERE SNAME LIKE 'N%';
OR (Option for part iii only)
(iii) Write the statements to:
a. DELETE FROM RESULT WHERE GRADE = 'IV';
b. ALTER TABLE RESULT ADD COLUMN REMARKS
VARCHAR(50);

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;
************************************************************************

APPAN RAJ D PGT- CS/IP 38


CHAPTER 7 – INTRODUCTION TO SQL AND ITS CONCEPTS

OBJECTIVE TYPE QUESTIONS (MCQ)


1. (a) Tables
2. (c) Schema
3. (a)Number of columns and Number of rows
4. (c) Foreign Key
5. (b) Primary
6. (b) Tuple
7. (b) alter
8. (b) Key
9. (b) Tuple
10. (d) Street
11. (d) ID
12. (a)Attribute
13. (b) Manipulation & processing of the database
14. (b) varchar(n)
15. (b) The mark column will always take a value equal to 10.
16. (d) yyyy-mm-dd
17. (d)Select
18. (a)Use
19. (a) 30 7500
20. (b)not null
21. (d) float
22. (b) Distinct
23. (c) Structured query language
24. (a) DDL
25. (d) DROP
26. (a) DDL
27. (d) All of these
28. (b) Create database databasename;
29. (a) Show databases;
30. (c) Use <databasename>;
31. (b) Use database_name; show tables;
32. (b) DDL

APPAN RAJ D PGT- CS/IP 39


33. (b) Values
34. (c) Desc emp;
35. (b) 6,20
36. (a) LIKE only
37. (c) 25, 35, 38 (d) 25, 25, 35, 35
38. (a) The AS clause in SQL is used to change the column
name in the output or assign a name to a derived
column.
39. (a)Where
40. (a) =
41. (b) Tuples with no null values
42. (c) Drop database database_name
43. (a) SELECT * WHERE RNO>100 FROM STU;
44. (c) In
45. (c) Ascending
46. (a) Composite Key (b) ALTER TABLE
47. (d) DELETE FROM TEMP;
48. (a) DML
49. (c) Fixed, Variable
50. (a) Atleast, Exactly
51. (a) SELECT * FROM EMP WHERE NAME LIKE "_A%";
52. (b) UPDATE STUDENT SET FEES=FEES*0.1;
53. (b) When an exact match is not possible in a SELECT statement.
54. (c) alter
ALTER, UPDATE, DELETE,DROP
55. (c) alter
56. (a) DELETE
57. (b) It decreases the salary of all the employees by 110%.
58. (d) All of the mentioned
59. (b) ALTER TABLE R DROP A
60. (a) DELETE,DROP
61. (b) DDL
AGGREGATE FUNCTIONS
62. (b) Multi row
63. (d) 6
64. (c) 61

APPAN RAJ D PGT- CS/IP 40


65. (a) Aggregate functions ignore NULL
66. (b) AVG
67. (d) All of the above
68. (a) MAX()
69. (c) Null value
70. (b) Null values
71. (b) 2.8
72. (c) 4
73. (d) 51000
74. (a) SELECT COUNT(Project) FROM Students
75. (a) 3 70000
76. (c) COUNT(),MAX(),SUM()
77. (b) Having, where
ORDER BY, GROUP BY , HAVING
78. (c) ORDER BY
79. (a) SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
80. Where, having
81. (b) ASC
82. (d) Having
83. (c) SELECT * FROM EMP ORDER BY ENAME DESC, DEPT;
84. (a) ascending, descending
85. (a) ALTER TABLE TEACHER ADD COLUMN FEES FLOAT;
86. (b) A 84
87. (a) To filter out the summary groups
88. (c) SELECT city, temperature FROM weather ORDER BY
temperature;
89. (c) Acts like a WHERE clause but is used for groups rather
than rows.
90. (b) SELECT COUNT (*) FROM ORDERS;
JOINS
91. (c) CROSS JOIN
92. (d) All of the Mentioned
93. (b) Inner Join

94. (c) Cartesian Product


95. (d) Cartesian product
96. (c) Select * FROM Table1 T1, Table1 T2;

APPAN RAJ D PGT- CS/IP 41


97. (b) SELECT PNAME,GNAME FROM GAMES,PLAYERS
WHERE GAMES.G1D=PLAYERS.G1D;
98. (a) Equi-join
99. (c) The having clause allows only those tuples that have
average balance 10000.
3 MARKS (OR) 4 MARKS
1. (a) SHOW DATABASES;
(b) USE STOCK;
(c) DESCRIBE ITEMS; (or) DESC STOCK.ITEMS;
2. (i) SELECT * FROM HOTEL WHERE LOCATION= 'LONDON';
(ii) SELECT * FROM HOTEL WHERE ROOM_TYPE = 'DELUXE'
AND PRICE > 6000 ORDER BY PRICE ASC;
(iii) SELECT H_NAME FROM HOTEL WHERE H_NAME LIKE
'%E';
(iv) SELECT ROOM_TYPE, COUNT(*) FROM HOTEL GROUP BY
ROOM_TYPE;
(v) SELECT H_NAME FROM HOTEL ORDER BY H_NAME
DESC;
3. (a) SELECT * FROM CUSTOMER WHERE NAME LIKE 'A%';
(b) SELECT NAME, BALANCE FROM CUSTOMER C,
TRANSACTION T WHERE GENDER = 'F' AND (YEAR(TDATE)
= 2019 AND C.ACNO=T.ACNO)
(c) SELECT GENDER, COUNT(*) FROM CUSTOMER GROUP BY
GENDER;
(d)(i) SELECT NAME, BALANCE FROM CUSTOMER ORDER BY
GENDER ASC;
(ii) SELECT NAME, (BALANCE * 0.08) AS INTEREST FROM
CUSTOMER;
4. (a) SELECT dept, SUM(comm) FROM EMP GROUP BY dept;

(b)
(a)
10+ QTY
13
PRICE*QTY
(b) 55.00
75.80

APPAN RAJ D PGT- CS/IP 42


5. (a) SELECT * FROM FURNITURE ORDER BY ITEM DESC;
(b) SELECT TYPE, COUNT(*) FROM FURNITURE GROUP BY
TYPE;
(c) SELECT MAX(PRICE) FROM FURNITURE;
(d) SELECT ITEM, ROUND(PRICE, 1) FROM FURNITURE;
6.
(i) (ii)

(iii) (iv)

7. (i)

(ii)

(iii)

APPAN RAJ D PGT- CS/IP 43


(iv)

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;

APPAN RAJ D PGT- CS/IP 44


10.
ENAME DNAME
NUSRAT ADMIN
KABIR ACCOUNTS
11. (a)

(b)

12. Cartesian Product: Cardinality: 9, Degree: 5


Natural Join: Cardinality: 3 , Degree: 4
13. Faculty_Id Name Stu_id Stu_Name
F100 Govardhan 12101 Anitha
F100 Govardhan 12102 Vishnu
F101 Janet 12101 Anitha
F101 Janet 12102 Vishnu
F102 Rithu 12101 Anitha
F102 Rithu 12102 Vishnu
14. (i) SELECT ANAME FROM ACTOR WHERE ANAME LIKE
'%CH%';
(ii) SELECT ANAME FROM ACTOR WHERE ANAME LIKE '_____'
AND ANAME LIKE '_O%'; (Or) SELECT ANAME FROM
ACTOR WHERE ANAME LIKE '_o___';
15. Rows: 2 , Columns: 4

APPAN RAJ D PGT- CS/IP 45


16. a) Union operation on MUSIC and DANCE.

b) Intersection operation on MUSIC and DANCE.

17. 1.

2.

APPAN RAJ D PGT- CS/IP 46


18. (a)

(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';

APPAN RAJ D PGT- CS/IP 47


20. (i) SELECT D_NAME, COUNT(EMP_ID) FROM DEPARTMENT D
JOIN EMPLOYEE E ON D.DEPT_ID = E.DEPT GROUP BY
DEPT HAVING COUNT(EMP_ID) > 1;
(ii) SELECT D_NAME, SUM(SALARY) FROM DEPARTMENT D ,
EMPLOYEE E WHERE D.DEPT_ID = E.DEPT GROUP BY
DEPT HAVING SUM(SALARY) > 100000;
(iii) SELECT NAME FROM EMPLOYEE ORDER BY JOIN_DT
DESC;
21. (i)
DEPARTMENT MAX(SALARY)
Computer Sc 21000
History 40000
Mathematics 30000

(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

APPAN RAJ D PGT- CS/IP 48


(ii)
STREAM COUNT(*)
PCMC 1
PCMB 1

(iii)
AGE STREAM
15 BS
15 BS
(iv)
ROLLNO STREAM
A04 PCMB

APPAN RAJ D PGT- CS/IP 49


23. (i)
MAX(DOB)
2003-11-10
(ii)
DISTINCT EVENT
DEBATE
QUIZ
CROSSWORD

(iii)
COUNT(DISTINCT(CLASS))
3

(iv) SELECT MAX(DOB), PNO FROM PARTICIPANTS GROUP BY


PNO HAVING COUNT(*)>1;
MAX(DOB) PNO

APPAN RAJ D PGT- CS/IP 50


24. Correct Question is:
Consider the following Tables Trainer and Course. Write the
Output for the following queries.

TABLE: TRAINER

TABLE: COURSE

(i)
TID TNAME
101 SUNAINA
102 ANAMIKA
104 MEENAKSHI
105 RICHA

(ii)
TID
101
102
103
104
105

APPAN RAJ D PGT- CS/IP 51


(iii)
TID COUNT(*) MIN(FEES)
101 2 12000

(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

APPAN RAJ D PGT- CS/IP 52


26. Write the SQL commands for the following:
(i) SELECT FIRSTNAME, LASTNAME, ADDRESS, CITY FROM
EMPLOYEES WHERE CITY = 'PARIS';
(ii) SELECT * FROM EMPLOYEES ORDER BY FIRSTNAME
DESC;
(iii) SELECT FIRSTNAME, LASTNAME, (SALARY + BENEFITS)
AS TOTALSALARY FROM EMPLOYEE E, EMPSALARY ES
WHERE E.EMPLOYEEID = ES.EMPLOYEEID AND
DESIGNATION = 'Manager';
(iv) SELECT MAX(SALARY) FROM EMPSALARY WHERE
DESIGNATION IN ('MANAGER', 'CLERK');
(v) SELECT AVG(SALARY) FROM EMPSALARY WHERE
DESIGNATION= 'CLERK';

27. (i) INSERT INTO HOUSE VALUES('Tulip','Rajesh',278)


(ii)
Sol:
(i)
COUNT(*) City
2 Mumbai
2 Delhi
2 Moscow

(ii)
MAX(DOB) MIN(DOB)
08-12-1995 07-05-1993

(iii)
NAME GENDER
Sanal F
Store M
(iv)
DISTINCT Class
X
XII
XI

APPAN RAJ D PGT- CS/IP 53


28. (i)
ROLL_NO AGE GNAME
A06 22 CRICKET
(ii)
AGE GENDER
16 M
22 O
(iii)
SNAME GENDER
AKILAN S M
AVINESH M
DEEPAK M
(iv)
GENDER AVG(TOTAL)
M 430
F 456
29. (i) SELECT SURNAME, FIRSTNAME, CITY FROM PERSONS
WHERE CITY = 'UDHAMWARA';
(ii) SELECT PID, CITY, PINCODE FROM PERSONS ORDER BY
PINCODE DESC;
(iii) SELECT FIRSTNAME, CITY FROM PERSONS WHERE
GENDER = 'F' AND BASICSALARY> 40000;
(iv) SELECT FIRSTNAME, BASICSALARY FROM PERSONS
WHERE FIRSTNAME LIKE 'G%';
30. (i)
MAX(FEES) MIN(FEES)
6000 4000
(ii)
COUNT(DISTINCT SNAME)
4
(iii)
SNAME SUM(No_of_Players)
Foot Ball 25
Basket Ball 80
Volley Ball 25
Kho-Kho 40
(iv)
AVG(FEES*No_of_players)
210000

APPAN RAJ D PGT- CS/IP 54


31. (i) SELECT NAME FROM DOCTOR WHERE DEPT =
'ORTHOPEDIC' AND EXPERIENCE > 10;
(ii) SELECT AVG(BASIC+ALLOWANCE) FROM DOCTOR,SALARY
WHERE DEPT="ENT" AND DOCTOR.ID=SALARY.ID;
(iii) SELECT MIN(ALLOWANCE) FROM DOCTOR D,SALARY S
WHERE SEX="F" AND D.ID=S.ID
(iv) SELECT MAX(CONSULATION) FROM DOCTOR,SALARY
WHERE SEX="M" AND DOCTOR.ID=SALARY.ID

**********************************************************

APPAN RAJ D PGT- CS/IP 55


CHAPTER – 8
(INTERFACING PYTHON WITH MYSQL)

STATE TRUE OR FALSE


1. True
2. False
3. True
4. True
5. True
6. True
7. True
8. False
9. True
10. False
OBJECTIVE TYPE QUESTIONS (MCQ)
1. (b) pip install mysql-connector import mysql.connector
2. (a) mysql-connector
3. (c) Username, Password, Hostname, Database Name
4. (c) 4
5. (a) connect()
6. (b) import mysql.connector
7. (a) connect()
8. (d) 0
9. (d) table
10. (a) connect(host="localhost", user="root", database="School")
11. (a) cursor
12. (b) INSERT
13. (d) List of Tuples (or) A list
Reason:
When the fetchall() method is used in Python-MySQL connectivity,
it indeed returns a list. However, each element of this list
represents a row retrieved from the table, and each row is stored as
a tuple.

So, while it returns a list, the elements of that list are tuples.
14. (a) sql module

APPAN RAJ D PGT- CS/IP 56


15. (d) password
16. (c) fetchone
17. (c) rowcount
18. (b)executemany
Reason:
To insert multiple rows into the database with one SQL statement,
the executemany() method should be used, as it efficiently handles
the bulk insertion of data. Therefore, the explanation for using
executemany() is correct.
19. (c) -1 (Because, immediately after executing a SELECT
statement, the rowcount attribute will be -1)
Reason:
The rowcount attribute of the cursor refers to the number of rows
that were affected by the last operation. For operations like
INSERT, UPDATE, or DELETE, rowcount will reflect the
number of affected rows. However, for a SELECT statement,
the rowcount attribute is not applicable immediately after
executing the query. It remains at -1 until you actually fetch some
rows from the result set.
20. (b)3
21. (b) execute()
22. (c) connection.close()
23. (b) Cursor.execute(Query)
24. (b) commit()
25. (b) fetchall()
26. (a) Fetch the next row of a query result set, returning a single
tuple, or None when no more data is available.
27. (a) Tuple
28. (b) List
29. (a) None
30. (c) Empty List
31. (c) Empty List
32. (c) connect( )

APPAN RAJ D PGT- CS/IP 57


3- MARKS (MISSING STATEMTS)
1. Statement 1: mysql.connector as ms
Statement 2: mycursor.excute("SELECT * FROM TEACHER
WHERE YEAR(RET)=2022")
Statement 3: mycursor.fetchall()
2. 1.
host="localhost",user="root",password="root",database="school"
2. con.cursor()
3. cur.fetchall()
4. cur.rowcount
3. Statement 1: mycursor.execute("USE MY")
Statement 2: mycursor.execute(Q)
Statement 3: con1.commit()
4. Statement 1: connection.cursor()
Statement 2: cursor.execute("INSERT INTO EMPLOYEE
VALUES({ },'{ }',{ })".format(empid,name,salary)
Statement 3: connection.commit()
5. Statement 1 – con.cursor()
Statement 2 – cursor.execute("SELECT * FROM EMPLOYEE
WHERE SALARY>25000")
Statement 3- cursor.fetchall()
6. i.mysql.connector
ii. cursor()
iii. 5000
iv. fetchall()
4 MARKS
1. import mysql.connector as q
def Write():
con=q.connect(host='localhost',user='root',password='tiger',
database='SCHOOL')
try:
if con.is_connected():
cur=con.cursor()
Rollno=int(input("Enter Roll number:"))
Name=input("Enter Name:"))
DOB=input("Enter your DOB:")

APPAN RAJ D PGT- CS/IP 58


Fee=float(input("Enter the Fees:"))
Q="INSERT INTO STUDENT VALUES ({},'{}','{}',{})"
.format(Rollno,Name,DOB,Fee)
cur.execute(Q)
con.commit()
except:
con.close()
2. import mysql.connector as q
def Write():
con=q.connect(host='192.160.1.2',user='root',
password='root',database='SHOP')
try:
if con.is_connected():
cur=con.cursor()
Q1="SELECT * FROM BOOKS WHERE DOB
BETWEEN '2000-05-09' AND '2001-11-23'"
cur.execute(Q)
D=cur.fetchall()
print(D)
Q2="UPDATE BOOKS SET PRICE=PRICE-(PRICE*0.07)
WHERE PRICE>900 AND AUTHOR='ANU'"
cur.execute(Q2)
con.commit()

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)”

APPAN RAJ D PGT- CS/IP 59


cur.execute(Q1)
Q2="ALTER TABLE EMP ADD BONUS INT"
cur.execute(Q2)
except:
pass
con.close()
4. import mysql.connector as q
def Write():
con=q.connect(host='localhost',user='root',
password='writer',database='LIBRARY')
try:
if con.is_connected():
cur=con.cursor()
Q="SELECT B_NAME FROM BOOK WHERE PRICE >
250”
cur.execute(Q)
D=cur.fetchall()
print(D)
except:
pass
con.close()
CASE STUDY BASED 2 - MARKS
1. (i) mysql.connector
(ii) execute()
(iii) mysql.connector.connect(host='192.168.11.111',

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
**************************************************************

APPAN RAJ D PGT- CS/IP 60

You might also like