CBSE COMPUTER SCIENCE
前往频道在 Telegram
QUESTION BANK, REFERENCE BOOK, LAB MANUAL , WORKSHEET ETC., PYTHON TEXT BOOK AND REFERENCE BOOKS, 01. ASK QUESTIONS AT https://t.me/joinchat/FJ1noGs-64I0OWI1
显示更多549
订阅者
无数据24 小时
无数据7 天
无数据30 天
帖子存档
COMPUTER SCIENCE WITH PYTHON
ONLINE MCQ TEST
Python Basics 001-
1. https://docs.google.com/forms/d/e/1FAIpQLSfwkh38h6uFGRIUqsD_gWtC0LatfwtYWXb-6Cd7WS5c8KbvcA/viewform?usp=sf_link
2. https://forms.gle/Czxgqb6p9N34hLsX9
Python Basics 002-
1. https://docs.google.com/forms/d/e/1FAIpQLScguFCbVkCc8ifNMljY77f90agvQxjd64PjydiBHEMDk29QqQ/viewform?usp=sf_link
2. https://forms.gle/gih7FNGas4nX5tDV7
Python Basics 003-
1. https://docs.google.com/forms/d/e/1FAIpQLSfH6n41FHNkRSWP9ZSpQjKOAo9jS5yobQAhC1xWRniPqPgS8A/viewform?usp=sf_link
2. https://forms.gle/Fsft6dDag1gTGRZn8
Revision Tour-1 -
1. https://docs.google.com/forms/d/e/1FAIpQLSdPSGBYh7-UpgW3hYQWKTMUJXe4PTVmEnXUSZakDI9_c_T4VA/viewform?usp=sf_link
2. https://docs.google.com/forms/d/e/1FAIpQLSdPSGBYh7-UpgW3hYQWKTMUJXe4PTVmEnXUSZakDI9_c_T4VA/viewform?usp=sf_link
List Object 001
1. https://docs.google.com/forms/d/e/1FAIpQLSc0dwUC6srssrHItlbmcO_qWvGAOcIXamC86GW3UDkOY2M14Q/viewform?usp=sf_link
2. https://forms.gle/qcPbd9HifatcybkT7
String Object 001-
1. https://docs.google.com/forms/d/e/1FAIpQLSfCe2ZBO52G7eb3pAoNtmq1ZMugmg_hKSIxvHgs0myEJKn5zQ/viewform?usp=sf_link
2. https://forms.gle/WbG1RiEsPYUvBWpi8
Dictionary Object 001-
1. https://docs.google.com/forms/d/e/1FAIpQLSfoL1be5aUKQW4f_aCoWUOqR5aoil9-tOIT3YRi61qEMHlFxA/viewform?usp=sf_link
2. https://forms.gle/LvemwL6kqjaeGne4A
Computer Concepts
1. https://docs.google.com/forms/d/e/1FAIpQLSc4JP77T5JZKhKRL6F4l1jE7-W-HBIlKtNu6hrQNHfqQi4xZQ/viewform?usp=sf_link
2. https://forms.gle/UPV6QRAo5HAqMvyW7
TEST THROUGH TELEGRAM
1. Python Basics-1 t.me/QuizBot?start=ayrNqFKS
2. Python List-1 t.me/QuizBot?start=eowBkzeL
3. Python List-2 t.me/QuizBot?start=k8DYZ3Oa
4. Python List-3 t.me/QuizBot?start=Smn9ThxH
5. Python FILE HANDLING -1 t.me/QuizBot?start=nQD1Q3kG
6. Python FILE HANDLING -2 t.me/QuizBot?start=vx12PVG3
7. Python FILE HANDLING -3 t.me/QuizBot?start=7VvdcQtz
8. Python FILE HANDLING -4 t.me/QuizBot?start=MnPrt2v4
9. Python FILE HANDLING -5 t.me/QuizBot?start=ohtwqD6S
10. Model Set t.me/QuizBot?start=mr6DO8hs
Python Basics 001- https://docs.google.com/forms/d/e/1FAIpQLSfwkh38h6uFGRIUqsD_gWtC0LatfwtYWXb-6Cd7WS5c8KbvcA/viewform?usp=sf_link , https://forms.gle/Czxgqb6p9N34hLsX9
Python Basics 002- https://docs.google.com/forms/d/e/1FAIpQLScguFCbVkCc8ifNMljY77f90agvQxjd64PjydiBHEMDk29QqQ/viewform?usp=sf_link , https://forms.gle/gih7FNGas4nX5tDV7
Python Basics 003- https://docs.google.com/forms/d/e/1FAIpQLSfH6n41FHNkRSWP9ZSpQjKOAo9jS5yobQAhC1xWRniPqPgS8A/viewform?usp=sf_link , https://forms.gle/Fsft6dDag1gTGRZn8
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an expression
• Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The return Statement
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
Live Demo
#!/usr/bin/python
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −
• Global variables
• Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −
Live Demo
#!/usr/bin/python
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
*********
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
You can call a function by using the following types of formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −
Live Demo
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −
Live Demo
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not matter.
Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −
Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
FUNCTIONS IN PYTHON
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −
Live Demo
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
Live Demo
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
Live Demo
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
import pickle
def writedata( ):
list =[ ]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")
pickle.dump(list,file) #list of dictionary dumped only once in file as now dictionary is appended inside the list
file.close( )
def readdata( ):
file = open("student.dat", "rb")
list1 = pickle.load(file)
print(list1)
for i in list1:
print(i['roll'],i['name'])
file.close()
def search():
file = open("student.dat", "rb")
list1 = pickle.load(file)
pname=input("enter the name to be searched:")
for i in list1:
if (i['name']==pname):
print("record found!")
print("rollno=",i['roll'],"name=",i['name'])
break
else:
print("not found!")
print("Press-1 to write data and Press-2 to read data Press 3 to search record ")
choice=int(input( "enter choice:"))
if choice==1:
writedata()
elif choice==2:
readdata()
elif choice==3:
search()
else:
print("You entered invalid value")
S SHUNMUGA SUNDARAM, M.E, A.M.I.E, MISTE,. IAENGG, [05-03-2023 22:55]
#Write a program to insert, display and search a number in a binary file. If number is not found then display appropriate message.
#single list program
import pickle
def write():
f=open("sample.dat",'wb')
rec=[3,5,7,2,6,7,1] #pre-defined list
#user input code below
'''
while True:
x=int(input("enter value:"))
rec.append(x)
ch=input("enter more?:")
if(ch=='n'):
break
'''
pickle.dump(rec,f) # entire list written to file once
print("added")
f.close()
def read():
print("reading...")
f=open("sample.dat",'rb')
p=pickle.load(f)
print(p)
f.close()
def search():
print("searching....")
f=open("sample.dat",'rb')
found=0
x=int(input("enter the number you want to search:"))
rec=pickle.load(f)
print(rec)
for R in rec:
if x==R:
found=1
print("record found")
break
if(found==0):
print("record not found")
f.close()
print("*"*20,"MENU","*"*20)
print("1.write\n2.read\n3.search")
choice=int(input("enter your choice:"))
if(choice==1):
write()
elif choice==2:
read()
elif choice==3:
search()
else:
print("invalid input")
S SHUNMUGA SUNDARAM, M.E, A.M.I.E, MISTE,. IAENGG, [05-03-2023 22:56]
#Write a program to search a record using its roll number and display the name of student. If record not found then display appropriate message.
#nested list
import pickle
def write():
f=open("sample.dat",'wb')
rec=[[1,'sakshi',45],[2,'kiara',66],[3,'inaya',47],[4,'anjali',76]] #pre-set list
pickle.dump(rec,f)
print("added")
f.close()
def read():
print("reading...")
f=open("sample.dat",'rb')
p=pickle.load(f)
#print(p) # will print the nested list
#display element by element
print("rno name marks")
for i in p:
print(" ",i[0],i[1]," ",i[2])
f.close()
def search():
print("searching....")
f=open("sample.dat",'rb')
found=0
x=int(input("enter the rno you want to search:"))
rec=pickle.load(f)
#print(rec) #... will print nested list
for i in rec:
if x==i[0]:
found=1
print("record found")
print("name=",i[1],"marks=",i[2])
break
if(found==0): print("record not found")
f.close()
print("*"*20,"MENU","*"*20)
print("1.write\n2.read\n3.search")
choice=int(input("enter your choice:"))
if(choice==1):
write()
elif choice==2:
read()
elif choice==3:
search()
else:
print("invalid input")
S SHUNMUGA SUNDARAM, M.E, A.M.I.E, MISTE,. IAENGG, [05-03-2023 22:56]
#Write a program to write and display the contents of a dictionary into a binary file.
#only dictionary but multiple records
import pickle
def write():
f=open("maps.dat","ab")
ch="y"
while ch == "y":
r=int(input("input enter rno "))
s=input("enter name ")
m=int(input("input enter marks "))
d={"rno":r,"name":s,"MARKS":m}
pickle.dump(d,f) # only 1 record dumped in file.loop repeats, next dumped.
# dictionaries dont have append() function, so each record needs to be written separately #using loop
ch=input("want to enter more rec ")
f.close()
def read():
f=open("maps.dat","rb")
d={}
try:
while True: # as long as there is data in the file
d=pickle.load(f)
print(d['rno'],':',d['name'])
#print(d)
except EOFError:
f.close()
write()
read()
S SHUNMUGA SUNDARAM, M.E, A.M.I.E, MISTE,. IAENGG, [05-03-2023 22:57]
#WAP to read,write and seach a record in a binary file using list of dictionaries.
#binary file - list of dictionary
SECTION E
34. Navdeep creates a table RESULT with a set of records to maintain the marks secured by students in Sem 1, Sem2, Sem3 and their division. After creation of the table, he has entered data of 7 students in the table. 1+1+2
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as Primary key.
Ans:
ROLL_NO
(ii) If two columns are added and 2 rows are deleted from the table result, what will be the new degree and cardinality of the above table?
Ans:
DEGREE= 8
CARDINALITY=5
(iii) Write the statements to:
a. Insert the following record into the table:
Roll No- 108, Name- Aadit, Sem1- 470, Sem2-444, Sem3- 475, Div – I.
Ans:
Insert into result values(108,’Aadit’,470,444,475,’I’);
b. Increase the SEM2 marks of the students by 3% whose name begins with ‘N’.
Ans:
update result set sem2=sem2+0.03*sem2 where sname like ‘N%’;
OR
(Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing IV division.
Ans:
Delete from result where division=’IV’;
b. Add a column REMARKS in the table with datatype as varchar with 50 characters
Ans:
Alter table result add REMARKS varchar(50);
35. Aman is a Python programmer. He has written a code and created a binary file record.dat with employeeid, ename and salary. The file contains 10 records.
He now has to update a record based on the employee id entered by the user and update the salary. The updated record is then to be written in the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat. If the employee id is not found, an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement given above:
import #Statement 1
def update_data():
rec={}
fin=open(“record.dat”,”rb”)
fout=open(” “) #Statement 2
found=False
eid=int(input(“Enter employee id to update their salary::”))
while True:
try:
rec= #Statement 3
if rec[“Employee id”]==eid:
found=True
rec[“Salary”]=int(input(“Enter new salary:: “))
pickle. #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print(“The salary of employee id “,eid,” has been updated.”)
else:
print(“No employee with such id is not found”) fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
Ans:
pickle
(ii) Write the correct statement required to open a temporary file named dat. (Statement 2)
Ans:
fout=open(“temp.dat”,”wb”)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat and in Statement 4 to write the updated data in the file, temp.dat?
Ans:
pickle.load(fin) #Statement 3
pickle.dump(rec,fout) #Statement 4
• Statement 2 – to execute the query that extracts records of those students whose marks are greater than 75.
• Statement 3- to read the complete result of the query (records whose marks are greater than 75) into the object named data, from the table student in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host=”localhost”,user=”root”, password=”tiger”, database=”school”)
mycursor= #Statement 1
print(“Students with marks greater than 75 are: “)
#Statement 2
data= #Statement 3
for i in data:
print(i)
print()
Ans:
#Statement 1 – con1.cursor()
#Statement 2 – mycursor.execute(‘select * from student where marks>75’)
#Statement 3 – mycursor.fetchall()
33. 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:
• 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
• COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
Ans:
Advantages of csv file
• It is easy to edit a CSV file.
• It is easily to understand.
• CSV files can be opened with text editor as well as spreadsheet applications like Excel.
• CSV files are smaller in size.
• CSV files are compact.
import csv
def ADD():
f=open(‘records.csv’,’a’,newline=”)
w=csv.writer(f)
empid=int(input(‘Enter employee id=’))
name=input(‘Enter employee name=’)
mobile=float(input(‘Enter salary =’))
rec=[empid,name,mobile]
w.writerow(rec)
f.close()
def COUNTR():
f=open(‘records.csv’,’r’)
r=csv.reader(f)
count=0
for rec in r:
count+=1
print(‘Number of records=’,count)
f.close()
OR
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:
• 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
• search()- To display the records of the furniture whose price is more than 10000. 5
Ans:
CSV file stores information in the form Comma Separated Values. They can be easily opened and modified using any text editor. They are readable by humans.
Binary files can be understood by computers only. Their processing is faster than csv files.
import csv
def add():
f=open(‘furdata’,’a’,newline=”)
w=csv.writer(f)
furid=int(input(‘Enter fid=’))
fname=input(‘Enter fname=’)
fprice=float(input(‘Enter fprice=’))
rec=[furid,fname,fprice]
w.writerow(rec)
f.close()
def search():
f=open(‘furdata’,’r’)
r=csv.reader(f)
count=0
for rec in r:
if float(rec[2])>10000:
print(rec)
f.close()
SECTION D
31. MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres in various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus, they are planning to have 3 different blocks for App development, Web designing and Movie editing. Each block has number of computers, which are required to be connected in a network for communication, data and resource sharing. As a network consultant of this company, you have to suggest the best network related solutions for them for issues/problems raised in question nos. to (v), keeping in mind the distances between various blocks/locations and other given parameters.
i. Suggest the most appropriate block/location to house the SERVER in the Kashipur campus (out of the 3 blocks) to get the best and effective Justify your answer. 1
Ans:
Movie editing block
Because this block contains maximum number of computers.
ii. . Suggest a device/software to be installed in the Kashipur Campus to take care of data 1
Ans:
Firewall
iii. Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect various blocks within the Kashipur 1
Ans:
Best wired medium: Twisted Pair Cable
Cable Layout
iv. Suggest the placement of the following devices with appropriate reasons: 1
1.
1. Switch / Hub
2. Repeater
Ans:
1. Switch/Hub should be placed in all blocks as they are needed to interconnect computers on a network.
2. There is no need of repeater in Kashipur block as distance between buildings is very less.
v. Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur Campus and Mussoorie Campus. 1
Ans:
VoIP
32. (a) Write the output of the code given below: 2
p=5
def sum(q,r=2):
global p
p=r+q**2
print(p, end= ‘#’)
a=10
b=5
sum(a,b)
sum(r=5,q=1)
Ans:
105#6#
(b) The code given below inserts the following record in the table Student:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named school.
• The details (RollNo, Name, Clas and Marks) are to be accepted from the
Write the following missing statements to complete the code: 2+3
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3- to add the record permanently in the database
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host=”localhost”,user=”root”, password=”tiger”, database=”school”)
mycursor= #Statement 1
rno=int(input(“Enter Roll Number :: “))
name=input(“Enter name :: “)
clas=int(input(“Enter class :: “))
marks=int(input(“Enter Marks :: “))
querry=”insert into student values({},'{}’,{},{})”.format(rno,name,clas,marks)
____________________________ #Statement 2
_____________________________ # Statement 3
print(“Data Added successfully”)
Ans:
#Statement 1 – con1.cursor()
#Statement 2 – mycursor.execute(querry)
#Statement 3 – con1.commit()
OR
(a) Predict the output of the code given below:
s=”welcome2cs”
n = len(s)
m=””
for i in range(0, n):
if (s[i] >= ‘a’ and s[i] <= ‘m’):
m = m +s[i].upper()
elif (s[i] >= ‘n’ and s[i] <= ‘z’):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +’&’
print(m)
Ans:
sELCcME&Cc
(b) The code given below reads the following record from the table named student and displays only those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
•
• Username is root
• Password is tiger
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
• Statement 1 – to form the cursor object
iv) SELECT Name, Place FROM Teacher T, Placement P WHERE Gender =’F’ AND T.Department=P.Department;
Ans:
Saman Ahmedabad
Samira Ahmedabad
Shalakha Jaipur
(b) Write the command to view all tables in a
Ans:
Show tables;
29. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The function returns another list named ‘indexList’ that stores the indices of all Non-Zero Elements of L. 3
For example:
If L contains [12,4,0,11,0,56]
The indexList will have – [0,1,3,5]
Ans:
def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList
30. A list contains following record of a customer: [Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named ‘status’:
• Push_element() – To Push an object containing name and Phone number of customers who live in Goa to the stack
• Pop_element() – To Pop the objects from the stack and display them. Also, display “Stack Empty” when there are no elements in the stack.
For example:
If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
The stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
The output should be:
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
Stack Empty
Ans:
customers=[
[“Gurdas”, “99999999999”,”Goa”],
[“Julee”, “8888888888”,”Mumbai”],
[“Murugan”,”77777777777″,”Cochin”],
[“Ashmit”, “1010101010”,”Goa”]
]
status=[]
def Push_element():
for i in range(len(customers)):
if customers[i][2]==”Goa”:
status.append([customers[i][0],customers[i][1]])
def Pop_element():
for i in range(len(status)):
print(status.pop())
if len(status)==0:
print(“Stack Empty”)
OR
Write a function in Python, Push(SItem) 3
where , SItem is a dictionary containing the details of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater than 75. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem={“Pen”:106,”Pencil”:59,”Notebook”:80,”Eraser”:25}
The stack should contain
Notebook
Pen
The output should be:
The count of elements in the stack is 2
Ans:
def Push(SItem):
STACK=[]
for i in SItem:
if SItem[i]>75:
STACK.append(i)
#print(STACK)
print(‘The count of elements in the stack is ‘,len(STACK))
OR
Predict the output of the Python code given below: 2
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) 2
25. Differentiate between count() and count(*) functions in SQL with appropriate example. 2
Ans:
count() function is used to count the number of records in a particular field or in SQL.
Syntax : count(Expression/*)
Expression may be the name of any field of table or any expression based on a field of a table.
* is used when we want to know the number of records in a table.
Examples
i. select count(fees) from student;
Above command will show the number of non null values stored in fees field of student table.
ii. select count(*) from student;
This command will show the total number of records stored in student table.
OR
Categorize the following commands as DDL or DML: INSERT, UPDATE, ALTER, DROP
Ans:
DDL : ALTER, DROP
DML: INSERT, UPDATE
SECTION C
26 (a) Consider the following tables – Bank_Account and Branch:
(a) What will be the output of the following statement?
SELECT * FROM Bank_Account NATURAL JOIN Branch;
Ans:
A01 Amrita Savings Delhi
A02 Parthodas Current Mumbai
A01 Amrita Savings Nagpur
(b) Write the output of the queries (i) to (iv) based on the table, TECH_COURSE given below:
(i) SELECT DISTINCT TID FROM TECH_COURSE;
Ans:
101
NULL
102
104
103
(ii) SELECT TID, COUNT(*), MIN(FEES) FROM TECH_COURSE GROUP BY TID HAVING COUNT(TID)>1;
Ans:
101 2 12000
(iii) SELECT CNAME FROM TECH_COURSE WHERE FEES>15000 ORDER BY CNAME;
Ans:
Digital marketing
Mobile Application Development
(iv)SELECT AVG(FEES) FROM TECH_COURSE WHERE FEES BETWEEN 15000 AND 17000;
Ans:
15500
27. 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. 3
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():
f=open(“TESTFILE.TXT”, “r”)
data = f.readlines()
count=0
for line in data:
if line[0] not in [‘a’,’A’, ‘e’,’E’,’i’,’I’,’o’,’O’,’u’,’U’]:
count+=1
print (“The number of lines not starting with any vowel – “,count)
f.close()
OR
Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT” and then count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).
Example:
If the file content is as follows:
Today is a pleasant day.
It might rain today.
It is mentioned on weather sites
The ETCount() function should display the output as:
E or e: 6
T or t : 9
Ans:
def ETCount():
f=open(“TESTFILE.TXT”, “r”)
s=” “
countE=0
countT=0
while s:
s=f.read(1)
if s==’E’ or s==’e’:
countE+=1
if s==’T’ or s==’t’:
countT+=1
print (“E or e: “,countE)
print (“T or t: “,countT)
f.close()
28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and Placement given below: 3
i. SELECT Department, avg(salary) FROM Teacher GROUP BY Department;
Ans:
Computer Sc 16500
History 30000
Mathematics 25000
ii) SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM Teacher;
Ans:
2021-09-05 2017-03-24
iii) SELECT Name, Salary, T.Department, Place FROM Teacher T, Placement P WHERE T.Department = P.Department
AND Salary>20000;
Ans:
Randeep 30000 Mathematics Nagpur
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct
choice as
• Both A and R are true and R is the correct explanation for A
• Both A and R are true and R is not the correct explanation for A
• A is True but R is False
• A is false but R is True
17. Assertion (A):- If the arguments in 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). 1
Ans: (c) A is True but R is False
18. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text file 1
Reason (R): The information is organized with one record on each line and each field is separated by comma.
Ans: (a) Both A and R are true and R is the correct explanation for A
SECTION B
19. 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. 2
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 :: “) )
for i in range (2, n//2):
if n%i == 0:
print(“Number is not prime \n”)
break
else:
print(“Number is prime \n “ )
20. Write two points of difference between Circuit Switching and Packet Switching. 2
Ans:
In circuit switching, a physical communication link is established between source and destination computers before transmitting information.
In packet switching, information is transferred from source computer to destination computer in the form of fixed sized blocks known as packets.
OR
Write two points of difference between XML and HTML. 2
HTML:
i. HTML stands for Hypertext Markup Language,
ii. HTML is used to create web pages.
XML
i. XML stands for Extensible Markup Language
ii.XML is used to store structured information
21. (a) Given is a Python string declaration: 1
myexam=”@@CBSE Examination 2022@@”
Write the output of:
print(myexam[::-2])
Ans:
@20 otnmx SC@
(b) Write the output of the code given below: 1
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’)]) 1
22. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give example to support your answer. 2
Ans:
Foreign Key is a field whose values are derived from primary key of another table. Foreign key can be used to establish a link between two tables.
In the following example
DeptID field in the Department table is a Primary Key in the Department Table.
DeptID field in the Employee table is a Foreign Key in the Employee Table.
23. (a) Write the full forms of the following: 2
(i) SMTP (ii) PPP
Ans:
(i) SMTP : Simple Mail Transfer Protocol
(ii) PPP : Point to Point Protocol
(b)What is the use of TELNET?
Ans:
Telnet is a network protocol to provide a two-way text-based communication between two computers.
24. Predict the output of the Python code given below: 2
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 #
SECTION A
1. State True or False 1
“Variable declaration is implicit in Python.”
Ans:
True
2. Which of the following is an invalid datatype in Python? 1
(a) Set (b) None (c)Integer (d)Real
Ans:
Real
3. Given the following dictionaries 1
dict_exam={“Exam”:”AISSCE”, “Year”:2023} dict_result={“Total”:500, “Pass_Marks”:165}
Which statement will merge the contents of both dictionaries?
1. update(dict_result)
2. dict_exam + dict_result
3. add(dict_result)
4. merge(dict_result)
Ans:
1. dict_exam.update(dict_result)
4. Consider the given expression: 1
not True and False or True
Which of the following will be correct output if the given expression is evaluated?
1. True
2. False
3. NONE
4. NULL
Ans:
1. True
5. Select the correct output of the code: 1
a = “Year 2022 at All the best”
a = a.split(‘2’)
b = a[0] + “. ” + a[1] + “. ” + a[3]
print (b)
a. Year . at All the best
b. Year at All the best
c. Year . at All the best
d. Year . at all the best
Ans:
(a) Year . 0. at All the best
6. Which of the following mode in file opening statement results or 1
generates an error if the file does not exist?
(a) a+ (b) r+ (c) w+ (d) None of the above
Ans:
(b) r+
7. Fill in the blank: 1
command is used to remove primary key from the table in SQL.
(a) update (b)remove (c) alter (d)drop
Ans:
(c) alter 1
8. Which of the following commands will delete the table from MYSQL database? 1
a. DELETE TABLE
b. DROP TABLE
c. REMOVE TABLE
d. ALTER TABLE
Ans:
(b) DROP TABLE
9. Which of the following statement(s) would give an error after executing 1 the following code? 1 S=”Welcome to class XII” # Statement 1
print(S) # Statement 2
S=”Thank you” # Statement 3
S[0]= ‘@’ # Statement 4
S=S+”Thank you” #Statement 5
a. Statement 3
b. Statement 4
c. Statement 5
d. Statement 4 and 5
Ans:
(b) Statement 4
10. Fill in the blank: 1
is a non-key attribute, whose values are derived from the primary key of some other table.
• Primary Key
• Foreign Key
• Candidate Key
• Alternate Key
Ans:
(a) Foreign Key
11. The correct syntax of seek() is: 1
a. seek(offset [, reference_point])
b. seek(offset [, reference_point])
c. seek(offset, file_object)
d. file_object(offset)
Ans:
(a) file_object.seek(offset [, reference_point])
12. Fill in the blank: 1
The SELECT statement when combined with clause, returns records without repetition.
a. DESCRIBE
b. UNIQUE
c. DISTINCT
d. NULL
Ans:
(c) DISTINCT
13. Fill in the blank: 1
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
14. What will the following expression be evaluated to in Python? 1
print(15.0 / 4 + (8 + 3.0))
(a) 14.75 (b)14.0 (c) 15 (d) 15.5
Ans:
(a) 14.75
15. Which function is used to display the total number of records from table in a database? 1
a. sum(*)
b. total(*)
c. count(*)
d. return(*)
Ans: (c) count(*)
16. To establish a connection between Python and SQL database, connect() is used. Which of the following arguments may not necessarily be given while calling connect() ? 1
• host
• database
• user
• password
Ans:
(b) database
