70 Important Question CS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Unit 1: Computational Thinking and Programming – 2

Chapter1:basic of python and functions

Q1) State True or False –


“Variable declaration is implicit in Python.”
-----------------------------------------------------------------------------------------------------------------------------------
Ans. TRUE
Q2) Which of the following is an invalid datatype in Python?
(a) Set (b) None (c)Integer (d)Real
Ans: (d) Real
-----------------------------------------------------------------------------------------------------------------------------------

Q3) Q1 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the minimum values that can be assigned to each of the
variables BEGIN and LAST.
import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3)
LAST = random.randint(2, 4)
for I in range (BEGIN, LAST+1):
print (VALUES[I], end = "-")
(i) 30-40-50- (ii) 10-20-30-40- (iii) 30-40-50-60- (iv) 30-40-50-60-70-
OUTPUT – (i) 30-40-50- Minimum value of BEGIN: 1 Minimum value of LAST: 2
-----------------------------------------------------------------------------------------------------------------------------------

Q4) What possible outputs(s) are expected to be displayed on screen at the time of execution of the program
from the following code? Also specify the maximum values that can be assigned to each of the variables
FROM and TO.
import random AR=[20,30,40,50,60,70]
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO):
print (AR[K],end=”#“)
(i)10#40#70# (ii)30#40#50# iii)50#60#70# (iv)40#50#70#
AnsMaximum value of FROM = 3
Maximum value of TO = 4
(ii) 30#40#50#
Q5) Q4 Consider the following code and find out the possible output(s) from the options given below. Also
write the least and highest value that can be generated.
import random as r
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(1 + r.r ndint(1 ,1 ) , end = ‘ ‘)
print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20 ii) 23 27 22 20 iv) 21 25 20 24
Ans
Possible outputs : i), iii) and iv)
Least value : 10
Highest value : 15
-----------------------------------------------------------------------------------------------------------------------------------

Q6) Assertion (A):- If the arguments in a function call statement match the number and order of arguments
as defined in the function definition, such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s) followed by
positional argument(s).
Ans: (c) A is True but R is False
-----------------------------------------------------------------------------------------------------------------------------------
Q7) Rao has written a code to input a number and check whether it is prime or not. His code is having
errors. Rewrite the correct code and underline the corrections made.
def prime():
n=int(input("Enter number to check :: ")
for i in range (2, n//2):
if n%i=0:
print("Number is not prime \n") break
else:
print("Number is prime \n’)
Ans:
def prime():
n=int(input("Enter number to check :: ")) #bracket missing
for i in range (2, n//2):
if n%i==0: # = missing
print("Number is not prime \n")
break #wrong indent
else:
print("Number is prime \n”) # quote mismatch
Q8) (a)Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
Ans: @20 otnmx SC@
-----------------------------------------------------------------------------------------------------------------------------------

Q8)Write the output of the code given below: my_dict = {"name": "Aman", "age": 26} my_dict['age'] = 27
my_dict['address'] = "Delhi" print(my_dict.items())
Ans: dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
-----------------------------------------------------------------------------------------------------------------------------------

Q9) Predict the output of the Python code given below:

def Diff(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
NUM= [10,23,14,54,32]
for CNT in range (4,0,-1):
A=NUM[CNT]
B=NUM[CNT-1]
print(Diff(A,B),'#', end=' ')
Ans: 22 # 40 # 9 # 13 #
-----------------------------------------------------------------------------------------------------------------------------------

Q10) Predict the output of the Python code given below:


tuple1 = (11, 22, 33, 44, 55 ,66)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%2==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
Ans: (22,44,66)
-----------------------------------------------------------------------------------------------------------------------------------

Q11) Given the following dictionaries

dict_exam={"Exam":"AISSCE", "Year":2024} dict_result={"Total":500, "Pass_Marks":165}

Which statement will merge the contents of both dictionaries?


a. dict_exam.update(dict_result)
b. dict_exam + dict_result
c. dict_exam.add(dict_result)
d. dict_exam.merge(dict_result)

Ans: (a) dict_exam.update(dict_result)


-----------------------------------------------------------------------------------------------------------------------------------

Q12) Select the correct output of the code:


