Xii Comp
Xii Comp
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
18 Fill in the missing lines of code in the following code. The code reads in a limit amount and a
list of prices and prints the largest price that is less than the limit. You can assume that all
prices and the limit are positive numbers. When a price 0 is entered the program terminates
and prints the largest price that is less than the limit.
20 Write a program that reads a date as an integer in the format MMDDYYYY. The program will
call a function that prints print out the date in the format <Month Name> <day>, <year>.
Number of words
Number of characters (including white-space and punctuation)
Percentage of characters that are alpha numeric
Hints: Assume any consecutive sequence of non-blank characters in a word.
22 Write a program that rotates the elements of a list so that the element at the first index moves
to the second index, the element in the second index moves to the third index, etc., and the
element in the last index moves to the first index.
Answer:
for Name in [“_Ramesh_”, “_Suraj_” , “_Priya_”]
if Name [0] =_=‘S’ :
print (Name)
26 What do you understand by mutability ? What does "in place" task mean ?
27 Start with the list [8, 9, 10]. Do the following using list functions:
1. Set the second entry (index 1) to 17
2. Add 4, 5 and 6 to the end of the list
3. Remove the first entry from the list
4. Sort the list
5. Double the list
6. Insert 25 at index 3
28 What are the two ways to remove something from a list? How are they different ?
29 In the Python shell, do the following :Define a variable named states that is an empty list.
33 Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What
is the condition to use tuples as a key in a dictionary?
34 Dictionary is a mutable type, which means you can modify its contents? What all is modifiable
in a dictionary? Can you modify the keys of a dictionary?
35 Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple
containing length of each word of a string. For example, if the string is "Come let us have some
fun", the tuple will have (4, 3, 2, 4, 4, 3)
36 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an
argument and displays the names (in uppercase)of the places whose names are longer than 5
characters. For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"} The output should be:
LONDON NEW YORK
37 What do you understand by local and global scope of variables? How can you access a global
variable inside the function, if function has a variable with same name
****
TOPIC: FUNCTIONS IN PYTHON
1 Function name must be followed by
2 keyword is used to define a function
3 Function will perform its action only when it is
4 Write statement to call the function.
def Add():
X=10+20
print(X)
#statement to call the above function
5 Write statement to call the function.
def Add(X,Y):
Z=X+Y
print(Z)
#statement to call the above function
6 Write statement to call the function.
def Add(X,Y):
Z=X+Y
return Z
#statement to call the above function
print(“Total =”,C)
7 Which Line Number Code will never execute?
def Check(num): #Line1
if num%2==0: #Line2
print("Hello") #Line 3
return True #Line4
print("Bye") #Line5
else: #Line6
return False #Line7
C = Check(20)
print(C)
8 What will be the output of following code?
def Cube(n):
print(n*n*n)
Cube(n) # n is 10 here
print(Cube(n))
9 What are the different types of actual arguments in function? Give example of any
one of them.
10 What will be the output of following code:
def Alter(x, y = 10, z=20):
sum=x+y+z
print(sum)
Alter(10,20,30)
Alter(20,30)
Alter(100)
11 Call the given function using KEYWORD ARGUMENT with values 100 and 200
def Swap(num1,num2):
num1,num2=num2,num1
print(num1,num2)
Swap( , )
12 Which line number of code(s) will not work and why?
def Interest(P,R,T=7):I
= (P*R*T)/100
print(I)
Interest(20000,.08,15) #Line1
Interest(T=10,20000,.075) #Line2
Interest(50000,.07) #Line3
Interest(P=10000,R=.06,Time=8) #Line4
Interest(80000,T=10) #Line5
13 What will be the output of following code?
def Calculate(A,B,C):
return A*2,B*2,C*2
val = Calculate(10,12,14)
print(type(val))
print(val)
14 What are Local Variable and Global Variables? Illustrate with example
15 What will be the output of following code?
def check():
num=50
print(num)
num=100
print(num)
check()
print(num)
16 What will be the output of following code?
def check():
global num
num=1000
print(num)
num=100
print(num)
check()
print(num)
list1=[21,20,6,7,9,18,100,50,13]
Fun1(list1)
print(list1)
26 Write a Python function that takes a number as a parameter and checks whether the number is prime or not.
Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and
itself.
27 Write a python function showlarge() that accepts a string as parameter and prints the words whose length is
more than 4 characters.
Eg: if the given string is “My life is for serving my Country” The output should be
serving
Country
28 Write a function OCCURRENCE() to count occurrence of a character in any given string. here function take
string and character as parameters.
29 Write definition of a method/function AddOddEven(VALUES) to display sum of odd and even values
separately from the list of VALUES.
For example : If the VALUES contain [15, 26, 37, 10, 22, 13] The function should display Even Sum: 58 Odd
Sum: 65
30 Write a Python function that takes a list and returns a new list with distinct elements from the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]
TOPIC: EXCEPTION HANDLING
Q1. The error occurs when rules of programming language are misused is called as:
a. Semantics Error b. 2. Logical Error
c. Syntax error d. Runtime Error
Q2. What is the purpose of the try block in Python error handling?
a) To define the block of code where an exception may occur
b) To catch and handle exceptions that occur within the block
c) To ensure that the code executes without any errors
d) To terminate the program if an exception occurs
Q3. Which keyword is used to catch exceptions in Python?
a) try b) catch c) except d) handle
Q4. Which of the following is NOT a standard Python exception?
a) KeyError b) SyntaxError c) IndexError d) TypeError
Q5. How can you handle multiple exceptions in a single except block?
a) Separate the exceptions using commas
b) Use nested except blocks
c) Use the except keyword only once
d) It is not possible to handle multiple exceptions in a single except block
Q6. What does the finally block in Python error handling ensure?
a) It ensures the program will terminate if an exception occurs.
b) It ensures the code within it will always execute, regardless of whether an exception occurs
or not.
c) It ensures that the program will skip executing the code if an exception occurs.
d) It ensures that only the code within the finally block will execute if an exception occurs.
Q7. Which of the following is true about the else block in Python error handling?
a) It is executed if an exception occurs.
b) It handles exceptions occurring in the try block.
c) It is executed if no exception occurs in the try block.
d) It is executed instead of the finally block.
Q8. What is the purpose of the assert statement in Python?
a) To handle exceptions b) To terminate the program
c) To check if a condition is true d) To raise an exception
Q9. Which of the following statements is true about the except clause in Python?
a) It is mandatory in a try-except block. b) It catches all exceptions by default.
c) It must be placed before the try block. d) It can specify the type of exceptions to catch.
Q10. Choose the correct output of the following.
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero")
finally:
print("Finally block")
a) Division by zero b) Finally block
Finally block
c) Division by zero d) ZeroDivisionError
Q11. What does the following Python code do?
try:
# Some code that may raise an exception
except:
pass
a) It raises an exception. b) It catches all exceptions and ignores them.
c) It terminates the program. d) It handles exceptions gracefully.
Q12. Choose the correct statement.
Statement-1: An exception is a Python object that represents an error.
Statement-2: Even if a statement or expression is syntactically correct, there might arise an error
during its execution.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q13. Choose the correct statement.
Statement-1: Exception needs to be handled by the programmer so that the program does not
terminate abnormally.
Statement-2: Exception does not disrupt the normal execution of the program.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q14. Choose the correct statement.
Statement-1: throws keyword is used to throw an exception from a block.
Statement-2: Built-in exceptions are defined in the Python compiler/interpreter.
a. Both Statement I and Statement II are true
b. Both Statement I and Statement II are false
c. Statement I is true but Statement II is false
d. Statement I is false but Statement II is true
Q15. Match the following with correct explanation of different types of errors in python
1. occur after the code has been compiled and the program is running. The
a) Syntax error error of this type will cause your program to behave unexpectedly or even
crash.
2. indicate that there is something wrong with the syntax of the program or
b) Logical errors rules for programming language are misused.
def push_char(ch):
STK.append(ch)
def display_STK():
strdata=""
if len(STK)==0:
print("Empty Stack")
else:
for i in STK:
strdata+=i
print(strdata[::-1])
def pop_char():
if STK!=[]:
item=STK.pop()
else:
pass
STK=[ ]
push_char('D')
push_char('A')
push_char('V')
push_char('M')
pop_char()
push_char('O')
push_char('D')
pop_char()
pop_char()
push_char('E')
push_char('L')
pop_char()
display_STK()
A. VAD
B. ODEL
C. LEDO
D. EVAD
8. Which of the following condition is necessary for fixed size stack for checking a stack st
is full in Python?
A. Top ==len(st)
B. Top ==len(st)-1
C. Top < len(st)
D. Top ==st
9. Which of the following is not an inherent application of stack?
A. Implementation of recursion
B. Evaluation of postfix expression
C. Job scheduling
D. Reversing a string
10. Choose the correct output for the following sequence of stack operations. push (5), push
(8), pop, push (2), push (5), pop, push (1)
A. 2551
B. 85251
C. 85521
D. 521
11. Consider a string strnew and write the following user defined functions in python to
perform the specified operations on the fixed size stack ‘vow’ (maximum element
accommodate by stack is 5)
i) Push_add(strnew): It takes the string as an argument and pushes only vowels
to the stack vow. If stack is full then it will print the message “Stack is Full,
no more element will be added to the stack” while trying to add element on
to the stack.
ii) Pop_item( ):- It remove the element and displays them. Also, the function
should display “Stack is Empty” when there are no elements in the stack.
12. Write a menu driven program to perform all the stack operation. Each operation will be
implemented with help of user defined function. The structure of the stack are as
follows:-
[ [ “Name of the student1”, totalmark1”], [ “Name of the student2”, totalmark2”]]
Different operation of stack are as follows:-
1) Push( ):- Add an element on to the stack.
2) Pop( ):- Remove an element from the stack.
3) Peek( ) :- Display current top element of the Stack.
4) Display( ) : Display all elements in top to bottom arrangement.
13. A list named datalist contains the following information:
Name of Employee
City
Phone number of Employee
in following manner
[[Name of Employee, City, Phone number of Employee]]
Write the following methods to perform given operations on the stack “status”:
Push_element (datalist) To Push an object containing Name of the Employee, city,
Phone no of the employee of those employee whose city is either “kolkata” or “new
delhi” into the stack.
Pop_element () To Pop an object from the stack and to release the memory.
14. Consider a dictionary which consists of key as “Admno” and value as Name, Class,
Markpercent, of 45 students in the following way-
data={“Admno”:[“Name”,”Class”,”Markpercent”]}
Write the following user defined function to perform push and pop operation on the
stack “Topers” respectively.
i) Push_top(data) accepts data dictionary as an argument and add only name of the
students on to the stack whose mark is more than 90% .
ii) Pop_element( ) to remove and display all the element from the stack and the
function should display “Stack is empty” if there is no element on to the stack.
Read the text carefully and answer the questions:
Millions of computer science students have taken a course on algorithms and data
structures, typically the second course after the initial one introducing programming.
One of the basic data structures in such a course is the stack. The stack has a special
place in the emergence of computing as a science, as argued by Michael Mahoney, the
pioneer of the history of the theory of computing. The stack can be used in many
computer applications, few are given below:
In recursive function When function is called.
Expression conversion such as - Infix to Postfix, Infix to Prefix, Postfix to Infix, Prefix
to Infix.
In stack, insertion operation is known as Push whereas deletion operation is known as
Pop.
Code 1
def push (Country, N):
Country.insert(len(Country),N) # Statement 1
# Function Calling
Country=[ ]
C=['Indian', 'USA', 'UK', 'Canada', 'Sri Lanka']
for i in range (0, len(C), 2): # Statement 2
push (Country, C[i])
print (Country)
# Output
#['Indian', 'UK', 'Sri Lanka']
9. Assertion (A): Primary key is a set of one or more attributes that recognize tuples in a
Tables
Reasoning (R): Every table must have one primary kay
10. Assertion (A): A foreign key is an attribute whose value is derived from the primary key of
another relation.
Reasoning (R): A foreign key is used to represent the relationship between tables or
relations.
11. A school has a rule that each student must participate in a sports activity. So each one
should give only one performance for sports activity. Suppose there are five students in a
class, each having a unique roll number.
The class representative has prepared a list of sports performance as shown below. Answer
the following.
Table: Sports Preferences
Roll_No Preference
9 Cricket
13 Football
17 Badminton
21 Hockey
24 NULL
NULL Kabaddi
a) Roll no 24 may not be interested in sports. Can a NULL value be assigned to that
student’s preference field?
b) Roll no 17 has given two preferences sports. Which property of relational DBMS is
violated here? Can we use any constraint or key in the relational DBMS to check against
such violation, if any?
c) Kabaddi was not chosen by any student. Is it possible to have this tuple in the Sports
Preferences relation?
12. The school canteen wants to maintain records of items available in the school canteen and
generate bills when students purchase any item from the canteen. The school wants to create
a canteen database to keep track of items in the canteen and the items purchased by
students.
Design a database by answer the following questions:
a) To store each item name along with its price, what relation should be used? Decide
appropriate attribute names along with their data type. Each item and its price should
be stored only once. What restriction should be used while defining the relation?
b) In order to generate bill, we should know the quantity of an item purchased. Should
this information be in a new relation or a part of the previous relation? If a new
relation is required, decide appropriate name and data type for attributes. Also,
identify appropriate primary key and foreign key so that the following two
restrictions are satisfied:
i) The same bill cannot be generated for different orders.
ii) Bill can be generated only for available items in the canteen.
c) The school wants to find out how many calories students intake when they order an
item. In which relation should the attribute ‘calories’ be stored?
13. Give the terms for each of the following:
a) Collection of logically related records.
b) DBMS creates a file that contains description about the data stored in the database.
c) Attribute that can uniquely identify the tuples in a relation.
d) Special value that is stored when actual data value is unknown for an attribute.
e) a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table.
f) Software that is used to create, manipulate and maintain a relational database.
14. In another class having 2 sections, the two respective class representatives have prepared 2
separate Sports Preferences tables, as shown below:
SECTION-1 SECTION-2
Table: Sports Preferences Table: Sports Preferences
Roll_No Preference
9 Cricket Preference Roll_No
13 Football Badminton 17
17 Badminton Cricket 9
21 Hockey Cricket 24
24 Cricket Football 13
Hockey 21
➢ Sports Preferences of SECTION-1 (arranged on roll number columns)
➢ Sports Preferences of SECTION-2 (arranged on Sports name column, and column
order is also different)
Are the states of both the relations equivalent? Justify.
15. Define the term referential integrity? How is it enforced in databases?
16. Explain the term ‘Relationship with reference to RDMS. Name the different types of
relationship that can be formed in RDMS.
17. Why foreign keys are allowed to have NULL values? Explain with an example.
18. List three significant differences between a file processing system and a DBMS.
19. Define the term database engine.
20. Differentiate between metadata and data dictionary.
TOPIC: MYSQL AND INTERFACE OF PYTHON WITH MYSQL
Q. Question
1. What does DML stands for?
a) Different Model Level
b) Data Model Language
c) Data Mode Lane
d) Data Manipulation Language
2. An attribute in a relation is a foreign key if it is the _________ key in any other relation.
a) Candidate
b) Primary
c) Super
d) Sub
3. Consider following SQL statement. What type of statement is this?
SELECT *FROM employee;
a) DML
b) DDL
c) DCL
d) Integrity Constraint
4. The data types CHAR(n) and VARCHAR(n) are used to create _________, and __________
types of string/text fields in a database.
a) Fixed, equal
b) Equal, variable
c) Fixed, variable
d) Variable, equal
5. Which of the following commands is used to remove a database?
a) Drop
b) Delete
c) Erase
d) Scratch
6. Which of the following is not an EQUI JOIN?
a) INNER JOIN
b) NATURAL JOIN
c) OUTER JOIN
d) LAP JOIN
1/5
8. Assertion(A): The Cartesian product of two sets(A and B) is defined as the set all possible
ordered pairs denoted by (A+B).
Reason(R): The Cartesian product is also known as the cross product of two sets. The Cartesian
product of two tables can be evaluated such that each row of the first table will be paired with all
the rows in the second table.
9. Assertion(A): Databases commands are not case sensitive.
Reason(R):. While creating databases in MySQL, we use commands to perform some
fundamentals task. The MySQL makes no difference whether you type the commands in
lowercase or uppercase while creating databases.
10. Assertion(A): In SQL, the GROUP BY clause is used to combine all such records of a table
which have the identical values in a special field(s).
Reason(R): The GROUP BY clause always returns one row for each group. We often use the
GROUP BY clause with aggregate functions such as SUM(), AVG(), MAX(), MIN() etc.
11. Assertion(A): The INNER JOIN is one of the types of SQL JOIN that can be performed between
two or more tables.
Reason(R): In SQL, The INNER JOIN clause returns all the matching records of two or more
tables where the key field of the records are same.
12. Assertion(A): The fetchall() and fetchmany() methods are used to store the records into the
MySQL database.
Reason(R): Both the methods are used for the same purpose. The user applies these functions as
per the need. However, they return the records as lists and return None (if there is no record to
fetch).
13. Assertion(A): The MySQL query using interface is executed by execute() method.
Reason(R):While interfacing with Python IDLE, the screen() method is used to receive bulk
records from the database.
14. A table ‘Student’ is created in the database “performance’. The details of the table are given
below:
StuID Name Class Total Grade
CB/01 Kaushal 12 A 488 A
CB/02 Debashish 12 C 491 A+
CB/03 Mohit 12 B 476 B
CB/04 Sujay 12 A 480 A
CB/05 Kunal 12 D 485 A
Thereafter, The table is to be interfaced with Python IDLE to perform certain tasks. The
incomplete code is given below:
import mysql.connector as mycon
mydb=mycon.connect(host='localhost',database='........',#1user='root',passwd='twelve')
mycursor=mydb.cursor()
mycursor.execute("SELECT *FROM Student") #2
record=mycursor.<........> #3
for i in record:
print(i)
With reference to the above code, answer the following questions:
a) What will you fill in #1 to complete the statement?
b) What will you fill in #3 to fetch all the records from the table?
c) What necessary change will you perform in #2 to display all such names from the table
‘Student’ who have secured Grade A?
d) What statement will you write in #2 to add one more record in the table ‘Student’ as per
2/5
the specifications given below?
StuID Name Class Total Grade
CB/06 Monali 12 C 493 A+
15. A table ‘Employee’ is already created in a database and few records are also entered in the table.
The details of the table are shown below:
Table: Employee
EmpCode Name Dept Salary (Rs.) PhNum
E001 Goutam Modak Elect 42000 01123563783
E002 Ashim Das IT 48000 01127484637
E003 Shivam Singh IT 38000 01126534536
E004 Vikram Jana Mech 41000 01124374543
E005 Somnath Bhalla Elect 35000 01127443546
16. A table ‘Teacher’ is created in MySQL workbench with various fields such as TID, Name,
Qualification, Experience, etc. with appropriate data types. Thereafter, few records are entered in
the table as shown below:
Table: Teacher
TID Name Qualification Experience DOJ Salary
T01 Shubham Das PGT 5 2015-06-10 32000
T02 Alok Sharma TGT 9 2010-10-24 28000
T03 Manisha Verma PRT 12 2008-04-15 24000
T04 Nishant Choudhury TGT 11 2009-02-11 28000
T05 Abhishek Sen TGT 8 2012-09-24 29000
T06 Sushant Singh PGT 4 2016-05-04 32000
Refer the above table and write SQL commands for the following queries:
a) To show all information of the PGT teachers.
b) To list the names of all teachers with their date of join (DOJ) in ascending order.
c) To display teacher’s name, experience, salary, of PRT teachers only.
d) To display the highest and the lowest salary of the teachers from the given table.
17. Consider the following tables Product and Client. Write the outputs for SQL queries.
Table: Product
P_ID Prod_Name Manufacturer Price
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
Table: Client
3/5
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
16 Dreams Banglore TP01
18. The school has asked their estate manager Mr. Sandip to maintain the data of all the labs in a
table LAB. Rahul has entered data of 5 labs.
Table:LAB
LAB_NO LAB_NAME INCHARGE CAPACITY FLOOR
L001 Chemistry Daisy 20 I
L002 Biology Venky 20 II
L003 Math Preeti 15 I
L004 Language Daisy 36 III
L005 Computer Mary Kom 37 II
Based on the data given above answer the following questions:
19. The code given below reads the following record from the table named Student and display only
those records who have marks greater than 75:
Roll_no-integer, Name- String, Class- integer, Marks-integer
5/5
TOPIC:-NETWORKING
1) Name the protocol responsible to send/receive files over Computer Network. 1
(a) PPP (b)HTTP (c) FTP (d) SMTP
2) __________ is a fundamental Protocol on Internet, which enables data transfer between a client 1
and a server.
3) Expand GSM and CDMA. 1
4) Name two E-mail Client software. 1
5) Name two Linux distributions? 1
6) Fill in the blank: 1
____________ protocol is used to provide access to the mail inbox that is stored in e-mail
server.
(a) VoIP (b) SMTP (c) POP3 (d)HTTP
7) What is Blog? 1
8) Expand SMTP and W3C. 1
9) What is Telnet? 1
10) Fill in the blank: 1
Data transfer in LAN is quite high, and usually varies from ________ Mbps (called Ethernet)
to ____________Mbps (called Gigabit Ethernet )
11) Each NIC has a MAC address . Expand NIC and MAC. 1
12) State whether true or false. 1
A router can be wired or wireless.
13) What is URI or URL? Give Two examples of it. 1
14) Fill in the blank: 1
192:68:0:178 is an Example of _________________ Address.
(a)IP (b)HTTP (c) MAC (d) SMTP
15) Expand IoT and WoT. 1
16) What is Trojan Horse? 1
21) (a) Twisted Pair Cable (b) Microwave transmission (c) Co-axial Cable (d) Fibre optic cable
22) “NSFNET came after ARPANET”. Expand both the terms and Evaluate the statement.(whether 2
true or false”).
23) Differentiate between Microwave and Infrared. 2
1 dict_student.update(dict_marks)
2 a) 1-b,2-d,3-a,4-c
3 b) ii,iii,iv
4 d) None of these
5 b) 1-a,2-c,3-d,4-b
6 b) x is 50
Changed global x to 2
Value of x is 2
7 Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
8 Assertion is true but Reason is false.
9 Assertion is false but Reason is true.
10 Both Assertion and Reason are false.
11 Both Assertion and Reason are false.
12 Assertion is false but Reason is true.
13 Both Assertion and Reason are true and Reason is not the correct explanation of Assertion.
14 Both Assertion and Reason are true and Reason is not the correct explanation of Assertion
15 Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
16 c) Assertion is true, but Reason is false.
17 100
90
80
70
60
50
18 #Read the limit
limit = float(input("Enter the limit"))
max_price = 0
# Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
while next_price > 0 :
if next_price < limit and next_price > max_price:
max_price = next_price
#Read the next price
next_price = float(input("Enter a price or 0 to stop:"))
if max_price > 0:
print("Largest Price =", max_price)
else :
print("Prices exceed limit of", limit);
19 dayNames = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY",
"SATURDAY", "SUNDAY"]
dayNum = int(input("Enter day number: "))
firstDay = input("First day of year: ")
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
24 def addDict(dict1, dict2):
union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict
1. listA[1] = 17
2. listA.extend([4, 5, 6])
3. listA.pop(0)
4. listA.sort()
5. listA = listA * 2
6. listA.insert(3, 25)
29 1. states = []
2. states.append('Delhi')
3. states.append('Punjab')
4. states2 = ['Rajasthan', 'Gujarat', 'Kerala']
5. states2.insert(0,'Odisha')
6. states2.insert(2,'Tripura')
7. a = states2.index('Gujarat')
states2.insert(a - 1,'Haryana')
8. b = states2.pop(4)
print(b)
30 1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements of the tuple whereas (a, a, a) creates nested tuple.
2. Yes, both a * 3 and a + a + a will result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
3. This colon indicates (:) simple slicing operator. Tuple slicing is basically used to obtain a
range of items.
tuple[Start : Stop] ⇒ returns the portion of the tuple from index Start to index Stop
(excluding element at stop).
a[1:1] ⇒ This will return empty list as a slice from index 1 to index 0 is an invalid range.
4. Both are creating tuple slice with elements falling between indexes start and stop.
a[1:2] ⇒ (2,)
It will return elements from index 1 to index 2 (excluding element at 2).
a[1:1] ⇒ ()
a[1:1] specifies an invalid range as start and stop indexes are the same. Hence, it will
return an empty list.
1. a Python string
2. a number
3. a tuple (containing only immutable entries)
33 For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a
tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a
key in a dictionary.
d={1:1}
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
35
36
37 A global variable is a variable that is accessible globally. A local variable is one that is only
accessible to the current scope, such as temporary variables used in a single function
definition. A variable declared outside of the function or in global scope is known as global
variable. This means, global variable can be accessed inside or outside of the function where as
local variable can be used only inside of the function. We can access by declaring variable as
global
****
TOPIC: FUNCTIONS
MARKING SCHEME
3 ()
2 def
3 Called/Invokedoranyotherwordwithsimilarmeaning
4 Add()
5 Add(10,20)
6 C=Add(10,20)
7 Line 5
8 1000
1000
None
9 1. Positional
2. Keyword
3. Default
4. Variable length argument
Example : (Keyword argument)
def Interest(principal, rate, time):
return(principal*rate*time)/100
R=Interest(rate=.06, time=7, principal=100000)
10 60
70
130
11 Swap(num1=100,num2=200)
12 Line 2 : Keyword argument must not be followed by positional argument
Line 4 : There is no keyword argument with name “Time”
Line5: Missing value for positional argument “R”
13 <class 'tuple'>
(20, 24, 28)
14 Local variables are those variables which are declared inside any block like function,
loop or condition. They can be accessed only in that block. Even formal argument will
also be local variables and they can be accessed inside the function only. Local
variables are always indented. Life time of local variables is created when we enter in
that block and ends when execution of block is over.
Global variables are declared outside all block i.e. without any indent. They can be
accessed anywhere in the program and their life time is also throughout the program.
Example:
count=1 #Global variable count
def operate(num1, num2): # Local variable num1 and
num2 result = num1 + num2 #Local variable
result print(count)
operate(100,200)
count+=1
operate(200,300)
15 100
50
100
16 100
1000
1000
17 True
18 True
19 exam$$*CBSE*COM
20 300@200
300#100
150@100
300@150
21 4
16
25
22 10#25$185
18#50$318
30#100$480
23 $$$$$
@@@@@@
@@@@ 325
AAAAA
24 3$3
6#30
6$1
6#7
1$1
2$7
25 [42,10.0,3.0,14,18,9.0,50.0,25.0,26]
26 def test_prime(n):
if (n == 1):
return False
elif (n == 2):
return True
else:
for x in range(2, n):
if (n % x == 0):
return False
return True
print(test_prime(9))
30 def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1, 2, 3, 3, 3, 3, 4, 5]))
TOPIC: EXCEPTION HANDLING
MCQ:
Q1. c. Syntax error
Q2. a) To define the block of code where an exception may occur
Q3. c) except
Q4. b) SyntaxError
Q5 a) Separate the exceptions using commas
Q6. b) It ensures the code within it will always execute, regardless of whether an exception occurs or
not.
Q7. c) It is executed if no exception occurs in the try block.
Q8. c) To check if a condition is true
Q9. d) It can specify the type of exceptions to catch.
Q10. a) Division by zero
Finally block
Q11. b) It catches all exceptions and ignores them.
Q12. a. Both Statement I and Statement II are true
Q13. c. Statement I is true but Statement II is false
Q14. d. Statement I is false but Statement II is true
15. b. a-2, b-3, c-1, d-4
Topic : File Handling
MCQ
1. c. seek() 1
2. d. dump() 1
3. b. r 1
4. a. file_object.seek(offset [, reference_point]) 1
5. c) A is True but R is False 1
6. d) Every line ends with new line character “\n” 1
7. a) f.read(3) 1
8. b) binary file 1
9. b) fh.seek(20,0) 1
10. (b) Both A and R are true and R is not the correct explanation for A 1
Programming
1. Bye
As when an existing file is opened in write mode, it truncates the existing data from the file.
2. def count_lines():
f=open"Story.txt","r")
line=f.readlines()
c=0
for wd in line:
if wd[0]=="A" or wd[0]=="a":
c=c+1
print("Total number of lines:",c)
f.close()
count_lines()
3. def create():
f=open("data.txt","r")
f1=open("info.txt","w")
str=f.read()
for i in str:
if i==".":
i=","
f1.write(i)
else:
f1.write(i)
f.close()
f1.close()
create()
4. import pickle
def display():
f=open('number.dat','rb')
try:
while True:
rec=pickle.load(f)
if(rec%7==0 and a%10==7):
print(rec)
except:
f.close()
display()
5. import pickle
def update(adno):
rec={}
fin=open("record.dat","rb")
fout=open("temp.dat","wb")
ack=False
while True
try:
rec=pickle.load(fin)
if rec["Adno"]==adno:
ack=True
rec["Fees"]=int(input("Enter the fees:"))
pickle.dump(rec,fout)
else:
pickle.dump(rec,fout)
except:
break
if ack==True:
print("Fees updated!"
else:
print("Record not found!")
fin.close()
fout.close()
6. import pickle
def search(dept)
with open('EMP.DAT','rb') as file:
while True:
try:
emprec=pickle.load(file)
for r in emprec:
dep=emprec[r][2]
if dep==dept:
print(r, emprec[r])
except EOFError:
break
7.
8.
9.
10.
11.
12.
ii. c. pickle.dump(L,F) 1
iii. a. R = pickle.load(F) 1
iv. a. ‘r+’ opens a file for both reading and writing. File object points to its beginning. 1
v. d. moves the current file position to a given specified position 1
******************
TOPIC: DBMS
1. d) Primary key
2. b)Tuples-to-Tuples
3. b)Redundancy
4. b)degree
5. b)Tuple
a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
c) (A) is true but ( R) is false
d) (A) is false but ( R) is true
e) Both (A) and ( R) are false
6. c) (A) is true but ( R) is false
7. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
8. b) Both ( A ) and ( R ) are true and ( R ) is not the correct explanation for ( A ).
9. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
10. a) Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
11. a) No NULL value cannot be assigned to it because according to the school rule every
Ans. student must participate in a sports activity.
b) No roll no 17 cannot give two preferences because it is violating the primary key
constraint. Every student has unique roll no. We can use primary key constraint to
check for such violations.
c) Not possible because roll no field cannot be NULL as no student can have NULL as
its roll number.
12. a) ITEM relation which holds data for the name of the food item and it's price.
Ans. ITEM( ItemId, ItemName, Price)
Here, ITEM is the table. ItemId column is the primary key of the relation, ItemName
is the name of the food item and price is its price per quantity.
To restrict duplicate values, ItemId is made the primary key of the relation.
b) A new relation is required to store the purchase of the item. It would be called
ORDERS and it has the following attributes -
1- OrderId - a unique id for every order. It is the primary key. This constraint satisfies
the condition (i).
2- Quantity - stores the quantity purchased by the student.
3- ItemId - foreign key that references the ITEM relation to make sure that item is
available in the canteen. This constraint satisfies the condition (ii).
c) ITEM relation. Since every item has it's own calorie value so it would be stored
with every item.
13. a) Database
Ans. b) Database catalog or data dictionary
c) Attribute that can uniquely identify the tuples in a relation is PRIMARY KEY.
d) Null.
e) A foreign key.
f) Relational Database Management System
14. Yes, the states of both the relations is equivalent because in database the row order
Ans. does not matter also there is no distinction of tables based on the order of attributes
(columns) they have, so both relations are equivalent.
15. Referential integrity is a term used in database design to describe the relationship
Ans. between two tables. It is important because it ensures that all data in a database remains
consistent and up to date. It helps to prevent incorrect records from being added,
deleted, or modified.
Referential integrity is usually enforced by creating a foreign key in one table that
matches the primary key of another table. If referential integrity is not enforced, then
you may encounter data redundancy and inconsistencies.
16. it is an association between tables. Those associations create using join statements to
Ans. retrieve data. It is a condition that exists between two database tables in which one
table contains a foreign key that references the primary key of the other tables.
19. A database engine (or storage engine) is the underlying software component that a
Ans. database management system (DBMS) uses to create, read, update and delete (CRUD)
data from a database.
20. The data dictionary contains data about the data in the database. Similarly.
Ans. Metadata component is the data about the data in the data warehouse.
-------- xxxxxxxx -----------------
Topic: MySQL and Interface of Python with MySQL
-----------------------------------------------------------------------------------------------------------------------------------
Q. Value points/ Key points
No.
1. d) Data Manipulation Language
2. b) Primary
3. a) DML
4. c)Fixed, variable
5. a) Drop
6. a) INNER JOIN
7. b)Different
8. (A) is false but ( R) is true
9. Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
10. (A) is false but ( R) is true
11. Both ( A ) and ( R ) are the correct and R is the correct explanation for ( A ).
12. (A) is false but ( R) is true
13. (A) is true but ( R) is false
14. a) Database=’Performance’
b) record=mycursor.fetchall()
c) mysursor.execute(“SELECT *FROM Student WHERE Grade=’A’ ”)
d) mycursor.execute(“INSERT INTO Student VALUES(‘CB/06’, ‘Monali’, ‘12C’, 493, ‘A+’)”)
17. a)
City
Delhi
Mumbai
Banglore
b)
Manufacturer Max(Price) Min(Price) Count(*)
LAK 40 40 1
ABC 55 45 2
XYZ 120 95 2
c)
ClientName Prod_Name
Cosmetic Shop Face Wash
Total Health Bath Soap
Live Life Shampoo
Pretty woman Face Wash
Dreams Talcom Powder
Prod_Name Price*4
TalcomPowder 160
Face Wash 180
d) Bath Soap 220
Shampoo 480
Face Wash 380
e)
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
12 Live Life Delhi SH06
15 Pretty Woman Delhi FW12
f)
ii) Degree:5
Cardinality:5
iii)
a) DELETE FROM LAB WHERE LAB_NO=’L004’;
b) UPDATE LAB SET CAPACITY=CAPACITY+10 WHERE FLOOR=’I’;
iv)
a) ALTER TABLE LAB ADD CONSTRAINT PKEY PRIMARY KEY (LABNO);
b) DROP TABLE LAB;
20. a)
Entity
Attributes/Fields
Records
b)
DDL: Data Definition Language
DQL: Data Query Language
DML: Data Manipulation Language
DCL: Data Control Language
c)
Primary Key Candidate Key
1.The Primary Key is a column or a combination 1.A candidate Key can be any column or a
of columns that uniquely identify a record combination of columns that can qualify as
‘Unique Key’ in a database.
2. Only one ‘Candidate Key’ can be a ‘Primary 2.There are multiple ‘Candidate Keys’ in a
Key’. table.
Example:
Table: Student
Admno RollNo Name
1000 1 Akash
1001 2 Neha
1002 3 Himanshu
Roll Number and Admission number both are unique field so, they are candidate key.
Unique field RollNo we can take as a Primary key.
f) The term ‘result set’ defines a set of records which are retrieved from a database table while
performing queries. However, the result set may not be known to the user but can be verified.
g) It defines the property of cursor object which returns the number of records retrieved from a
database table.
h) Usually, a cursor in SQL and databases is control structure to traverse over the records in a
database. So it is used for the fetching of the results. We get the cursor object by calling the cursor()
method of connection.
i) The EQUI Join is a simple Join clause where the relation is established using equal (=) sign as the
relational operator to mention the condition.
The NATURAL Join is referred to as a type of EQUI Join and is structured in such a way that the
columns with the same name of the associated tables will appear once only.
j)
WHERE CLAUSE HAVING CLAUSE
1.WHERE clause allows you to filter data from 1.HAVING clause allows you to filter data
specific rows(individual rows) from a table from a group of rows in a query based on
based on certain conditions. conditions involving aggregate values.
2.WHERE clause cannot include aggregate 2. HAVING clause can include aggregate
functions functions.
Example: Example:
SELECT *FROM Student WHERE marks>75 SELECT avg(gross), sum(gross) FROM
employee GROUP BY grade HAVING
grade=’E4’;