a = "Year 2022 at All the best"
a = a.split('2')
b = a[0] + ". " + a[1] + ". " + a[3]
print (b)

a. Year . 0. at All the best


b. Year 0. at All the best
c. Year . 022. at All the best
d. Year . 0. at all the best

Ans: (a) Year . 0. at All the best


-----------------------------------------------------------------------------------------------------------------------------------

Q13) What will the following expression be evaluated to in Python?


print(15.0 / 4 + (8 + 3.0))
(a) 14.75 (b)14.0 (c) 15 (d) 15.5
-----------------------------------------------------------------------------------------------------------------------------------

Q14) A _________ statement skips the rest of the loop and jumps over to the statement following the loop.
Ans) break
-----------------------------------------------------------------------------------------------------------------------------------

Q15). Python's __________ cannot be used as variable name.


Ans.keywords
-----------------------------------------------------------------------------------------------------------------------------------
Unit 1: Computational Thinking and Programming – 2
Chapter2:Exceptional handling

Q16) Explain Raise keyword with Example?


Ans: The raise keyword is used to manually raise an exception like exceptions are raised by Python itself.
That means, as a programmer can force an exception to occur through raise keyword. It can also pass a
custom message to your exception handling module.
ii.a = int( input("Enter value for a :"))
b = int( input("Enter value for b :"))
try:
if b == 0:
raise ZeroDivisionError :# raising exception using raise keyword
print(a/b)
except ZeroDivisionError:
print("Please enter non-zero value for b.")
-----------------------------------------------------------------------------------------------------------------------------------
Q17) Which exception is raised when attempting to access a non-existent file?
- A. FileNotFoundError - B. FileNotAccessibleError
- C. NonExistentFileError - D. InvalidFileAccessError
Answer: A
-----------------------------------------------------------------------------------------------------------------------------------
Unit 1: Computational Thinking and Programming – 2
Chapter3:File handling
Q18) Define all the Access Mode of file?
Ans)

-----------------------------------------------------------------------------------------------------------------------------------

Q19)Write the different Between CSV ,Binary and Text file?


Ans
TYPES OF FILE
TEXT FILE
1) A text file stores information in ASCII or unicode characters
2) each line of text is terminated, (delimited) with a special character known as EOL
BINARY FILES
1) A binary file is just a file that contains information in the same format in which the information is held in
memory i.e the file content that is returened to you is raw.
2) There is no delimiter for a line
3) No translation occurs in binary file
4) Binary files are faster and easier for a program to read and write than are text files.
5) Binary files are the best way to store program information.
CSV FILES
1) CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
2) CSV stands for "comma-separated values“.
3) A comma-separated values file is a delimited text file that uses a comma to separate values.
4) Each line of the file is a data record. Each record consists of one or more fields, separated by commas.
The use of the comma as a field separator is the source of the name for this file format
-----------------------------------------------------------------------------------------------------------------------------------

Q20) write a method in python to read lines from a text file MYNOTES.TXT and display those lines which
start with alphabets 'K'
Ans) def display ():
file=open(MYNOTES.TXT’ , ‘r’)
lines=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
file.close()
-----------------------------------------------------------------------------------------------------------------------------------

Q21) write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting with @
sign.
Ans) def filter (oldfile, newfile):
fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)
-----------------------------------------------------------------------------------------------------------------------------------
Q22) What is pickling and unpickling of data?
Ans) Pickling is the process of transforming data or an object in memory (RAM) to a stream of bytes called
byte streams. These byte streams in a binary file can then be stored in a disk or in a database or sent through
a network. Unpickling is the inverse of pickling process where a byte stream is converted back to Python
object.
-----------------------------------------------------------------------------------------------------------------------------------

Q23) Amritya Seth is a programmer, who has recently been given a task to write a python code to perform
the following binary file operations with the help of two user defined functions/modules: a. AddStudents() to
create a binary file called STUDENT.DAT containing student information – roll number, name and marks
(out of 100) of each student. b. GetStudents() to display the name and percentage of those students who have
a percentage greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent.
Ans)
i.import pickle
def AddStudents():
F= open("STUDENT.DAT",'wb')
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
c. pickle.dump(L,F)
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
R = pickle.load(F)
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
F.close()
-----------------------------------------------------------------------------------------------------------------------------------

Q24) What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user defined functions:
a. ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a
list with field elements as empid, name and mobile to store employee id, employee name and employee
salary respectively.
b. COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.

Ans:
Advantage of a csv file:
• It is human readable – can be opened in Excel and Notepad applications
• It is just like text file

Program:
import csv
def ADD():
fout=open("record.csv","a",newline="\n")
wr=csv.writer(fout)
empid=int(input("Enter Employee id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter mobile number :: "))
lst=[empid,name,mobile]
wr.writerow(lst)
fout.close()
def COUNTR():
fin=open("record.csv","r",newline="\n")
data=csv.reader(fin)
d=list(data)
print(len(d))
fin.close()
ADD()
COUNTR()
-----------------------------------------------------------------------------------------------------------------------------------

Q25) Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:

a. add() – To accept and add data of an employee to a CSV file ‘furdata.csv’. Each record consists of
a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price
respectively.
b. search()- To display the records of the furniture whose price is more than 10000.

Ans)
• Binary file:
• Extension is .dat
• Not human readable
• Stores data in the form of 0s and 1s
CSV file
• Extension is .csv
• Human readable
• Stores data like a text file
Program:
import csv
def add():
fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout)
fid=int(input("Enter Furniture Id :: "))
fname=input("Enter Furniture name :: ")
fprice=int(input("Enter price :: "))
FD=[fid,fname,fprice]
wr.writerow(FD)
fout.close()
def search():
fin=open("furdata.csv","r",newline='\n') data=csv.reader(fin)
found=False
print("The Details are") for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
add()
print("Now displaying")
search()
-----------------------------------------------------------------------------------------------------------------------------------

Q26)Write stack program to enter detail of person who live in delhi. And pop() function for delete?
def Push_record(List):
for i in List:
if i[2]=="Delhi":
Record.append(i)
print(Record)
def Pop_record():
while True:
if len(Record)==0:
print('Empty Stack')
break
else:
print(Record.pop())
-----------------------------------------------------------------------------------------------------------------------------------
Q27) Add element in the stack and pop element from the stack using function()?
Ans)
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PushElement(S,N):
S.append(N)
def PopElement(S):
if S!=[ ]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%7==0:
PushElement(ST,k)
while True:
if ST!=[ ]:
print(PopElement(ST),end=" ")
else:
break
Unit 1: Unit 2: Computer Networks
Chapter4: Unit 2: Computer Networks

Q28) Fill in the blank:

is a communication methodology designed to deliver both voice and multimedia


communications over Internet protocol.

(a) VoIP (b) SMTP (c) PPP (d)HTTP

Ans: (a) VoIP


-----------------------------------------------------------------------------------------------------------------------------------

Q29)

-----------------------------------------------------------------------------------------------------------------------------------

Q30) Write two points of difference between XML and HTML.


Ans:
XML (Extensible MarkupLangauge)
• XML tags are not predefined, they are user defined
• XML stores and transfers data.
• Dynamic in nature
• HTML (Hypertext Markup Langauge)
• HTML tags are pre-defined and it is a markup language
• HTML is about displaying data.
• Static in nature
-----------------------------------------------------------------------------------------------------------------------------------

Q31) (i) Expand the following terms: SMTP , PPP


(ii) Give one difference between Web browser and Web Server.
Ans) (i) PPP - Point to Point Protocol, SMTP - Simple Mail Transfer Protocol
(ii) Websites are stored on web servers, web browser is the client which makes a request to the server
-----------------------------------------------------------------------------------------------------------------------------------

Q32
(i) Define network device Gateway with respect to computer networks.
(ii) How is ARPANET different from NSFNET?
Ans) (i) Gateway serves as the entry and exit point of a network, as all data coming in or going out of a
network must first pass through the gateway in order to use routing paths. It's a device that connects
dissimilar networks.
(ii) ARPANET (Advanced Research Project Agency Network): It is a project sponsored by U. S. Department
of Defense to connect the academic and research institutions located at different places for scientific
collaborations
-----------------------------------------------------------------------------------------------------------------------------------
Q33)
-----------------------------------------------------------------------------------------------------------------------------------

Q34) What are Protocols? Name the protocol used to transfer a file from one device to the other.
Ans Protocols are set of rules that are followed while transmitting data through a computer network.
Protocols determines how to data can be moved securely from a source device to a destination device. The
protocol used for transferring a file from one device to another is the File Transfer Protocol (FTP)
-----------------------------------------------------------------------------------------------------------------------------------

Q35) What do you mean by an IP Address? Give an example for IP Address.


Ans An IP Address is a numerical address that uniquely identifies every device connected to a network or
internet. The user’s physical location can be tracked by using an IP Address. IP V4 (IP Version 4) is a
popular version of IP Address. IP Address (in IP V4) consists of four set of numbers separated by a dot.
These numbers can range from 0 to 255. An example IP Address format is given below: 192.158.12.38
-----------------------------------------------------------------------------------------------------------------------------------

Q36) Define the following: a. Bandwidth b. Data rate


Ans Bandwidth: It is the range of frequencies that can be carried through a communication channel. The
bandwidth of a channel determines its capacity. It is the difference between the highest and lowest
frequencies that can be carried through the channel. The unit of Bandwidth is Hertz (Hz). Data transfer rate:
It is the amount of data moved through a communication channel per unit time. The units of Data transfer
rate are Bits per second (Bps), Kilobits per second (Kbps) , Megabits per second (Mbps) or Gigabits per
second (Gbps).
-----------------------------------------------------------------------------------------------------------------------------------
Q37) What are the advantages of Packet switching over Circuit switching.
Ans In Packet Switching the communication channel is utilized completely whenever it is free. Where as in
Circuit Switching, once the connection is assigned for a particular communication, the entire channel cannot
be used for other data transmissions even if the channel is free. Data packets moves simultaneously through
different paths in a Packet Switched network, making the transmission quick and easy. But in the case of
Circuit Switched network, there is a delay in setting up a physical connection between the source and
destination before communicating the actual message. Packet Switching is cost effective compared to Circuit
Switching as there is no need to set up a connection between the communicating parties every time before
the actual communication.
-----------------------------------------------------------------------------------------------------------------------------------

Q38)Explain why Circuit Switching is not cost effective compared to Packet Switching?
Ans The Circuit Switching is not cost effective like Packet Switching because, in Circuit Switching, every
time there is a need to set up a connection between the sender and the receiver before communicating the
message.
-----------------------------------------------------------------------------------------------------------------------------------

Q39) What is the difference between E-mail and chat?


Ans In order to chat, you need to have an account on the same service as the person you are chatting with.
e.g. on the other hand, in case of E-mail, it is not necessary, i.e. you can have an account from any provider
and you can establish your own. 15 What are cookies?
-----------------------------------------------------------------------------------------------------------------------------------
Q40)
Ans)

-----------------------------------------------------------------------------------------------------------------------------------

Unit 3: DBMS
Chapter4:DBMS
Q41)Fill in the blank:
_____ is a non-key attribute, whose values are derived from the primary key of some other
table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
ANS)(B)
-----------------------------------------------------------------------------------------------------------------------------------

Q42 )An Attribute in a relations a foreign key if it is the _____ key in any other relation.
(A) Candidate Key (B) Foreign Key (C) Primary Key (D) Unique Key
Ans)c
-----------------------------------------------------------------------------------------------------------------------------------

Q43) An attribute in a relation is a foreign key if it is the ________ key in any other relation.
(A) Candidate Key (B)Foreign Key (C) Primary Key (D)Unique Key
Ans)c
-----------------------------------------------------------------------------------------------------------------------------------
Q44) _________ is an attribute, whose values are Unique and not null.
(A) Primary Key (B)Foreign Key (C)Candidate Key (D)Alternate Key
Ans)a
Q45 Select the correct statement, with reference to RDBMS:
a) NULL can be a value in a Primary Key column
b) ' ' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.
Ans)d
-----------------------------------------------------------------------------------------------------------------------------------

Q45) Differentiate between DDL and DML?


Data Definition Language (DDL): This is a category of SQL commands. All the commands which are used
to create, destroy, or restructure databases and tables come under this category. Examples of DDL commands
are - CREATE, DROP, ALTER. Data Manipulation Language (DML): This is a category of SQL commands.
All the commands which are used to manipulate data within tables come under this category. Examples of
DML commands are - INSERT, UPDATE, DELETE.
-----------------------------------------------------------------------------------------------------------------------------------

Q46) What are the differences between DELETE and DROP commands of SQL?
DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a table
while DROP is used to remove the entire table from the database.
-----------------------------------------------------------------------------------------------------------------------------------

Q47) Differentiate between WHERE and HAVING clause


WHERE clause is used to select particular rows that satisfy the condition where having clause is used in
connection with the aggregate function GROUP BY clause. FOR EXAMPLEselect * from student where
marks >80; Select * from student group by stream having marks>90;
-----------------------------------------------------------------------------------------------------------------------------------

Q49) A table "Animals" in a database has 3 columns and 10 records. What is the degree and cardinality of
this table?
ans)
Degree 3 and Cardinality=10
-----------------------------------------------------------------------------------------------------------------------------------

Q50) Fill in the blank:


The SELECT statement when combined with clause, returns records without repetition.

a. DESCRIBE
b. UNIQUE
c. DISTINCT
d. NULL

Ans: (c) DISTINCT


-----------------------------------------------------------------------------------------------------------------------------------

Q51)
Fill in the blank:
is a non-key attribute, whose values are derived from the primary key of some other table.
a. Primary Key
b. Foreign Key
c. Candidate Key
d. Alternate Key

Ans: (b) Foreign Key


-----------------------------------------------------------------------------------------------------------------------------------

Q52)
Which of the following commands will delete the table from MYSQL database?
a. DELETE TABLE
b. DROP TABLE
c. REMOVE TABLE
d. ALTER TABLE
Ans: (b) DROP TABLE
-----------------------------------------------------------------------------------------------------------------------------------

Q53) Fill in the blank:


command is used to remove primary key from a table in SQL.

a. update (b)remove (c) alter (d)drop

Ans: (c) alter


-----------------------------------------------------------------------------------------------------------------------------------
Q53) Which of the following mode in file opening statement results or generates an error if the file
does not exist?
(a) a+ (b) r+ (c) w+ (d) None of the above
Ans: (b) r+
-----------------------------------------------------------------------------------------------------------------------------------
Q54) Which type of network consists of both LANs and MANs?
a. Wide Area Network
b. Local Area Network
c. Both a and b
d. None of the above
Ans: a. Wide Area Network
-----------------------------------------------------------------------------------------------------------------------------------
Q55) How do you check if a file exists before opening it in Python?
a) Use the exists() function from the os module
b) Use the open() function with the try-except block
c) Use the isfile() function from the os.path module
d) All of the above
Ans: d) All of the above
-----------------------------------------------------------------------------------------------------------------------------------
Q56) Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give example to
support your answer.
Ans:
A foreign key is used to set or represent a relationship between two relations ( or tables) in a database. Its
value is derived from the primary key attribute of another relation.
For example:
In the tables TRAINER and COURSE given below, TID is primary key in TRAINER table but foreign key
in COURSE table.
-----------------------------------------------------------------------------------------------------------------------------------
Q57) Differentiate between COUNT() and COUNT(*) functions in SQL with appropriate example.
Ans) COUNT(*) returns the count of all rows in the table, whereas COUNT () is used with Column_Name
passed as argument and counts the number of non-NULL values in a column that is given as argument.

----------------------------------------------------------------------------------------------------------------------------------
Q58) Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
Ans:
DDL- ALTER, DROP DML – INSERT, UPDATE
-----------------------------------------------------------------------------------------------------------------------------------

Q59)

-----------------------------------------------------------------------------------------------------------------------------------

Q60) Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display
the lines which are not starting with any vowel.
Example:
If the file content is as follows:
An apple a day keeps the doctor away. We all pray for everyone’s safety.
A marked difference will come in our country.
The COUNTLINES() function should display the output as: The number of lines not starting with any vowel
-1
Ans:
def COUNTLINES() :
file = open ('TESTFILE.TXT', 'r') lines = file.readlines()
count=0
for w in lines :
if (w[0]).lower() not in 'aeoiu' count = count + 1
print ("The number of lines not starting with any vowel: ", count)
file.close()
-----------------------------------------------------------------------------------------------------------------------------------

Q61)

Ans)
(i) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE;
(ii) SELE T TNAME, TY FROM TRA NER WHERE H REDATE BETWEEN ‘ 1-12- 1’AND ‘ 1-12-31’;
(iii) SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE WHERE
TRAINER.TID=COURSE.TID AND FEES<=10000;
(iv) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;
-----------------------------------------------------------------------------------------------------------------------------------
Q62)Satyam. a database analyst has created thefollowing table:

He has written following queries:


i.select sum (Marks) from student whereOptional= 'IP' and STREAM= 'Commerce';
ii.select max (Marks) + min (Marks) fromstudent where Optional = ‘CS';
iii.select avg (Marks) from student where Optional = 'IP';
iv.select length (SName) from student where Marks is NULL;
Help him in predicting the output of the abovegiven queries

Answer: i. 193 ii. 194 iii. 93.75 iv. 6


-----------------------------------------------------------------------------------------------------------------------------------

Q63)
Ans)

-----------------------------------------------------------------------------------------------------------------------------------

Q64) 1. Write a Python code to connect to a database


Ans.
import mysql.connector
Mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”)
print(Mycon)
-----------------------------------------------------------------------------------------------------------------------------------

Q65. How to create a database in MySQL through Python ?


Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”)
cursor=mycon.cursor( )
cursor.execute(“create database student”)
mycom.close()
-----------------------------------------------------------------------------------------------------------------------------------

Q66). Write the Python code to display the present databases in MySQL
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
mycom.close()

-----------------------------------------------------------------------------------------------------------------------------------

Q67) Write the Python code to insert data into student table of database kvs in MYSQL .
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,password=”root”,database=”kvs”)
cursor=mycon.cursor()
no=int(input(“Enter roll no “))
n=input(“Enter name “)
g=input(“Enter gender ”)
dob=input(“Enter DOB “)
m=float(input(“Enter mark ”))
query= “insert into student values( {}, ‘{}’ , ‘{}’ , ’{}’ , {} )”.format( no,n,g,dob,m)
cursor.execute(query)
mycon.commit( )
----------------------------------------------------------------------------------------------------------------------------------

Q68) (i) What is the difference between degree and cardinality with respect to RDBMS. Give one example
to support your answer.
(ii) Mr. Shuvam wants to write a program in Python to Display the following record in the table named EMP
in MYSQL database EMPLOYEE with attributes: •EMPNO (Employee Number ) - integer • ENAME
(Employee Name) - string size(30) • SAL (Salary) - float (10,2) • DEPTNO(Department Number) - integer
Note: The following to establish connectivity between Python and MySQL: • Username - root • Password –
admin • Host – localhost The values of fields rno, name, DOB and fee has to be accepted from the user. Help
Shuvam to write the program in Python.
Ans)
(i) DEGREE: The number of attributes in a relation is called the Degree of the relation. For example,
relation GUARDIAN with four attributes is a relation of degree 4.
CARDINALITY: The number of tuples in a relation is called the Cardinality of the relation. For example,
the cardinality of relation GUARDIAN is 5 as there are 5 tuples in the table.
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root", passwd="admin",database="EMPLOYEE")
mycursor=mycon.cursor()
print("\nBEFORE DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
eno=int(input("Enter the empno which record you want to delete: "))
qr="DELETE FROM EMP WHERE empno={}".format(eno)
mycursor.execute(qr)
mycon.commit() # To save above DML tansactions to the databases otherwise will not save permanently
print("\nAFTER DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
mycon.close()
--------------------------------------------------------------------------------------------------------------------------------
Q69) (i) What is the difference between Primary and Foreign key?
(ii) Mr. Pranay wants to write a program in Python to update the particular record by accepting its
Department Number value in the table named DEPT in MYSQL database EMPLOYEE with attributes:
•DEPTNO (Department Number) – integer • DNAME (Department Name) – string size(15) •LOC(Location
of the Department) – string size(15) Note: The following to establish connectivity between Python and
MySQL: • Username - root • Password – admin • Host – localhost The values of fields rno, name, DOB and
fee has to be accepted from the user. Help Kabir to write the program in Python.
Ans)
(i) Primary Key: One or more than one attribute chosen by the database designer to uniquely identify the
tuples in a relation is called the primary key of that relation.
Foreign key: It is used to represent the relationship between two relations. A foreign key is an attribute
whose value is derived from the primary key of another relation.
(ii)
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root",passwd="admin", database="EMPLOYEE")
mycursor=mycon.cursor()
dno=int(input("Enter the DEPT. NO which record you want to update: "))
qr="SELECT * FROM DEPT WHERE deptno={}".format(dno)
mycursor.execute(qr)
rec=mycursor.fetchall()
print("\n Old Record is follows: ")
for k in rec:
print(k)
print("\nENTER DETAILS TO UPDATE RECORD:\n")
print("Entered DEPTNO No:",dno)
dname=input("Enter Department Name:")
loc=input("Enter Location of the Department:")
qr="UPDATE dept SET dname='{}', loc='{}' WHERE deptno={}".format(dname, loc,dno)
print(qr)
mycursor.execute(qr)
mycon.commit()
print("\nNEW RECORD AFTER UPDATE OF TABLE: ")
mycursor.execute("SELECT * FROM DEPT")
for k in mycursor:
print(k)
mycon.close()
--------------------------------------------------------------------------------------------------------------------------------
Q70) Question from PB-1(33)
Ans)
def ChecknDisplay():
import mysql.connector as mycon
mydb=mycon.connect(host="localhost",user="root", passwd="school123",database="COMPANY")
mycur=mydb.cursor()
eid=input("Enter EmpID : ")
nm=input("Enter EmpName : ")
s=input("Enter Salary: ")
dept=input("Enter Department : ")
query="INSERT INTO EMPLOYEES VALUES ({},'{}',{},’{}’)". format(eid,nm,s,dept)
mycur.execute(query)
mydb.commit()
mycur.execute("select * from EMPLOYEES where salary>50000")
for rec in mycur:
print(rec)
-----------------------------------------------------------------------------------------------------------------------------------

You might also like