Class XII Study Material KV 2022-23
Class XII Study Material KV 2022-23
2
KENDRIYA VIDYALAYA SANGATHAN JAIPUR REGION
Content Developer
3
Syllabus
Computer Science
CLASS-XII
Code No.
083
2022-23
1. Prerequisites
Computer Science- Class XI
2. Learning Outcomes
Student should be able to
a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL.
3. Distribution of Marks:
Unit Unit Marks Periods
No. Name
Theory Practical
4
• Binary file: basic operations on a binary file: open using file open modes (rb, rb+,
wb, wb+, ab, ab+),close a binary file, import pickle module, dump() and load()
method, read, write/create, search, append and update operations in a binary
file
• CSV file: import csv module, open / close csv file, write into a csv file using
csv.writer() and read from a csv file using csv.reader( )
• Data Structure: Stack, operations on stack (push & pop), implementation of stack
using list.
5
Index
S.No. Name of Topic Page No.
1 Revision of Python topics covered in Class XI. 7
2 Functions: 12
3 Introduction to files 14
4 Computer Networks 41
5 Database concepts: 68
6 Interface of python with an SQL database 76
7 Practice Paper-1 91
8 Answer Key Practice Paper-1 100
9 Practice Paper-2 106
10 Answer Key Practice Paper-2 116
11 Practice Paper-3 122
12 Answer Key Practice Paper-3 130
13 Practice Paper-4 135
14 Answer Key Practice Paper-4 145
15 Practice Paper-5 149
16 Answer Key Practice Paper-5 161
17 CBSE SAMPLE PAPER WITH MARKING SCHEME 166
6
Unit I: Computational Thinking and Programming – 2
Python Revision Tour
Developer :- Python Programming language was developed by Guido Van Roussum in
early 1990s, its name is taken from a famous circus “Monty Python Flying Circus”
Python IDE(Integrated Development Environment):- It is a software that provides an
environment where a programmer can develop python program. There are various IDE
available for example:- IDLE(Integrated Development Learning Environment), Sublime,
Atom,Pycharm, Canopy, Tonney etc
Python is a case-sensitive language. All the commands are written in small letters. It
differentiate between Capital letter and small letter of same character. For example
Computer and computer are considered two different words. Capital letters are always
treated smaller then lower letters. For example ‘Z’ is smaller then ‘a’.
Python Data Types :- int, float, complex, bool,None
Python Sequences :- String, Tuple, List, Dictionary and Set
Python control statement:- if , if else , while and for
Python loop :- while and for are two popular loop. Loop is also called iteration
Python variables/identifiers/function naming rules :- All name must start with
alphabets. No special characters except (_) underscore are allowed. All the keyword and
reserve words of python language cannot be used as variable name.
Commonly used methods of python :-
Method and Description Example
operators
max() and min() Finds maximum value max( [56,34,87,67,5])
output:- 87
max(“computer”)
output:- u
max([“Yuppi”, “apple”])
output :- apple
sorted() Return sorted sequence L=sorted([8,2,1])
Values in L is [1,2,8]
L=sorted(“comp”)
Values in L [‘c’,’m’,’o’,’p’]
id() Return id of object D={}
id(D) It wil return the id of D
sum() It calculate total of values sum((67,33)) returns 100
7
chr() Return corresponding chr(65) return ‘A’
character of a given values
chr(97) return ‘a’
A-Z means 65 to 90
chr(48) return ‘0’
a-z means 97 to 122
0 to 9 means 48 to 57
ord() Return ascii values of one ord(‘A’) return 65
character
ord(“0”) return 48
abs() Return absolute value in abs(-45) return 45
int
fabs() Return absolute value in fabs(-45) return 45.0
float
ceil() Return next rounded ceil(4.2) return 5.0
value
pow() Return ab pow(10,2) return 100
len() Return length of a len({1:3,2:3)} return 2
sequence
renge(start,stop,step) It generates range of for x in range(5) generates 0 1
values 234
it takes minimum one and for x in range(0,5,1) give same
maximum 3 parameters as above
default start is 0 and for x in range(-3,-7,-1) give -3 -
default step is 1. stop is -4 -1
compulsary
8
Default start :- 0 “champ”[::-1] return “pmahc”
Default stop :- end “champ”[-1::-1] return
“pmahc”
Default step :- 1
“champ”[0::-1] return “c”
“champ”[::2] return “ca”
Python String:- String is sequence of characters. It can be created using pair of single
quote ( ‘ ) or double quote (“). Pair of three single quote or three double quotes are used
to create multiline string.
String is immutable and never support ‘=’ assignment operator for modifying its
content.
Methods Description Example
S.lower() Return a copy of the string S “HELlO”.lower() return “hello”
converted to lowercase
S.upper() Return a copy of S converted to “hello”.upper() return
uppercase “HELLO”
S..capitalize() Make the first character “HELLO”.capitalize() return
have upper case and the rest “Hello”
lower case
S.islower() Return True if all cased characters “wagonR”.islower() returns
in S are lowercase False
S.isupper() Return True if all cased characters “HI”.isupper() return True
in s are uppercase
S.istitle() Return True if all words of string “The Times Of India”.istitle()
starts with Capital letters rest return True
with lower
S.split() Return list of strings all separated “times of inda”.split() return
by space or any specified [ “times”, “of”, “india”]
character “abc@pink@city”.split(“@”)
return
[“abc”, “pink”,”city”]
“times of india”.split(“es”)
return
[“tim”, “of india”]
S.join(S1) Fills S between each character of “hi”.join(“bye”) will return
S1 “bhiyhie”
“-“.join([“one”,”two”,”three”])
It can also be used with list or Return
tuple of strings “one-two-three”
S.endswith(S1) Return True if S ends with S1 “women”.endswith(“men”)
return True
S.strip() Removes leading and trailing spaces, “ s “.strip() return “s”
S.lstrip() if any “ s “.lstrip() return “s “
S.rstrip() Removes leading spaces only, if any “ s “.rstrip() return “ s”
Removes trailing spaces only, if
any
9
S.isdigit() Returns True if S contains only “345”.isdigit() return True
digits
S.isalpha() Return True if S contains only “test”.isalpha() return True
alphabets “test123”.isalpha() return
False
S.isalnum() Return True if S contains alphabet, “abc123".isalnum() return
digit or mixture of both. True
“abc”.isalnum() return True
“123”.isalnum() return True
“abc-123”.isalnum() return
False
S.find(S1) Return index number of first “gabbar singh”.find(“b”)
occurance of S1 otherwise -1 return 2
“babbar”.find(“singh”) return -
1
Python tuple :- It is immutable ordered sequence. It does not support the assignment
operator for changing the value stored in it.
Methods Description Example
index(object) It return index number of given T=(34,56,34,65)
object otherwise raise ValueError T.index(34) return 0
T.index(50) Raise
ValueError
10
L.sort() It can arrange the list in both L=[45,23,7]
ascending and descending L.sort(reverse=False) will
order. make [7,23,45]
L.sort(reverse=True) will
make [45,23,7]
13
elif x.isupper():
print(“upper”)
else:
print(“all the best”)
prog(“rajesh.123.yahoo”)
Ans :- Alphabet
Digit
Alphabet
(vi) def check(x,y):
if x != y:
return x+5
else:
return y+10
print(check(10,5)) Ans :- 15
14
Python Text File Handling
TEXT FILE :- Python provides inbuilt functions for creating, writing, and reading files.
There are two types of files that can be handled in python, normal text files. In text files,
each line of text is terminated with a special character called EOL (End of Line), which is
the new line character (‘\n’) in python by default. The string object of python is used for
reading and writing the text file
File Object :- This is needed to keep a reference to a file in a python program whereas
the file is actually stored in Hard Disk (Memory)
open() method:- It takes one or two parameters. First is name of the file and second
mode of the file. If mode is not mentioned then the file is opened in read-only mode.
File_object=open(filename) # read only mode
File_object=open(filename,mode) # user’s choice of mode
Example : - ABC.txt file is saved in the folder where python is installed
F=open(“ABC.txt”,”r”)
If ABC.txt file is saved in d drive and inside the computer folder then the command will
be
F=open(d://computer//ABC.txt”,”r”)
read() method :- It reads the entire content of the file and saves it into a string.
read(n) method :- It reads n bytes of a file from the position where the file pointer is
located. When we
open a file the file pointer is placed at 0 positions. After reading n
bytes the file pointer moves n bytes forward.
readlines():- It reads the entire content of the file and returns list of strings, every
string is the lines of files.
redlines(n) :- It reads n lines from the position of file pointer and returns a list of
string
write():- It writes string into a file
writelines(list of string) :- It writes multiple lines into file if all lines are written as a
list of strings and all string should end with “\n” character.
16
S=F.read()
countB=0
countD=0
for x in S:
if x ==”D”:
countD=countD+1
if x==”B”:
countB=countB+1
print(“ Total occurance of B is “, countB)
print(“Total occurance of D is “, countD)
F.close()
F=open(“abc.txt”,”r”)
L=F.readlines()
for x in L[-1::-1]:
print(x)
F.close()
Binary Files: It is a file that contains information in the same format as it is held in
memory. In binary files, no delimiters are used for a line and no translations occur here.
They represent the actual content such as image, audio, video, executable files, etc.
These files are not human readable. The file extension of binary file is .dat.
(i) Python object handles the binary files. Python provides a special module-the
pickle module which has different predefined functions to manipulate the binary
files.
(ii) Using dump( ) method : It is used to write objects in a file. Before use the dump( )
method, you first have to import the pickle module.
Syntax: import pickle
17
...... ...... ......
pickle.dump(object_to_pickle,FileObject)
(iii) Using load() method :This method is used to read data from a binary file.
Syntax: import pickle
...... ...... ......
object=pickle.load(FileObject)
* In binary file data is in unreadable format. To work on a binary file, we have to convert
the data into readable form for read as well as write operation.
* The binary file stores some objects which have some structure associated with them.
Like list, nested list, tuple, dictionary etc..
* These objects are first serialized and then stored in a binary file.
* If a binary file (existing) open for reading purpose, when the last record is reached (EOF
reached), it may raise an EOF Error exception, if not handled properly.
* Thus a binary file should open for reading purposes either in “try and except” blocks or
using “with statement”.
Serialization or Pickling:
It is the process of transforming a python object to a stream of bytes called byte
streams. These byte streams can then be stored in binary files. Serialization process is
also called pickling.
De-serialization or un-pickling:
It is the reverse of the pickling process where a byte stream is converted back to a
Python object.
The pickle module implements the algorithm for serializing and de-serialization the
python objects and deals with binary files. The Pickle Module must be imported to read
and write objects in binary files.
MODES OF BINARY FILES
b = Open the binary file
rb = Open binary file in read only mode (file must be existed)
wb = Open binary file in write only mode (new file created, overwritten if existed)
ab = Open binary file in append (write only) mode. (Open if exists otherwise create
new file)
rb+ = Open binary file in read & write mode. (file must be existed)
wb+ = Open binary file in write & read mode. (new file created, overwritten if
existed)
ab+ = Open binary file in append (write & read) mode. (Open if exists otherwise
create new file)
BASIC OPERATIONS ON BINARY FILE
· Creating a new file
· Reading from file
· Writing into file
· Appending the file
· Searching in File
· Deleting data from file
· Creating a copy of file
18
OPENING AND CLOSING A BINARY FILE
open( ) function:
Syntax:
File_Object=open(file_name, access mode)
Example:
file_obj= open(“bin_file.dat”,'wb')
This statement opens bin_file.dat binary file in write mode.
Note : if file mode is not mentioned in open function then default file mode i.e 'rb' is used,
close() function:
The close( ) method of a file object flushes any unwritten information and close the file
object after which no more writing can be done. Example: file_obj.close( )
WRITING DATA INTO A BINARY FILE
To write an object into file, the file should be opened in write mode. The dump( )
function of the pickle module is used to write objects into a binary file.
Syntax:
import pickle
File_Handler=open(“Bin_file.dat”,’wb’)
pickle.dump(python_Obj_to_be_Written, File_obj)
Example:
# To Write a Dictionary Object in Binary file.
import pickle
stud={ }
fwb=open("student.dat","wb")
choice='y'
while choice.lower()=='y':
rno=int(input("Enter Roll No: "))
name=input("Enter Name: ")
marks=float(input("Marks out of 500 "))
per=marks/5
if (per>=33):
res="Pass"
else:
res="Fail"
stud['rollno']=rno
stud['name']=name
stud['Marks']=marks
stud['percent']=per
stud['result']=res
pickle.dump(stud, fwb)
print("Record Saved in File")
choice=input("More Record(Y/N)? ")
fwb.close()
APPENDING DATA IN BINARY FILE
19
Binary file must be opened in append mode (i.e., "ab'") to append the records in file. A file
opened in append mode will retain the previous records and write the new records at the
end.
Syntax:
import pickle
File_Handler=open(“Bin_file.dat”,’ab’)
pickle.dump(python_Object_to_be_Written, File_Handler)
Example:
# To Append data in the Binary file
import pickle
stud={}
fwb=open("student.dat","ab")
choice='y'
while choice.lower()=='y':
rno=int(input("Enter Roll No: "))
name=input("Enter Name: ")
marks=float(input("Marks(out of 500): "))
per=marks/5
if(per>=33):
res="Pass"
else:
res="Fail"
stud['rollno']=rno
stud['name']=name
stud['Marks']=marks
stud['percent']=per
stud['result']=res
pickle.dump(stud, fwb)
print("Record Saved in File")
choice=input("More Record(Y/N)? ")
fwb.close()
READING DATA FROM A BINARY FILE:
While working with a binary file for reading purposes the runtime exception EOFError
raised when it encountered the EOF position. This EOFError exception can be handled
with two ways.
1. Use of try and except block
The try and except statements together, can handle runtime exceptions. In the try block,
i.e., between the try and except keywords, write the code that can generate an exception
and in the except block, ie., below the except keyword, write what to do when the
exception (EOF - end of file) has occurred
Syntax:
File_object=(“binary File Name”,’access mode’)
try:
…………………………………………….……….
20
Write actual code, work in binary file
……………………………………………………..
except EOFError:
……………………………………………………
Write Code here that can handle the error raised in try block.
…………………………………………………
2. Use of ‘with’ statement
The ‘with’ statement is a compact statement which combines the opening of file,
processing of file along with inbuilt exception handling and also closes the file
automatically after with block is over.
Explicitly, we need not to mention any exception for the “with statement”.
Syntax:
with open(“File_Name”,’mode’) as File_Handler:
# Read Records from Binary file
import pickle
stud={}
frb=open("student.dat","rb")
try:
while True:
stud=pickle.load(frb)
print(stud)
except EOFError:
frb.close()
SEARCHING DATA FROM A BINARY FILE
import pickle
stud={}
found=0
print("Searching in file student.dat...")
try:
frb=open("student.dat", "rb")
while True:
stud=pickle.load(frb)
if stud['percent']>51.0:
print(stud)
found+=1
except EOFError:
if found==0:
print("No Record with marks>51")
else:
print(found," Record(s) found")
frb.close()
COPYING A BINARY FILE DATA TO ANOTHER BINARY FILE
import pickle
def fileCopy():
ifile = open("student.dat","rb") # Existing File
21
ofile = open("newfile.dat","wb") # New File
try:
while True:
rec=pickle.load(ifile)
pickle.dump(rec,ofile)
except EOFError:
ifile.close()
ofile.close()
print("Copied successfully")
def display1():
ifile = open("student.dat","rb")
print("----Records of Student file---")
try:
while True:
rec=pickle.load(ifile)
print(rec)
except EOFError:
ifile.close()
def display2():
ofile = open("newfile.dat","rb")
print("----Records of Copy file---")
try:
while True:
rec=pickle.load(ofile)
print(rec)
except EOFError:
ofile.close()
fileCopy()
display1()
display2()
flush() Method: This method will force out any unsaved data that exists in a program
buffer to the actual file. Python automatically flushes the files when closing them. But
you may want to flush the data before closing any file.
Syntax: FileObject.flush()
CSV File: CSV (Comma Separated Values) format is one of the most simple and common
ways to store data in tabular form. Each record consists of one or more fields separated by
commas. To represent a CSV file, it must be saved with the .csv file extension. It is
a file format for data storage which looks like a text file. The information is organized with
one record in each line and each field is separated by comma.
● It is a plain text file that contains the comma-separated data.
● These files are often used for exchanging data between different applications.
● CSV files are usually created by programs that handle huge amounts of data. They
are used to export data from spreadsheets (ex:- excel file) and databases (Ex:-
Oracle, MySQL). It can be used to import data into a spreadsheet or a database.
(i) Working with csv file: csv files are used to store a large number of variables or
data. They are incredibly simplified spreadsheets. Each line in a csv file is a data record.
(ii) Read from CSV File: Using csv.reader(): To read data from csv files, you must
use the reader() function to generate a reader object. This function returns a reader
object which is an iterator of lines in the csv file.
Syntax: csv.reader()
(iii) csv.writer (): The csv.writer(file object) function returns a writer object that converts
the user’s data into delimiter string.
(iv) Write into a CSV File using csv.writerow(): To write an existing file, you must
first open the file in one of writing modes (w, a or r+) first. then writerow() function is
used to write items in a sequence (list, tuple or string) separating them by comma.
(v) Writerows():If we need to write the content of 2‐Dimensional list into csv file,
instead of using writerow() function many times, we can write use object.writerows()
method.
Syntax for accessing modules: import module_name
Syntax for accessing methods: Objectname=module name.method_name()
writer( ) Methods:
This function returns a writer object which is used for converting the data given by the
user into delimited strings on the file object.
writer( ) Object Methods –
· w_obj . writerow( <Sequence> ) #Write a Single Line
· w_obj . writerows ( <Nested Sequence> ) #Write Multiple Lines
Example:-
# writerow()
import csv
row=['Nikhil', 'CEO', '2', '9.0']
f=open("myfile.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
# writerows()
import csv
25
rows = [['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','2','9.1']]
f=open("myfile.csv",'w')
w_obj = csv.writer(f)
w_obj.writerows(rows)
f.close()
reader( ) Methods:
This function returns a reader object which will be used to iterate over lines of a given
CSV file.
r_obj = csv.reader( csvfile_obj )
To access each row, we have to iterate over this object.
for i in r_obj:
print(i)
Example:-
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f)
for data in r_obj:
print(data)
f.close()
If we consider the sample.csv file given above in the CSV file structure the output of the
above code will be:
## OUTPUT:
['Name', 'DOB', 'City']
['Ram', '12-Jul-2001', 'Delhi']
['Mohan', '23-Jan-2005', 'Delhi']
['Suraj', '17-Dec-2002', 'Kolkata']
def traverse(stack):
if (isEmpty(stack)):
print("Stack is Empty ")
else:
for i in stack:
print(i, end=" ")
def peak(stack):
global top
return stack[top]
def isFull(stack):
global maxsize
if (top==maxsize-1):
return True
else:
return False
def isEmpty(stack):
if (top==-1):
return True
else:
return False
Q2. What is the difference between read(‘r’) and write(‘w’) mode of file?
Ans: Read mode: - Opens a file for reading, error if the file does not exist. Write mode: Opens
a file for writing, creates the file if it does not exist.
Q4. Which method is used to specify current position and particular position of file object
respectively?
Ans: tell ( )-specify current position of file object and seek ( )- specify the particular position
of file object.
Q7. Which of the following statements correctly explain the function of seek()
method?
(a) Tells the current position within the file.
(b) Determines if you can move the file position or not.
(c) Indicates that the next read or write occurs from that position in a file.
(d) Moves the current file position to a given specified position
Ans: (d) Moves the current file position to a given specified position
Note: seek() method moves the current file position to a given specified position.
This method does not return any value.
29
Ans: A text file consists of human readable characters, which can be opened by any
Text editor. while, binary files are made up of non-human readable characters
and symbols, which require specific programs to access its contents.
Q.11. Which of the following statement opens a binary file ‘test.bin’ in write mode and
writes data from a tuple t1=(2, 5, 8, 2) on the binary file?
(a) with open(‘test.bin’,‘wb’) as f: (b) with open(‘test.bin’,‘wb’) as f:
pickle.dump(f, t1) pickle.dump(t1,f)
(c) with open(‘test.bin’,‘wb+’) as f: (d) with open(‘test.bin’,‘ab’) as f:
pickle.dump(f,t1) pickle.dump(f,t1)
Ans: (b) with open(‘test.bin’,‘wb’) as f:
pickle.dump(t1,f)
03 marks questions:
Q1. ICC has created a dictionary containing top players and their runs as key value
pairs of cricket team. Write a program, with separate user defined functions to perform
the following operations:
● Push the keys (name of the players) of the dictionary into a stack, where the
corresponding value (runs) is greater than 59.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
SCORE={"Mukesh":43, "Virendra":64, "Rajesh":88, "Amit":75, "Wajid":97 }
The output from the program should be:
Virendra Rajesh Amit Wajid
Ans:
SCORE={"Mukesh":43, "Virendra":64, "Rajesh":88, "Amit":75, "Wajid":97 }
def PUSH(S,R):
S.append(R)
def POP(S):
if S!=[]:
return S.pop()
else:
return None #Message
ST=[ ]
for k in SCORE:
if SCORE[k]>59:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
30
else:
break
Q2. Madhuri has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the following operations based on this
list.
● Traverse the content of the list and push the ODD numbers into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
13,21,89,35
Ans:
N=[12, 13, 34, 56, 21, 79, 98, 22,35, 38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[ ]:
return S.pop()
else:
return None
ST=[ ]
for k in N:
if k%2!=0:
PUSH(ST,k)
while True:
if ST!=[ ]:
print(POP(ST),end=" ")
else:
break
Q3. Mayur Enterprises have a dictionary of top performer EMPLOYEES and their SALES
of as key value pairs of COMPANY. Write a program, with separate user defined
functions to perform the following operations:
● Push the keys (name of the EMPLOYEE) of the dictionary into a stack, where the
corresponding value (SALES) is greater than 500000.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
SALES={"SUNIL":700000, "ROHIT":400000, "RAJEEV":350000, "MAYANK":750000,
"RAHUL":1000000, }
The output from the program should be: SUNIL MAYANK RAHUL
Solution:
SALES={"SUNIL":700000, "ROHIT":400000, "RAJEEV":350000, "MAYANK":750000,
"RAHUL":1000000, }
def PUSH(STK,S):
STK.append(S)
def POP(STK):
if STK!=[]:
return STK.pop()
31
else:
return None
ST=[]
for k in SALES:
if SALES[k]>500000:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
Q4. Saroj have a list of 10 numbers . You need to help him create a program with
separate user defined functions to perform the following operations based on this list.
● Traverse the content of the list and push the numbers into a stack which are divisible
by 5.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[2,5,10,13,20,23,45,56,60,78]
Sample Output of the code should be:
5,10,20,45,60
Solution:
N= [2,5,10,13,20,23,45,56,60,78]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%5==0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
04 Marks Questions:
Q1. 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.
32
He has succeeded in writing partial code and has missed out certain statements, so he has
left certain queries in comment lines. You as an expert of Python have to provide the
missing statements and other related queries based on the following code of Amritya.
import pickle
def AddStudents():
____________ #1 statement to open the binary file to write data
while True:
Rno = int(input(“Rno :”))
Name = input(“Name:”)
Percent = float(input(“Percent :”))
L = [Rno, Name, Percent]
____________ #2 statement to write the list L into the file
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: ____________ #3 statement to read from the file
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”)
average=Total/Countrec
print(“average percent of class = ”, average)
AddStudents()
GetStudents()
Answer the questions from the above mentioned program:
(i) Which of the following commands is used to open the file “STUDENT.DAT” for writing
only in binary format? (marked as #1 in the Python code)
(a) F= open(“STUDENT.DAT”,‘wb’) (b) F= open(“STUDENT.DAT”,‘w’)
(c) F= open(“STUDENT.DAT”,‘wb+’) (d) F= open(“STUDENT.DAT”,‘w+’)
Ans: (a) F= open(“STUDENT.DAT”,‘wb’) #To open the file binary, open() function is
used.
(ii) Which of the following commands is used to write the list L into the binary file
‘STUDENT.DAT’? (marked as #2 in the Python code)
(a) pickle.write(L,f) (b) pickle.write(f, L) (c) pickle.dump(L,F) (d) f=pickle.dump(L)
Ans: (c) pickle.dump(L,F) #To write the list L into file, pickle.dump (L,F) is used.
#For using dump() method, you first have to import the pickle
module.
33
(iii) Which of the following commands is used to read each record from the binary file
‘STUDENT.DAT’? (marked as #3 in the Python code)
(a) R = pickle.load(F) (b) pickle.read(r,f) (c) r= pickle.read(f) (d)
pickle.load(r,f)
Ans: (a) R = pickle.load(F) #The correct statement used in marked as #3 is
R=pickle.load(F) #because load() method is used to load
data from a binary file.
(iv) Which of the following statement(s) are correct regarding the file access modes?
(a) ‘r+’ opens a file for both reading and writing. File object points to its beginning.
(b) ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file, if it
exists and creates a new one, if it does not exist.
(c) ‘wb’ opens a file for reading and writing in binary format. Overwrites the file, if it exists
and creates a new one, if it does not exist.
(d) ‘a’ opens a file for appending. The file pointer is at the start of the file, if the file exists.
Ans: (a) ‘r+’ opens a file for both reading and writing. File object points to its beginning.
#The correct statement regarding file access modes is r+ opens a file for both
#reading and writing. File object points to its beginning.
Q2. Consider a binary file stock.dat that has the following data: OrderId,
MedicineName, Qty and Price of all the medicines of wellness medicos, write the
following functions:
a)AddOrder() that can input all the medicine orders.
b)DisplayPrice() to display the details of all the medicine that have Price more than
10.
Ans:(a)
import pickle
def AddOrder():
f=open("Stock.dat",'ab')
OrderId=input("Enter Order Id")
MedicineName=input("Enter Medicine Name")
Qty=int(input("Enter Quantity:"))
Price=int(input("Enter Price:"))
data=[OrderId,MedicineName,Qty,Price]
pickle.dump(data,f)
f.close()
AddOrder()
(b)
def DisplayPrice():
f=open("Stock.dat",'rb')
try:
while True:
data=pickle.load(f)
if data[3]>10:
print(data[0],data[1],data[2],data[3],sep="\t")
except:
34
f.close()
DisplayPrice()
Q3. Create a binary file funandfood.dat (a) Write a function AddRides() that can store
details of rides such as Ticketno, Ridename, No_ofpersons, and price with the help of
(b) Write python function displayTotal to display total amount of each ticket. Also
count total number of tickets sold.
Ans: (a)
import pickle # to use binary file
def AddRides():
f=open("funandfood.dat",'ab')
Ticketno=input("Enter Ticket Number")
RideName=input("Enter The Name of Ride")
No_ofperson=int(input("Enter no of Persons"))
Price=int(input("Enter Price:"))
data=[Ticketno,RideName,No_ofperson,Price]
pickle.dump(data,f)
f.close()
AddRides()
(b)
def DisplayTotal():
f=open("funandfood.dat",'rb')
total=0
count=0
try:
while True:
data=pickle.load(f)
total=data[2]*data[3]
print(data[0],data[1],data[2],data[3],total,sep="\t")
count=count+1
except:
f.close()
print("Total number of Tickets sold are:",count)
DisplayTotal()
Q4. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
(a) Write a user defined function CreateFile() to input data for a record and add to
Book.dat.
(b) Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and retum number of books by the given Author are stored in
the binary file “Book.dat”.
Ans: (a)
import pickle
35
def CreateFile():
fobj=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author: ")
Price = int(input("Price : "))
rec=[BookNo,Book_name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()
CreateFile()
(b)
def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
name=input(“Enter author name :”)
print(CountRec(name))
Q5. A binary file named “TEST.dat” has some records of the structure [Subject,
ScoredMarks].
(a) Write a function in Python named AddRec() to add following records in the file
“TEST.dat”.
["maths", 96]
["cs",95]
["maths",90]
["cs",80]
(b) Write a function in Python named DisplayAvgMarks(Sub) that will accept a
subject as an argument and read the contents of TEST.dat. The function will calculate
& display the Average of the ScoredMarks of the passed Subject on screen.
Ans: (a)
import pickle
def AddRec():
f=open("TEST.dat","wb")
pickle.dump(["maths",96],f)
pickle.dump(["cs",95],f)
pickle.dump(["maths",90],f)
pickle.dump(["cs",80],f)
f.close()
AddRec()
(b)
def DisplayAvgMarks(sub):
f=open("TEST.dat","rb")
count=0
sum=0
36
try:
while True:
#pos=f.tell()
rec=pickle.load(f)
if rec[0]==sub:
sum+=rec[1]
count+=1
except:
f.close()
print("AVG Marks:",sum/count)
sub=input(“Enter subject :”)
DisplayAvgMarks(sub)
Q6. Arun, during Practical Examination of Computer Science, has been assigned an
incomplete search() function to search in a pickled file student.dat. The file student.dat
is created by his teacher and the following information is known about the file.
● File contains details of students in [roll_no,name,marks] format.
● File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each
student is written in the binary file using dump().
Arun has been assigned the task to complete the code and print details of roll number 1.
def search():
f = open(“student.dat”,____) #Statement 1
____: #Statement 2
while True:
rec = pickle.____ #Statement 3
if(____): #Statement 4
print(rec)
except:
pass
f.close()
Answer the questions from the above mentioned program:
(i) In which mode, Arun should open the file in Statement 1?
(a) r (b) r+ (c) rb (d) wb
Ans: (c) rb # This mode opens a file for reading only in binary format
(ii) Identify the suitable code to be used at blank space in line marked as Statement 2.
(a) if(rec[0]==1) (b) for i in range(10) (c) try (d) pass
Ans: (c) try
(iii) Identify the function (with argument), to be used at blank space in line marked as
Statement 3.
(a) load() (b) load(student.dat) (c) load(f) (d) load(fin)
Ans: (c) load(f) #This method is used to load data from a binary file.
(iv) What will be the suitable code for blank space in line marked as Statement 4.
(a) rec[0]==2 (b) rec[1]==2 (c) rec[2]==2 (d) rec[0]==1
Ans: (d) rec[0]==1
37
05 Marks Questions:
Q1. Mohit, a student of Class 12th, is learning CSV File Module in Python. During
examination, he has been assigned an incomplete Python code (shown below) to create
a CSV File ‘Student.csv’ (content shown below). Help him in completing the code which
creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
Incomplete Code
import_____ #Statement 1
fh = open(_____, _____, newline=‘ ’) #Statement 2
stuwriter = csv._____ #Statement 3
data = [ ]
header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
data.append(header)
for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_____] #Statement 4
data.append(rec)
stuwriter. _____ (data) #Statement 5
fh.close()
Answer the questions from the above mentioned program:
(i) Identify the suitable code for blank space in line marked as Statement 1.
(a) csv file (b) CSV (c) csv (d) Csv
Ans: (c) csv
(ii) Identify the missing code for blank space in line marked as Statement 2.
(a) “School.csv”,“w” (b) “Student.csv”,“w” (c) “Student.csv”,“r” (d) “School.csv”,“r”
Ans: (b) “Student.csv”,“w”
# It opens a file student.csv in write mode because append( ) method is using.
(iii) Choose the function name (with argument) that should be used in the blank space
of line marked as Statement 3.
(a) reader(fh) (b) reader(MyFile) (c) writer(fh) (d) writer(MyFile)
Ans: (c) writer(fh) #csv. writer is used to insert data to the CSV file.
38
(iv) Identify the suitable code for blank space in line marked as Statement 4.
(a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’ (b) ROLL_NO, NAME, CLASS, SECTION
(c) ‘roll_no’,‘name’,‘class’,‘section’ (d) roll_no,name,class,section
Ans: (d) roll_no,name,class,section
(v) Choose the function name that should be used in the blank space of line marked as
Statement 5 to create the desired CSV file?
(a) dump( ) (b) load( ) (c) writerows( ) (d) writerow( )
Ans: (c) writerows( )
#writerows() writes each sequence in a list as a comma separated line of items in file.
Q2. Abhishek is making a software on “Countries & their Capitals” in which various
records are to be stored/retrieved in CAPITAL.CSV data file. It consists of some
records. He has written the following code. As a programmer, you have to help him
to successfully execute the program.
(a) Write a function in Python named AddNewRec(Country,Capital) to append
following records in the file “CAPITAL.CSV”.
[“FRANCE”,”PARIS”]
[“SRILANKA”,”COLOMBO”]
(b) Write a function in Python named ShowRec( ) that will show all the contents
of CAPITAL.CSV.
Ans: (a)
import csv
def AddNewRec(Country,Capital):
f=open("CAPITAL.CSV",'a')
fwriter=csv.writer(f,lineterminator="\n")
fwriter.writerow([Country,Capital])
f.close()
(b)
def ShowRec():
with open("CAPITAL.CSV","r") as NF:
NewReader=csv.reader(NF)
for rec in NewReader:
print(rec[0],rec[1])
AddNewRec(“FRANCE”,”PARIS”)
AddNewRec(“SRILANKA”,”COLOMBO”)
ShowRec()
Q3. Radha Shah is a programmer, who has recently been given a task to write a Python
code to perform the following CSV file operations with the help of two user defined
functions/modules:
(a) CSVOpen() : to create a CSV file called books.csv in append mode containing
information of books – Title, Author and Price.
(b) CSVRead() : to display the records from the CSV file called books.csv where the field
title starts with ‘R’.
Ans:(a)
import csv
39
def CSVOpen():
with open('books.csv','a',newline='') as csvf:
cw=csv. writer (csvf)
cw. writerow ([ 'Title', 'Author', 'Price'])
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Rarbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
(b)
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=csv. reader (csvf)
for r in cr:
if r [0] [0] == 'R':
print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()
40
Unit : 3 introduction to Computer Networks
Network:-
The collection of interconnected computing devices is called a network. Two computing
devices are said to be interconnected if they are capable of sharing and exchanging
information.
Benefits of Network: -
(1) Resource Sharing: Resource Sharing means to make the
applications/programs, data(files) and peripherals available to anyone on the
network irrespective of the physical location of the resources and the user.
(2) Reliability: Reliability means to keep the copy of a file on two or more different
machines, so if one of them is unavailable (due to some hardware crash or any
other) them its other copy can be used.
(3) Cost Factor: Cost factor means it greatly reduces the cost since the resources can
be shared. For example a Printer or a Scanner can be shared among many
computers in an office/Lab.
(4) Communication Medium: Communication Medium means one can send and
receive messages. Whatever the changes at one end are done, can be
immediately noticed at another.
EVOLUTION OF NETWORKING
ARPANET (1969) – US Government formed an agency named ARPANET( Advanced
Research Project Agency Network) to connect computers at various universities and
defence agencies to share data/information efficiently among all of them.
NSFNET (1985) - National Science Foundation Network was a program of
coordinated, evolving projects sponsored by the National Science Foundation (NSF) from
1985 to 1995 to promote advanced research and education networking in the United
States. The program created several nationwide backbone computer networks in
support of these initiatives. Initially created to link researchers to the NSF-funded
supercomputing centers, through further public funding and private industry
partnerships it developed into a major part of the Internet backbone.
INTERNET (1990)- INTER-connection NETwork , The worldwide network of
networks.
41
Data communication terminologies:
Concept of communication: Communication is the act of sending and receiving data
from one device to another device or vice-versa. Data can be of any form i.e. text, image,
audio, video and multimedia files.
Components of Data communication:
Sender: A device that can send data over a network i.e. computer, laptop, smart phone
etc.
Receiver: A device can receive data over a network i.e. computer, laptop, smart phone
etc.
The sender and receivers are basically called nodes.
Message: It is the data/information that needs to be shared between the sender and
receiver.
Communication media: It is the medium through which the data/information is
travelled between the
sender and receiver. These may be wired or wireless.
Protocols: A network protocol is an established set of rules that determine how data is
transmitted between different devices in the same network. Essentially, it allows
connected devices to communicate with each other, regardless of any differencesin their
internal processes, structure or design.
Measuring Capacity of Communication Media: In data communication, the
transmission medium is also known as channel. The capacity of a channel is the maximum
amount of signals or traffic that a channel can carry. It is measured in terms of bandwidth
and data transfer rate as described below:
Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of data
through that channel.
Higher the bandwidth, higher the data transfer rate.
Normally, bandwidth is the difference of maximum and minimum frequency contained in
the composite signals.
Bandwidth is measured in Hertz (Hz).
1 KHz = 1000 Hz, 1 MHz =1000
Data Transfer Rate
Data travels in the form of signals over a channel. One signal carries one or more bits over
the channel. Data transfer rate is the number of bits transmitted between source and
destination in one second. It is also known as bit rate. It is measured in terms of bits per
second (bps). The higher units for data transfer rates are:
1 Kbps=1024 bps
1 Mbps=1024 Kbps
1 Gbps=1024 Mbps
IP Address:
An IP address is a unique address that identifies a device on the internet or a local
network. IP stands for "Internet Protocol," which is the set of rules governing the format
of data sent via the internet or local network.
Switching techniques:
In large networks, there may be more than one path for transmitting data from sender to
receiver. Selecting a path that data must take out of the available options is called
switching. There are two popular switching techniques – circuit switching and packet
switching.
Circuit switching: Circuit switching is a type of network configuration in which a
physical path is obtained and dedicated to a single connection between two endpoints in
the network for the duration of a dedicated connection. Ordinary landline telephone
42
service uses circuit switching.
Packet switching: Packet switching is the method by which the internet works; it
features delivery of packets of data between devices over a shared network. For example
the school web server is sending you a webpage over the internet or you sending an email
to a friend.
Transmission Media: Transmission media is a communication channel that carries the
information from the sender to the receiver. All the computers or communicating devices
in the network must be connected to each other by a Transmission Media or channel.
➢ A Transmission medium is a medium of data transfer over a network.
➢ The selection of Media depends on the cost, data transfer speed, bandwidth and
distance. Transmission media may be classified as
44
Network Topologies:
Topology: Topology refers to the way in which the
device/computer/workstations attached to the
network are interconnected.
The layout of interconnection of devices in a
network is called Topology.
Different Topologies are: Star, Bus, Tree, Mesh.
BUS Topology: - The bus topology uses a common
single cable (backbone cable) to connect all the workstations. Each computer performs
its task of sending messages without the help of the central server. However, only one
workstation can transmit a message at a particular time in the bus topology.
Advantages:
(i) Easy to connect and install.
(ii) Involves a low cost of installation time.
(iii) Can be easily extended.
Disadvantages:-
(i) The entire network shuts down if there is a failure in the central cable.
(ii) Only a single message can travel at a particular time.
(iii) Difficult to troubleshoot an error.
STAR Topology: -In Star topology, each node is directly connected to a central device like
Hub or Switch. It is most popular topology to form Local Area Networks (LAN).
Advantages:
(i) Easy to troubleshoot
(ii) A single node failure does not affects the entire network.
(iii) Fault detection and removal of faulty parts is easier.
(iv) In case a workstation fails, the network is not affected.
Disadvantages: -
(i) Difficult to expand.
(ii) Longer cable is required.
(iii) The cost of the hub and the longer cables makes it expensive
over others.
(iv) All nodes are dependent on central node. if the central device (Switch) goes down
then entire network breaks down.
TREE Topology: - The tree topology combines the characteristics of the linear bus and
the star topologies. It consists of groups of star – configured workstations connected to a
bus backbone cable.
Advantages:
(i) Eliminates network congestion.
(ii) The network can be easily extended.
(iii) Faulty nodes can easily be isolated from the rest of the
network.
Disadvantages:
➢ Uses large cable length.
➢ Requires a large amount of hardware components and
hence is expensive.
➢ Installation and reconfiguration are very difficult.
Types of Computer Network:
A computer network may be small or big as per number of computers and other
network devices linked together. A computer network may contain devices ranging from
45
handheld devices (like mobile phones, tablets, laptops) connected through Wi-Fi or
Bluetooth within a single room to the millions of computers spread across the globe.
Based on the size, coverage area, data transfer speed and complexity, a computer network
may be classified as:
LAN (Local Area Network): A Local Area Network (LAN) is a network that is limited to
a small area. It is generally limited to a geographic area such as within lab, school or
building. It is generally privately-owned networks over a distance up to a few kilometers.
Now-a-days, we also have WLAN (Wireless LAN) which is based on wireless network.
MAN (Metropolitan Area Network): MAN is the networks cover a group of nearby
corporate offices or a city and might be either private or public. Cable TV network or cable
based broadband internet services are examples of MAN.
WAN (Wide Area Network):These are the networks spread over large distances, say
across countries or even continents through cabling or satellite uplinks are called WAN.
Typically, a WAN combines multiple LANs that are geographically separated. It is a
network of network. The world’s most popular WAN is the Internet.
Network Protocols:
46
➢ Telnet is protocol which used for login on remote computer to access/transfer
files or trouble shooting.
FTP (File Transfer Protocol) is a network protocol for transmitting files between
computers over Transmission Control Protocol/Internet Protocol (TCP/IP) connections.
Point-to-Point Protocol (PPP) is a TCP/IP protocol that is used to connect one
computer system to another. Computers use PPP to communicate over the telephone
network or the Internet. A PPP connection exists when two systems physically connect
through a telephone line.
Overview of Internet:
➢ Internet is a network of networks that consists of millions of private, public,
academic, business, and government networks, that are linked by various wired,
wireless, and optical networking technologies.
➢ The Internet is a global system of interconnected computer networks that use the
standard Internet protocol suite (TCP/IP) to serve several billion users
worldwide.
47
➢ The modern Internet is an extension of ARPANET (Advance Research Project
Agency Network), created in1969 by the American Department of Defense.
➢ In 1990 the British Programmer Tim Berners-Lee developed Hypertext and HTML
to create World Wide Web (WWW).
➢ The Internet carries an extensive range of information resources and services,
such as the inter-linked hypertext documents of the World Wide Web (WWW), the
communicational infrastructure to support mail, chat and transfer of Text, Images,
Audio, Video etc.
In the above URL, http is the protocol name, it can be https, http, FTP, Telnet, etc.
www is a sub domain. ncert.nic.in is the domain name. Textbook is directory and
textbook.htm is webpage.
48
The complete unique address of the page on a website is called URL (Uniform Resource
Locator) e.g. http://www.cbse.nic.in/welcome.html
Since computers on the network are identified by its IP addresses, so it is required
to convert a Domain name or URL typed in the Browser, in to its corresponding IP
address. This process is called Domain Name Resolution. This resolution is done by the
designated servers called DNS servers, provided by the Internet Service Providers (ISP)
like BSNL, Airtel, Jio etc.
Website:
➢ Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
website.
➢ A website is a collection of web pages related through hyperlinks, and saved on a
web server. A visitor can navigate pages by clicking on hyperlinks.
➢ The main purpose of website is to make the information available to people at
large. For example, a company may advertise or sell its products, a government
organization may publish circulars, float tenders, invite applications for
recruitments etc.
➢ A website can be accessed by providing the address of the website (URL) in the
browser. The main page of website (Home page) will be open when it is opened
on the browser.
Web Page:
➢ A web page is a document on the WWW that is viewed in a web browser. Basic
structure of a web page is created using HTML (Hyper Text Markup Language).
➢ To make web pages more attractive, various styling CSS (Cascading Style Sheets)
and formatting are applied on a web page.
➢ Further, program codes called scripts also used to make webpage interactive and
define different actions and behavior. JavaScript, PHP and Python are commonly
used script language.
➢ The first page of the website is called a home page which contains Menus and
Hyperlinks for other web pages.
➢ A web page is usually a part of a website and may contain information in different
forms, such as: text, images, audio & video, Hyperlinks, interactive contents (chat
etc.)
A web page can be of two types: Static Web Page and Dynamic Web Page
Web Browsers:
➢ A web browser or simply ‘browser’ is a software application used to access
information on the World Wide Web. When a user requests some information, the
web browser fetches the data from a web server and then displays the webpage
on the user’s screen.
➢ The popular web browsers are Google Chrome, Mozilla Firefox, Internet Explorer,
Opera, Safari, Lynx and Netscape Navigator, Microsoft Edge etc.
➢ A web browser essentially displays the HTML documents which may include text,
images, audio, video and hyperlinks that help to navigate from one web page to
another. The modern browsers allow a wide range of visual effects, use encryption
for advanced security and also have cookies that can store the browser settings
and data.
49
Web Server:
➢ A web server is used to store and deliver the contents of a website to web clients
such as a browser.
➢ A Computer stores web server software and a website's contents (HTML pages,
images, CSS style sheets, and JavaScript files). The server needs to be connected to the
Internet so that its contents can be made accessible to others.
➢ Web server as a software, is a specialized program that understands URLs or web
addresses coming as requests from browsers, and responds to those requests.
➢ The server is assigned a unique domain name so that it can be accessed from
anywhere using Internet. The web browser from the client computer sends a HTTP
request for a page containing the desired data or service. The web server then accepts
request, interprets, searches and responds (HTTP response) against request of the
web browser. The requested web page is then displayed in the browser of the client. If
the requested web page is not found, web server generates “Error: 404 Not found” as
a response.
Web Hosting:
➢ A web hosting service is a type of Internet hosting service that allows individuals and
organisations to make their website accessible via the World Wide Web. In Simple,
uploading of website on Web Server is known as hoisting. To upload the website, we
need some web space on server to upload website. This space is available on some
nominal charges.
➢ All web servers are assigned a unique numeric address called IP address when
connected to the Internet. This IP address needs to be mapped/changed to domain name
(Textual name) of the website using DNS (Domain Name Service). Thus, user can access
website by providing domain name through a browser (URL). The domain name has to
be registered (purchased) with an authorized agency i.e. Registrar Domain Names.
50
EXPANDED FORMS
ARPANET= Advance Research Project Agency Network (1969)
NIU= Network Interface Unit
LAN= Local Area Network
MAN= Metropolitan Area Network
WAN= Wide Area Network
ISP= Internet Service Provider
OSS= Open Source Software
ISDN= Integrated Service Digital Network
FLOSS= Free Libre Open Source Software
NIC= Network Interface Card
UTP= Unshielded Twisted Pair
STP= Shielded Twisted Pair
MODEM= Modulator Demodulator
RJ-45= Registered Jack -45
XML= Extensible Markup Language
FTP=File Transfer Protocol
TCP= Transmission Control Protocol
SMTP= Simple Mail Transfer Protocol
POP3= Post Office Protocol 3 (Version 3)
IMAP= Internet Message Access Protocol
IP= Internet Protocol
SLIP= Serial Line Internet Protocol
PPP= Point To Point Protocol
PDA= Personal Data Assistant
GSM= Global System For Mobile
SIM=Subscriber Identity Module
CDMA= Code Division Multiple Access
WLL= Wireless In Local Loop
WWW= World Wide Web
URL=Uniform Resource Locator
DHTML= Dynamic Hyper Text Markup Language
OSS= Open Source Software
GNU= GNU’s Not Unix
FSF= Free Software Foundation
OSI= Open Source Initiative
HTTP=Hyper Text Transfer Protocol
HTTPS : Hyper Text Transfer Protocol Secure
HTML= Hyper Text Markup Language
W3C= World Wide Web Consortium
ASP= Active Server Pages
JSP=Java Server Pages
51
Important Question-Answers as per CBSE Sample Paper 2022-23 Pattern
1-Mark Questions (MCQs, Fill in the blank & One Word answer types)
1. The main computer in any network is called as
(a) Switch (b) Hub (c) Client (d) Server
Ans: (d) Server
2. Mahesh, a Class X student, has just started understanding the basics of Internet
and web technologies. He is bit confused in between the terms “ Website‘ and ‘Webpage’
. Help him in understanding both the terms with the help of suitable examples of each.
Ans: Website: Website is a collection of web pages displayed on web with a web
browser.
It contains more than one webpages.
Webpage: It is a part of website that includes information and content and is displayed
on the browser to user. It is a single document display on browser
3. Sushil, a Class X student, has just started understanding the basics of Internet
and web technologies. He is bit confused in between the terms “ Web page ‘ and ‘Home
Page’ . Help him in understanding both the terms with the help of suitable examples of
each.
Ans:
Home Page Webpage
It is the first or main page of a It is a part of website that includes
website information and content and is displayed on
the browser to user.
Every website has this page and It is a single document display on browser
appears when the user go to a even home page is also a webpage
website.
4. Yuvika, a Class X student, has just started understanding the basics of Internet
and web technologies. She is bit confused about the term ‘web servers’ . Help her in
understanding the terms along with the utility of web servers.
Ans: A web server is a computer or a group of computers that hosts or stores content of
website.
It processes and delivers web pages of the websites to the users.
The main job of a web server is to display the website content.
A web server provides four major functions:
(i) Serving web pages
(ii) Running gateway programs and returning output
(iii) Controlling access to the server.
Monitoring and logging server access statistics.
53
5. Neeta is a bit confused between the term URL and Domain Name. Help him in
understanding both the terms with the help of suitable explanation using an example.
Ans:
URL Domain Name
It stands for Unifom Resource It is a website address.
locator.
It is the complete address of a It is the address we give on browser's
website on the internet. search bar to directly access your website
e.g.www.no2jaipur.com/index.html e.g. cbse.nic.in
6. Nirmala is a bit confused between the terms Web server and Web browsers. Help
her in understanding both the terms with the help of suitable example.
Ans:
Web Server Web Bowser
A web server is a computer or a group of A web browser is an application
computers that hosts or stores content of used to access and view websites.
website. Common web browsers include
It processes and delivers web pages of the Microsoft Internet Explores,
websites to the users. Google Chrome etc.
The main job of a web server is to display the
website content
7. Neeta is a bit confused between the terms Website and Web hosting. Help her in
understanding both the terms with the help of suitable example.
Ans:
Website Web Hosting
A collection of webpages which Web hosting is the process of uploading/saving the
are grouped together and web content on a web server to make it available
usually connected together in on WWW (World Wide Web).
various ways is called a In case an individual or a company wants to make
website. It is a group of web its website available on the internet, it should be
pages, containing text, images hosted on a web server.
and all types of multimedia
files.
8. Yamini has her own business of Garments but she is unaware about Internet.
Give any two application of Internet that could be beneficial for her business.
Ans: (i) Exchanging and communicating among friends and other people.
(iii) Publish information world wide.
9. Virat wants to develop a website. He has to acquire information on webhosting
and various services provided in webhosting. Help him to understand about web
hosting and its functions.
Ans: Web hosting is the process of uploading/saving the web content on a web server to
make it available on WWW (World Wide Web).
In case an individual or a company wants to make its website available on the internet,
it should be hosted on a web server.
54
10. Raman wants to develop a website for his garments business. He has to acquire
information on website and various components of a website. Help him to understand
about website and its components.
Ans: Website is a group of web pages, containing text, images and all types of multi-
media files.
Components of Website are:
Web host, URL, Home page, Design, Web page with content, Navigation Structure.
11. Kiran needs a network device that should regenerate the signal over the same
network before signal becomes weak or corrupted. Arun needs a network device to
connect two different networks together that work upon different networking models
so that the two networks can communicate properly. Name the devices that should be
used by Kiran and Arun.
Ans: Gateway
12. Priyanka is a web developer but is a bit confused between Add-ons and Plug-ins
that are used by web browser. Help her to understand the above two terms along with
method to install them.
Ans:
Add-ons Plug-ins
It is either a hardware unit that is added It is a software component that adds a
to a computer to increase the capabitilies specific feature to an existing computer
or a program unit that enhances primary program. When a program supports
program. plug-ins, it enables customization. They
Examples include card for sound, graphic are commonly used in internet
acceleration, modem capability. Software browsers but also can be utilized in
add-ons are common games, word- numerous other types of applications.
processing and accounting program.
17. Rehan wants to edit some privacy settings of her browser. How can she
accomplish her task ?
Ans: She can accomplish her task by performing following steps:
➢ Open your web browser.
➢ Open browser settings.
➢ Look for privacy and security settings. If not directly found, click on advance
settings.
After reaching Privacy and security settings she can edit their settings.
(iii) Voice over Internet Protocol (iv) Hyper Text Transfer Protocol secure
Mrkt Dept
MrktDept
MrktDept to FunDept 80 m
MrktDept to LegalDept 180 m
MrktDept to SalesDept 100 m
LegalDept to SalesDept 150 m
LegalDept to FunDept 100 m
FunDept to SalesDept 50 m
Number of computers in the buildings:
MrktDept 20
LegalDept 10
FunDept 08
SalesDept 42
(i) Suggest the network type between the Departments and specify
topology.
(ii) Suggest the most suitable building to place the server with a suitable
reason.
(iii) Suggest the placement of Hub/Switch in the network.
57
(iv) The organization is planning to link its sale counters situated in various
parts of the same city. Which type of network out of LAN, WAN, MAN
will be formed? Justify.
(v) Suggest the Economical way for reasonable high speed Internet
connectivity.
Answer :
(i) Star topology layout
(ii) SalesDept , Maximum no. of computer are installed there.
(iii) Each block
(iv) MAN, due to all the offices are situated in same city.
(v) Broadband
Q. 2:
Star Info Solution is a professional consultancy company. The company is planning to
set up their new offices in India with its hub at Jaipur. As a network adviser, you have to
understand their requirement and suggest them the best available solutions. Their
queries are mentioned as (i) to (iv) below.
Physical Locations of the blocked of Company
(i) What will be the most appropriate block, where company should plan to install
their server?
(ii) Draw a block to cable layout to connect all the buildings in the most appropriate
manner for efficient communication.
(iii) What will be the best possible connectivity out of the following, you will suggest to
connect the new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
(iv) Which of the following device will be suggested by you to connect each computer
in each of the buildings:
o Switch
o Modem
o Gateway
(v) Which protocol will be used to transfer files over this network?
58
Answer :
(ii)
(iii) Satellite link
(iv) Switch
(v) FTP
Q. 3:
1. Hello IT Solution is an online, corporate training provider company for IT related
courses. The company is setting up their new campus in Mumbai. You as a
network expert have to study the physical locations of various buildings and the
number of computers to be installed. In the planning phase, provide the best
possible answer for the following questions (i) to (v):
59
(iii) Which type of network out of the following is formed by connecting the computers
of these three buildings?
o LAN
o MAN
o WAN
(iv) Which wireless channel out of the following should be opted by the company to
connect to students of all over the world?
o Infrared
o Microwave
o Satellite
(v) Suggest the device to be used to connect all the computers together in each
building.
Answer :
(i) Faculty Studio Building
(ii) Bus Topology
(iii) LAN
(iv) Satellite
(v) Switch/Hub in each building
Q. 4:
Smart Solution is a skill development organisation which has an aim to promote the
standard of skills in the society. It is planning to set up its training centers in multiple
towns and villages Pan India with its head offices in the nearest cities. They have
created a model of their network with a city ABC Nagar, a town (UVW town) and 3
villages.
As a network consultant, you have to suggest the best network related solutions for
their issues/ problems raised in (i) to (iv), keeping in mind the distances between
various locations and other given parameters.
Note:
– In Villagers, there are community centers, in which one room has been given as
training center to this organization to install computers.
– The organization has got financial support from the government and top Multinational
Organizations.
(i) Suggest the most appropriate location of the SERVER in the Cluster (out of the 4
locations), to get the best and effective connectivity. Justify your answer.
(ii) Suggest the best wired medium and draw the cable layout (location to location) to
efficiently connect various locations within the Cluster.
60
(iii) Which hardware device will you suggest to connect all the computers within each
location.
(iv) Which service/protocol will be most helpful to conduct live interactions of
Experts from Head Office and people at all locations of Cluster?
(v) Suggest a system (hardware/software) to prevent unauthorized access to or
from the network.
Answer :
(i) Best location for the server is UVW-TOWN, because it is approximately
equidistant from the village P, Q and R.
(ii) For connectivity between UVW-TOWN to head office is optic Fiber and to connect
the villages, P, Q and R with server at UVW- TOWN is co-axial cable.
(iii) The villages R Q and R can be connected with server at UVW-TOWN by a Hub and
the head office is connected by a Bus topology.
(iv) Between head office and UVWTOWN
we recommend for Bus topology, so HTTP protocol and other terminal can be
connected by UDP or FTP protocols.
(v) Firewall
Q. 5:
Alka Institute is planning to set up its center in Bikaner with four specialized blocks for
Medicine, Management, Law courses along with an Admission block in separate buildings.
The physical distances between these blocks and the number of computers to be installed
in these blocks are given below. You as a network expert have to answer the queries
raised by their board of directors as given in (i) to (iv).
(i). Suggest the most suitable location to install the main server of this institution to get
efficient connectivity.
(ii). Suggest by drawing the best cable layout for effective network connectivity of the
61
blocks having server with all the other blocks.
(iii). Suggest the devices to be installed in each of these buildings for connecting
computers installed within the building out of the following:
• Modem
• Switch
• Gateway
• Router
(iv) Suggest the most suitable wired medium for efficiently connecting each computer
installed in every building out of the following network cables:
• Coaxial Cable
• Ethernet Cable
• Single Pair
• Telephone Cable.
Answer:
i) Admin Block
(ii)
Q. 6:Adarsh School in Delhi is setting up the network between its different wings.
There are 4 wings named as SENIOR(S), MIDDLE(M), JUNIOR(J) and OFFICE(O).
(i) Suggest a suitable Topology for networking the computer of all wings.
(ii) Name the wing where the server to be installed. Justify your answer.
(iii) Suggest the placement of Hub/Switch in the network.
(iv) Where do you install repeater?
(v) Mention an economic technology to provide internet accessibility to all wings
Answer : (i) Star or Bus or any other valid topology.
(ii) Wing S, because maximum number of computers are located at Wing S.
(iii) Hub/ Switch in all the wings.
(iv) Coaxial cable/Modem/LAN/TCP-IP/Dialup/DSL/Leased Lines or any other
valid technology.
(v) Between those Wings whose distance more than 100m.
62
Q. 7: Soft Foundation Ltd. is a Mumbai based organization which is expanding its office set-up to
Chennai. At Chennai office compound, they are planning to have 3 different blocks for
Admin, Training and Accounts related activities. Each block has a number of computers,
which are required to be connected in a
network for communication, data and
resource sharing.
As a network consultant, you have to
suggest the best network related
solutions for them for
issues/problems raised by them in 1
to 5, as per the distances between
various blocks/locations and other
given parameters.
1. Suggest the most appropriate
block/location to house the SERVER in
the CHENNAI office (out of the 3
blocks) to get the best and effective
connectivity. Justify your answer.
3. Suggest a device/software and its placement that would provide data security for
the entire network of the CHENNAI office.
4. Suggest a device and the protocol that shall be needed to provide wireless Internet
access to all Smartphone/laptop users in the CHENNAI office.
5. Device required connecting computers together in each block.
Answer :
3. Firewall
4. Device: Wi-Fi Card and protocol: TCP/IP
5. Hub /Switch In each block
Q. 8: DM Center has set up its new center in Kolkata. It has four buildings as shown in the
diagram given below: Distance between various buildings
Accounts to research Lab 55m
Accounts to store 150m
Store to packaging unit 160m
Packaging unit to research lab 60m
Accounts to packaging unit 125m
63
Store to research lab 180m
Number of Computers
Accounts 25
Research Lab 100
Store 15
Packaging Unit 60
As a network expert, provide the best possible answer for the following queries:
i) Suggest a cable layout of connections between the buildings.
ii) Suggest the most suitable place (i.e. buildings) to house the server of this
organization.
iii) Suggest the placement of the following device with justification: Repeater
iv) Suggest the placement of the following device with justification: Hub/Switch
v) Suggest a system (hardware/software) to prevent unauthorized access to or
from the network.
(ii) The most suitable place/ building to house the server of this
organization would be building Research Lab, as this building
contains the maximum number of computers
(iii) For layout1, since the cabling distance between Accounts to Store
is quite large, so a repeater would ideally be needed along their
path to avoid loss of signals during the course of data flow in this
route. For layout2, since the cabling distance between Stores to
Research Lab is quite large, so a repeater would ideally be placed.
(iv) In both the layouts, a Hub/Switch each would be needed in all the
buildings to interconnect the group of cables from the different
computers in each building.
(v) Firewall
64
Q. 9:
Professional Training Institute is planning to set up its centre in Amritsar with four
specialized blocks for Medicine, Management, Law courses along with an Admission
block in separate buildings. The physical distances between these blocks and the number
of computers to be installed in these blocks are given below. You as a network expert
have to answer the queries as raised by their board of directors as given in (i) to (v).
Shortest distances between various locations in metres:
(i) Suggest the most suitable location to install the main server
of this institution to get efficient connectivity.
➢ Co-axial Cable
➢ Ethernet Cable
➢ Single Pair Telephone Cable
(v) Suggest the Economical way for reasonable high speed Internet
connectivity.
Answer :
(i) Admin Block
(ii) Switch
(iii)
SENIOR JUNIOR
HOSTEL ADMIN
66
(iv) Suggest the placement of the following devices with justification.
o Repeater
o Hub/Switch
(v) The organisation also has inquiry office in another city about 50-60 km away in hilly
region. Suggest the suitable transmission media to interconnect to school and
inquiry office out of the following :
o Fiber optic cable
o Microwave
o Radio wave
Answer :
(i)
(ii) Server can be placed in the ADMIN building as it has the maximum number of
computer.
(iii) Firewall.
(iv) Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
(v) Radio waves can be used in hilly regions as they can travel through obstacles.
67
DATABASE MANAGEMENT
INTRODUCTION OF DATABASE CONCEPTS AND IT’S NEED
Database is a collection of interrelated data stored together to serve multiple
applications.
DBMS: DBMS(Data Base Management System) refers to a software that is responsible for
storing, maintaining and utilizing database.
Examples of database management systems are: MS-Access, MySQL, PostgreSQL, SQLite,
Microsoft SQL Server, Oracle, SAP, DBASE, FoxPro, etc.
Advantage of Database System :-
i. Database reduces redundancy(duplicacy of data)
ii. Database controlled data inconsistency
iii. Sharing of data
iv. Integrated data
v. Database provide security
vi. Standardized data
RELATIONAL DATA MODEL:- In the relational data model, the data is stored/organized
into tables. These tables are called relation. Database is represented as collection of
related tables. Each table is termed as relation and has its unique name in the relational
data model. A Table is a collection of rows and columns. A row (horizontal subset) of a
table represents a tuple or record, while column (vertical subset) of a table represents an
attribute.
TERMINOLOGIES OF RDBMS:
RELATION: A relation means a 'table', in which data are organized/consist in the form of
rows and columns. Therefore, in database, relations are also known as tables. For
example
RELATION/TABLE: STUDENT
TABLE: TEACHER ADMNO NAME GENDER CLASS SECTION MARKS
101 ANU F 12 A 85
TID TNAME 105 BALU M 12 D 65
101 SUMAN 203 REENA F 11 B 92
203 SUMIT 205 MADHU F 10 B 75
305 MANOJ M 9 C 70
DOMAIN: A domain is a set of values of a particular data type that are allowed to be used
in a column of a database table.
For example:
i)The domain of gender column has a set of two possible values i.e, Male or Female.
ii) The domain of section column has a set of four possible values i.e A, B, C, D.
TUPLE/RECORD/ROW: Horizontal subset/information in a table is called tuple. The
tuple is also known as a 'record', which gives particular information of the relation
(table). For example: In Student table, one row gives information about one student only.
ATTRIBUTE/COLUMN: Vertical subset of a table is called attribute/column/field. For
example: In Student Table ADMNO, NAME, GENDER, CLASS, SECTION, MARKS are the
columns.
DEGREE OF TABLE/RELATION: Total number of attributes/column/fields is known as
Degree of relation. For example: In above Student table/relation degree=6
CARDINALITY OF TABLE/RELATION: Total number of rows/records/tuples in a table
is known as Cardinality of a table. For example: In above Student table/ relation
cardinality=5
NOTE: if more than one tables are given and performed Cartesian product then resultant
68
table degree= Total no. of column table1 + Total no. of column table2 and
cardinality = Total no. of rows of table1 * Total no. of rows of table2
KEYS: it is important/key part of the structure of a table. It helps enforce integrity and
help identify the relationship or links between tables.
Primary Key: A column or set of columns that uniquely identifies a row within a table is
called primary key. Possible candidate keys of student table are AdmNo, Name and Marks
serve the best primary key is AdmNo. Only one primary key possible in one relation.
Candidate Key: Candidate keys are set of fields (columns with unique values) in the
relation that are eligible to act as a primary key.
In the above table student, AdmNo and Name, Marks has unique values. Therefore,
AdmNo, Name and Marks are candidate keys.
Alternate/Alter Key: Out of the candidate keys, after selecting a key as primary key, the
remaining keys are called alternate/ alter keys. Possible candidate keys of student table
are AdmNo, Name and Marks. Here the best primary key is AdmNo and the remaining
attributes of candidate keys become the alternate keys which are Name and Marks.
Foreign Key: A foreign key is a field (or collection of fields) in one table that uniquely
identifies a row of another table. In other words, a foreign key is a column or a
combination of columns that is used to establish a link between two tables. Foreign key
is referenced from the Primary Key column of Master/Base/Parent table and the table in
which the foreign key is referenced is called as Detailed/ Derived/ Child Table.
Structured Query Language (SQL) : SQL is a standardized programming language that
is used to manage relational databases and perform various operations on the data in
those tables. SQL provides statements for defining the structure of the data, manipulating
data in the database, declaring constraints and retrieving data from the database in
various ways, depending on our requirements. SQL is not a case sensitive language.
Types of SQL commands:- SQL commands are classified as:
(i) Data definition language (DDL) and (ii) Data manipulation language (DML)
DATA DEFINITION LANGUAGE(DDL)- SQL allows us to write statements for defining,
modifying and deleting relation schemas/ physical structure of table. DDL commands are
CREATE, ALTER, DROP etc.
DATA MANIPULATION LANGUAGE- This allows us to write SQL statements for adding,
updating and deleting the data (values) from the table. DML commands are INSERT, UPDATE,
DELETE etc.
Datatypes in SQL:- Commonly used to identifying the values given by user. Data types in
MySQL are numeric types, date and time and string types.
Data type Description
CHAR(n) Specifies character type data of length n where n could be any value from 0 to 255.
CHAR is of fixed length means declaring CHAR (10) implies to reserve spaces for 10
characters. If data not have 10 characters (e.g., ‘city’ has four characters), MySQL
fills the remaining 6 characters with blank spaces padded on the right.
VARCHAR(n) Specifies character type data of length where n could be any value from 0 to 65535.
But unlike CHAR, VARCHAR(n) is a variable-length data type. That is, declaring
VARCHAR (30) means a maximum of 30 characters can be stored but the actual
allocated bytes will depend on the length of entered string. So ‘city’ in VARCHAR (30)
will occupy space needed to store 4 characters only.
69
INT INT specifies an integer value. Each INT value occupies 4 bytes of storage. The range
of unsigned values allowed in a 4 byte integer type are 0 to 4,294,967,295. For values
larger than that, we have to use BIGINT, which occupies 8 bytes.
FLOAT Holds numbers with decimal points. Each FLOAT value occupies 4 bytes.
DATE The DATE type is used for dates in 'YYYY-MM-DD' format. YYYY is the 4 digit year,
MM is the 2 digit month and DD is the 2 digit day. The supported range
is '1000-01-01' to '9999-12-31'.
Constraint: - These are the certain types of restrictions on the data values that an attribute can
have. If we apply constraints on single attribute, it is known as column constraint and if we apply
on more than one attribute than known as table constraint.
Commonly used SQL Constraints: -
Constraint Description
NOT NULL Ensures that a column cannot have NULL values where NULL means
empty/missing/ unknown/not applicable value.
UNIQUE Ensures that all the values in a column are distinct/unique.
PRIMARY KEY The column which can uniquely identify each row/record in a table.
SQL Commands:-
SHOW DATABASES:- This command used to display list of all databases. By default, it
shows three databases- information_schema, mysql, test.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
+--------------------+
3 rows in set (0.00 sec)
CREATE DATABASE: - This command used to create new database.
Standard Syntax: - CREATE DATABASE <NAME OF DATABASE>;
CREATE DATABASE SCHOOL;
We created new database SCHOOL. if we want to see it then use
SHOW DATABASES;
USE DATABASE: - This command is used to select a database on which we want to work.
USE SCHOOL;
DROP DATABASE:- This command used to permanently remove the particular database.
Standard Syntax: - DROP DATBASE <NAME OF DATABASE>;
DROP DATABASE SCHOOL;
This command removes the school database permanently.
SHOW TABLES:- This command we used to display the list of all the tables under a
particular database.
Standard Syntax: SHOW TABLES;
CREATE TABLE:- This command used to create new table under a particular database
like school.
USE SCHOOL;
Standard Syntax: CREATE TABLE <tablename>
( attributename1 datatype constraint,
attributename2 datatype constraint,
attributenameN datatype constraint);
70
CREATE TABLE EMP # Creating New Table/Relation as emp
(empid int not null primary key, #attribute-empid,datatype int, constraint -not null &
primary key
ename varchar(30), # attribute -ename, datatype-varchar and size-30
doj date,
dept varchar(32) unique,
salary float(8,2)
);
When we create table, we can also find degree of table/relation- To count number of
attributes/columns. In above Relation of emp Degree=5.
DESCRIBE TABLE NAME- This is used to check/show physical structure of table and data
types, constraints which we created. It also help us when we add rows in table.
NOTE:- When we add rows we assign values according to given data type and constraints.
Standard Syntax: DESCIBE TABLE NAME;
DESCRIBE EMP;
Structure of EMP table.
+-----------------+------------------------+--------+------------------
| Field | Type | Null | Key |
+-----------------+------------------------+-------- +------------------
| empid | int(11) | NO | PRI |
| ename | varchar(30) | YES | |
| doj | date | YES | |
| dept | varchar(32) | YES | |
| salary | float(8,2) | YES | |
+----------------+--------------------------+-------+----------------+
Changing Structure of table: -
ALTER TABLE :- When we define the system, we specify what data we need to store, the
size and data type of that data. What can we do when the requirements change? We can
alter the table to accommodate the changed requirements.
Alter table command is used to change definition of existing tables.
ALTER TABLE is used to- (i) To add a new column (ii) To add an integrity constraints
(iii) To redefine a column (data type, size, default value).
ADD clause: Syntax to add new column to a table-
ALTER TABLE <TABLE_NAME>
ADD <COLUMN_NAME> < DATA TYPE> ( <SIZE> ) <CONSTRAINT NAME>;
e.g. - ALTER TABLE EMP ADD MOBNO INT(12); (# here table name is EMP)
Modify clause-If we want to make changes in data type and its size.
ALTER TABLE EMP MODIFY DEPT CHAR(30);
We can change data type from varchar to char and its size also.
Drop clause: If we want to remove the attribute of a table. Then we may use the DROP
clause of ALTER TABLE.
ALTER TABLE EMP DROP DEPT;
Here we removed dept column from the emp table.
Note: Similarly we can also add/remove the constraints using ADD and DROP clause.
ALTER TABLE EMP ADD PRIMARY KEY (NAME OF ATTRIBUTE);
ALTER TABLE EMP ADD PRIMARY KEY ENAME;
(here we added primary key constraint on ename column.)
ALTER TABLE EMP DROP PRIMARY KEY;
(here we removed primary key from table emp.)
DROP TABLE Command:-If we want to remove the table from the database
permanently. Standard syntax: DROP TABLE <TABLE_NAME>;
71
DROP TABLE EMP;
INSERT INTO Command: This command used to add new row in relation/table.
Standard Syntax: INSERT INTO TABLE _NAME VALUES(according to data types);
# to add single row
We can also add one row or a particular values in row:
INSERT INTO TABLE_NAME (Attributes name1, name2, name3) VALUES (According to
data type);
We can add multiple rows also by using-
INSERT INTO TABLE_NAME VALUES(according to data types),
(According to data type another row);
INSERT INTO EMP VALUES(1,’RAVI’,’2008-10-4’,’MATHS’,50000);
Except numeric data type values must be in form of string.
INSERT INTO EMP VALUES(1,’RAVI’,’2008-10-4’,’MATHS’, 50000),
(2,’SWETA’,’2012-12-6’,’HINDI’,40000); #adding multiple rows.
SELECT Command:- The SELECT statement is used to select data from a database. This
command is used to view/retrieved table information from SQL database.
SELECT column1, column2,...FROM table_name;
Here, column1, column2, ... are the field_names of the table we want to select data from.
If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
The SQL WHERE Clause:
The WHERE clause is used to filter records. It is used to extract only those records that
fulfill a specified condition.
Syntax:-
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:Display all the details of employee whose department science.
SELECT * FROM EMP
WHERE DEPT=’SCIENCE’;
Arithmetic operators: Arithmetic operator takes two operands and performs a
mathematical calculation on them. However, they can be used only in SELECT command.
The arithmetic operators used in SQL are: + Addition, - Subtraction, *Multiplication,
/ Division.
SELECT 2+ 5 FROM EMP;
RELATIONAL OPERATORS:- These are used to implement comparison between two
operands. These operators can be used only in 'where clause'. Relational operators are - <
less than, > greater than, <= less than or equal to, >= greater than equal to, = equal to, !=
not equal to.
Example- Display all the details of employee whose salary greater than or equal to 3000
and less than 60000.
SELECT * FROM EMP WHERE SALARY>=30000 AND SALARY< 60000;
LOGICAL OPERATORS:- These are also possible only in 'where clause' and are used to
merge more than one condition. Logical operators are - and, or, not.
Example - Display details of all employee whose employee id is 2 or 3.
SELECT * FROM EMP WHERE EMPID=2 OR EMPID=3;
RENAMING OF COLUMNS (ALIASING using AS):- When we want to change name of
72
column for Displaying output AS clause should be use. Example- Display ename as name
of employee. SELECT ENAME AS NAME FROM EMP;
DISTINCT CLAUSE:- This clause used with SELECT to display different data of particular
attribute (remove the repetition of data/removed the duplication of data).
Example - SELECT DISTINCT(DEPT) FROM EMP; it will display different department of
table employee.
WHERE CLAUSE: The WHERE clause is used to filter records. It is used to extract only
those records that fulfil a specified condition.
Example- Display all the details of those employee whose employee_id is 1 and 2.
SELECT * FROM EMP WHERE EMPID=1 OR EMPID=2;
IN OPERATOR:- The IN operator allows us to specify multiple values in a WHERE clause.
We also say work like or operator from logical operators.
Example-Display all the details of employee whose department as hindi, maths or science.
SELECT * FROM EMP WHERE DEPT IN(‘HINDI’,’MATHS’,’SCIENCE’);
SELECT * FROM EMP WHERE DEPT=‘HINDI’ OR DEPT=’MATHS’ OR DEPT=’SCIENCE’;
BETWEEN CLAUSE:- The BETWEEN operator selects values within a given range. The
values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Example-Display employee_name and salary of those employee whose salary 30000 to
40000.
SELECT ENAME, SALARY FROM EMP WHERE SALARY BETWEEN 30000 AND 40000;
OR
SELECT ENAME SALARY FROM EMP WHERE SALARY>=30000 AND SALARY<=40000;
ORDER BY: The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
Example- Display all the details of employee in ascending order of department.
SELECT * FROM EMP ORDER BY DEPT;
NULL VALUE:- SQL supports a special value called NULL to represent a missing or
unknown value. NULL is used to represent such unknown values. It is important to note
that NULL is different from 0 (zero). Also, any arithmetic operation performed with NULL
value gives NULL.
IS NULL:- In order to check for NULL value in a column, we use IS NULL operator.
SELECT * FROM EMP WHERE DOJ IS NULL;
It displays only those tuples which have DOJ as NULL.
IS NOT NULL:- In order to check for not NULL value in a column, we use IS NOT NULL
operator.
SELECT * FROM EMP WHERE DOJ IS NOT NULL;
It displays only those tuples which does not have DOJ as NULL.
LIKE CLAUSE:- SQL provides a LIKE operator that can be used with the WHERE clause
to search for a specified pattern in a column.
The LIKE operator makes use of the following two wildcard characters:
➢ % (per cent)- used to represent zero, one, or multiple characters (% -means
anything)
➢ _ (underscore) - used to represent exactly a single character.
Display details of all those employees whose name starts with 'R'.
SELECT * FROM EMP WHERE ENAME LIKE ‘R%’;
Display details of all those employees whose name have second letter as 'A'.
SELECT * FROM EMP WHERE ENAME LIKE ‘_A%’;
73
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
WHERE CustomerName LIKE 'a%' Finds any values that start with "a"
WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any
position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at
least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
with "o"
74
specified column.
SUM(column) Returns the sum of the mysql> SELECT SUM(Price)
values for the specified FROM INVENTORY;
column.
COUNT(*) Returns the number of mysql> SELECT COUNT(*)
records in a table. Note: from PRODUCT;
In order to display the
number of records that
matches a particular
criteria in the table, we
have to use COUNT(*)
with WHERE clause.
COUNT(column) Returns the number of SELECT COUNT(MEMNAME)
values in the specified FROM PRODUCT;
column ignoring the
NULL values.
GROUP BY CLAUSE:- The GROUP BY statement groups rows that have the same values
into summary rows, like "find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.
EXAMPLE- SELECT COUNT(*) SALARY FROM EMP GROUP BY DEPT;
It display result with count salary each group of department.
HAVING CLAUSE:- As mentioned earlier, the 'where' clause is used only to place condition
on the selected columns, whereas the 'HAVING' clause is used to place condition on groups
created by 'group by' clause, because here the 'WHERE' clause is not useable.
EXAMPLE-Display to count dept of those employee according to department, whose
department is more than one.
SELECT COUNT(*) SALARY FROM EMP
GROUP BY DEPT HAVING COUNT(*) >1;
JOINS:- JOIN operation combines tuples from two tables on specified conditions.
CARTESIAN PRODUCT OF TWO TABLES: This is applied on two tables results in a
table having all combinations of tuples from the underlying tables. When more than
one table is to be used in a query, then we must specify the table names by separating
commas in the FROM clause,
SELECT * FROM TEACHER, STU;
It will display all combinations of tuples from both tables.
EQUI JOIN:- Equi Joins are used to give information in different tables. It is a special type
of join in which we use only equality operator.
SELECT * FROM TEACHER, STU WHERE TEACHER.TID=STU.ADM;
It display all tuples whose id matches.
NATURAL JOIN:- This operator can be used to join the contents of two tables if there is
one common attribute in both the tables. The common column will display only once
and display the tuples according to common attributes.
SELECT * FROM TEACHER NATURAL JOIN STU;
75
INTERFACE OF PYTHON WITH AN SQL DATABASE:
We need input from the user using python Interface that is known as Front End (Basic
application programming is there, which provides the Graphical User Interface(GUI) for
input values from user) and we want to save data permanently on hard disk for
modification, deletion and retrieval. These data directly not accessible to the user so that
we make the connection python with MySql (database) that is known as Back End
Database.
Steps to connecting python with MySql are:
(i)To check in computer/Laptop that python and MySql softwares are installed or not, if
not installed then First Installed those.
(ii)Upgrade the version pip using: Path of python\python.exe -m pip install --upgrade pip
on command prompt.
Example: C:\Users\HP>AppData\Local\Programs\Python\Python310\python.exe -m
pip install --upgrade pip
(iii) Install the driver of MySQL using: Path up to Script\pip install mysql.connector
Example:C:\Users\HP>AppData\Local\Programs\Python\Python310\Scripts\pip
install mysql.connector and check on python import mysl.connector driver installed or
not.
(iv) To find user and host we use:
select current_user(); #It gives user and local host names.
(iv) To establish the connection, write program on scripting mode:
import mysql.connector #To check driver of MySQL installed or not
mydb=mysql.connector.connect(host='localhost',user='root',passwd='tiger')
# connect() statement create a connection to the MySQL server and returns a MySQL
connection object mydb and pass three parameters if required than also pass database
parameter.
print(mydb) #It displays the message of mydb object connection established or not
<mysql.connector.connection.MySQLConnection object at 0x0000017590025000>
(v) Creating cursor object of a class cursor which allows python code to execute database.
Mycursor=mydb.cursor()
(vi) Mycursor.execute(“Write query of MySQL”) #To execute SQL queries from python.
(vii) To save the current transactions of inserting, updating and deleting data we use:
mydb.commit()
(viii) To read the data(rows) using fetchone()/ fetchmany(2)/ fetchall() methods as per
our requirement and returned result in form of list or we can also use for loop to
retrieving all rows with fetch or without fetch result in form of tuple and one by one
record.
Note: fetchone() method give only one record at a time and we cannot pass parameter.
fetchmany(size) will pass one parameter and display records according to pass
76
parameter
fetchall() will display all the records and can not pass parameters.
(ix) rowcount: This is a read only attributes and returns the number of rows that were
affected by an execute method. Syntax: object of cursor.rowcount.
INSERT RECORD:-
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='tiger',database=
'school')
mycursor=mydb.cursor()
mycursor.execute("INSERT INTO EMP VALUES(%s,%s,%s,%s,%s)",(7,'MANISH',
'2009-01-12','ENGLISH',45000))
mydb.commit()
print(mycursor.rowcount, "record inserted/added")
UPDATE RECORD:
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='tiger',database=
'school')
mycursor=mydb.cursor()
mycursor.execute("UPDATE EMP SET SALARY=35000 WHERE EMPID=1")
mydb.commit()
print(mycursor.rowcount,"record updated")
DELETE RECORD:
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='tiger',database=
'school')
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM EMP WHERE EMPID=4")
mydb.commit()
print(mycursor.rowcount,"record deleted")
TO DISPLAY ALL RECORDS:
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='tiger',database=
'school')
mycursor=mydb.cursor()
mycursor.execute("SELECT * FROM EMP")
myrec=mycursor.fetchall()
print(myrec) # It will display all records in form of list
for i in myrec: #it will display all records in form of tuple and record by record.
print(i)
print(mycursor.rowcount)# To count total no of records fetched by execute method.
77
QUESTIONS-1 MARKS(MYSQL)
1. A relation can have only one ________ key and may have more than one _______ keys.
a) Primary, Candidate b) Candidate, Alternate
c) Candidate, Primary d) Alternate, Candidate
2. The vertical subset of a table is known as:
a) Tuple b) Row c) Attribute d) Relation
3. If software is released under open source, it means:
a) It is expensive. b) Its source code is available to the user.
c) It belongs to a company. d) It is a DBMS.
4. Which of the following columns in a Student table can be used as the primary key?
a) Class b) Section c) First_Name d) Admission_No
5. A tuple is also known as a ___________________________ .
a) table b) relation c) row d) field
6. An attribute is also known as a_________________________.
a) table b) relation c) row d) column
7. A field or a combination of fields in a table that has a unique value for each row is called:
a) Candidate key. b) Foreign key. c) Main key. d) Alternate key.
8. Number of rows in a table is called
a) Power b) Degree c) Cardinality d) Design
9. Number of columns in a table is called
a) Power b) Degree c) Cardinality d) Design
10. Which key provide link between two tables
a) Candidate key. b) Foreign key. c) Main key. d) Alternate key.
Answers:-
Q1 Q2 Q3 Q4 Q5
A C B D C
Q6 Q7 Q8 Q9 Q10
D A C B B
QUESTIONS-1 MARKS(MYSQL)
Q1. Which statement is used to retrieve data from a table?
A. SELECT B. DISPLAY C. READ D. EXTRACT
Q2. How do you select all the columns from a table named "Employee"?
A. SELECT [all] FROM Employee; B. SELECT Employee;
C. SELECT * BY Employee; D. SELECT * FROM Employee ;
Q3. How do you select a column named "Name" from a table named "Inventory"?
A. SELECT Inventory FROM name; B. DISPLAY name FROM Inventory;
C. SELECT name FROM Inventory; D. SELECT Name, Inventory FROM name;
Q4. Which of the following are invalid column names?
A. Marks_ Eng B. 66_Marks C. MarksEng D. _Eng_Marks
Q5. SELECT statement can be used to perform these functions.
A. Insert rows into a table. B. Choose and display columns from a table.
C. Modify data in a table. D. Select and display structure of a table.
Q6. Which statement is used to add new tuple in a table?
A. ADD RECORD B. INSERT RECORD C. INSERT INTO D. INSERT ROW
Q7. How would you display all those rows from a table named "Trends" where value of
78
the column "Hobbies" is "marketing" ?
A. SELECT ALL FROM Friends WHERE Hobbies IS 'marketing';
B. SELECT * FROM Friends WHERE Hobbies='marketing';
C. SELECT * FROM Friends WHERE Hobbies = 'marketing" ;
D. SELECT ALL FROM Friends WHERE Hobbies 'marketing' ;
Q8. Which statement is used to modify data in a table?
A. CHANGE B. MODIFY C. UPDATE D. SAVE AS
Q9. Which SQL statement is used to delete data from a table?
A. DELETE B. DROP C. TRUNCATE D. REMOVE
Q10. How do you select all the rows from a table named "Student" where the value of the
column "FName" starts with "S"?
A. SELECT * FROM Student WHERE FName LIKE 'S_' ;
B. SELECT * FROM Student WHERE FName='S';
C. SELECT * FROM Student WHERE FName LIKE 'S%' ;
D. SELECT * WHERE Student WHERE FName='%S%' ;
Q11. Which keyword is used to return only different values in a column?
A. DIFFERENT B. EXCLUSIVE C. DISTINCT D. UNIQUE
Q12. Which SQL keyword(s) is/are used to sort the rows in the output:
A. SORTED ORDER B. SORT C. SORT BY D. ORDER BY
Q13. How would you return all the rows from a table named "Item" sorted in descending
order on the column "IName"?
A. SELECT * FROM Item SORT 'IName' DESC;
B. SELECT * FROM Item ORDER BY IName DESC ;
C. SELECT * FROM Item ORDER IName DESC ;
D. SELECT * FROM Item SORT BY 'IName' DESC;
Q14. How can you insert a new row into the "Store" table?
A. INSERT (1,'Abc Rice') INTO Store; B. INSERT VALUES (1,'Abc Rice') INTO Store ;
C. NSERT INTO Store VALUES(1,'Abc Rice'); D. ADD ROW Store values(1,'Abc Rice');
Q15. Which statement is appropriate to change the first name "Madhur" to "Mridul" in
the "FName" column in the 'Student' table?
A. UPDATE Student SET FName='Mridul' WHERE FName='Madhur' ;
B. MODIFY Student SET FName='Madhur' INTO FName='Mridul ;
C. UPDATE Student SET FName='Madhur' INTO FName='Mridul' ;
D. UPDATE Student SET FName='Madhur' WHERE FName='Mridul' ;
Q16. How do you delete the rows with marks below 33 in the 'Student' Table?
A. DELETE FROM Student WHERE marks <=33; B. DELETE marks < 33 FROM Student ;
C. DELETE ROW marks <33; D. DELETE FROM Student WHERE marks<33;
Q17. The OR operator displays a record if ANY of the conditions listed are true. The AND
operator displays a record if ALL of the conditions listed are true:
A. False B. True C. 0 D. None of These
Q18. SUM, AVG, COUNT are examples of ____________________functions.
(a) Date (b) String (c) Multiple Row (d) Single Row
Q19. MySQL is a /an
A. Relational Database B. Database C. RDBMS D. Table
Q20. USE <database name >command:
79
A. is not used in MySQL B. is given before quitting MySQL
C. opens a table D. opens a database
Q21. A database:
A. Contains tables B. Is a part of a table
C. Is same as a table D. Removes data from a table
Q22. ORDER BY clause is used to sort data
A. in ascending order B. in descending order
C. both (a) and (b) D. None of the above
Q23. Wild card characters are used
A. In LIKE clause B. In ORDER BY clause
C. In BETWEEN clause D. In IN clause
Q24. DDL is
A. a part of SQL B. a part of DML C. a part of DCL D. None of these
Q25. LIKE clause is used
A. For pattern matching B. For table matching
C. For inserting similar data in a table D. For deleting data from a table
Q26. Which of the following will give the same answer irrespective of the NULL values in
the specified column:
A. MIN() B. MAX() C. SUM() D. None of the above
Q27. An aggregate function:
A. Takes a column name as its arguments B. May take an expression as its argument
C. Both (a) and (b) D. None of (a) and (b)
Q28. In the FROM clause of a SELECT statement
A. Multiple Column Names are specified. B. Multiple table names are specified.
C. Multiple Column Names may be specified. D. Multiple table names may be specified.
Q29. JOIN in RDBMS refers to
A. Combination of multiple columns B. Combination of multiple rows
C. Combination of multiple tables D. Combination of multiple databases
Q30. Equi-join is formed by equating
A. Foreign key with Primary key B. Each row with all other rows
C. Primary key with Primary key D. Two tables
Q31. Referential integrity
A. Must be maintained B. Cannot be maintained
C. Is automatically maintained by databases D. Should not be maintained
Q32. A Primary key column
A. Can have NULL values B. Can have duplicate values
C. Both (a) and (b) D. Neither (a) nor (b)
Q1 Q2 Q3 Q4 Q5
A D C B B
Q6 Q7 Q8 Q9 Q10
C B C A C
Q11 Q12 Q13 Q14 A15
C D B C A
Q16 Q17 Q18 Q19 Q20
D B(TRUE) C C D
Q21 Q22 Q23 Q24 Q25
A C A A A
Q26 Q27 Q28 Q29 Q30
C A B C A
Q31 Q32 Q33 Q34 Q35
C D D B C
Q36 Q37 Q38 Q39 Q40
A B D B D
82
Q50. Write any 4 things that are displayed when you display the structure of a table using
DESCRIBE statement.
ANS: Four things are:- Field | Type | Null | Key | Default | Extra |
Q51. Harsh write statement it shows error: INSERT Emp(Empid,Salary) VALUES
('I201',25000,’MALE’); Where is mistake done by harsh help him to correct statement.
ANS: INSERT INTO Emp(Empid, salary) VALUES('I201',25000);
Q52. What is the difference in the output of SELECT statement if we write the keyword
ALL in place of DISTINCT?
ANS: By using ALL it will display duplicate data also.
Q53. What is the purpose of a Column Alias?
ANS: Column Alias will change name of attributes in output which we given with AS
clause
Q54. Write the purpose of the following SELECT statement?
SELECT Itemcode, IName AS "Item Title" FROM Item;
ANS: SELECT statement display in output IName as Item Title.
Q55. Which statement is used to modify data in a table?
ANS: UPDATE TABLE_NAME SET COLUMN_NAME=<New_Value/ Updated_Value>;
Q56. Which statement is used to remove a column from a table?
ANS: ALTER TABLE with DROP clause.
Q57. What is the purpose of "ORDER BY" clause?
ANS: ORDER BY clause arranging/sorting data in ascending or descending order.
Q58. Mr. Rohan has created a table 'student' with rollno., name, class and section. Now he
is confused to set the primary key. So identify the primary key column.
ANS: ROLLNO column will be PRIMARY key because it is unique.
Q59. Ms. Ravina is using a table 'customer' with custno, name, address and phonenumber.
She needs to display name of the customers, whose name start with letter 'S'. She wrote
the following command, which did not give the desired result.
Select * from customer where name="S%";
Help Ms. Ravina to run the query by removing the errors and write the correct query.
ANS: SELECT NAME FROM CUSTOMER WHERE NAME LIKE ‘S%’;
Q60. Write SQL query to add a column totalprice with data type numeric and size 10, 2 in
a table product.
ANS: ALTER TABLE PRODUCT ADD TOTALPRICE FLOAT(10,2);
NAME
Q61. The name column of a table 'student' is given below.
Anu Sharma
Based on the information, find the output of the following
Rohan Saini
queries: A. Select name from student where name like "K%";
Deepak Sing
B. Select name from student where name like "%i%";
Kannika Goal
Ans: NAME Kunal SharmA
NAME
Kannika Goal Rohan Saini TABLE:STUDENT
Kunal SharmA Deepak Sing
Kannika Goal RESULT OF A
RESULT OF B
Q62. A customer table is created with cno, cname, and address columns. Evaluate the
following statement whether it is correct or not? Delete cname from customer.
83
ANS: ALTER TABLE CUSTOMER DROP CNAME;
Q63. Shopkeeper needs to change the Cname of ‘SURESH’ of one of his customers in table
'customer'. whose cno is 1. Which command should he use for the same?
ANS: UPDATE CUSTOMER
SET CNAME=’SURESH’
WHERE CNO=1;
Q64. Sonal needs to display name of teachers, who have "o" as the third character in their
name.
She wrote the following query. Select name From teacher Where name ="$$o?";
But the query is not producing the result. Identify the problems.
ANS: SELECT NAME FROM TEACHER
WHERE NAME LIKE ‘_ _ o%’;
Q65. Pooja created a table 'bank' in SQL. Later on, she found that there should have been
another column in the table. Which command is used to add column to the table?
ANS: ALTER TABLE BANK
ADD COLUMN NAME DATA TYPE(SIZE);
Q66. Deepak wants to remove all rows from the table Bank. But he needs to maintain the
structure of the table. Which command is used to implement the same?
ANS: DELETE * FROM BANK;
Q67. Which command is use to delete a table?
ANS: DROP TABLE command
Q68. What is the default value of order by command?
ANS: ASCENDING
Q69. Create the following table item.
ANS: CREATE TABLE ITEM
(Itemno Number(3) Not Null Primary Key, TABLE: ITEM
Iname varchar(15),
Column name Data type SIZE Constraint
Price float(10,2),
Itemno Number 3 Primary Key
Quantity int
Iname Varchar 15
);
Price Float 10,2
Quantity Int 3
char varchar
Char(n) specifies the Character type data Varchar(n) specifies the Variable
of length n where n ranges from 0 to 255. Character type data of length n where n
ranges from 0 to 65535.
Char is of Fixed Length. Varchar is of Variable Length.
Char(10) implies to reserve memory for Varchar(10) implies a maximum of 10
10 characters, if data does not have 10 characters can be stored but the actual
characters (less than 10 characters), allocated bytes will depend on length of
MySQL fills the remaining characters entered string.
with space character padded at right
side.
Example- ‘Station’ in char(10) will Example- ‘Station’ in varchar(10) will
occupy 6 bytes only and rest 4 bytes will
occupy 6 bytes only and rest 4 bytes will
be padded with space character at right
not used by the compiler so in this data
side and totally 10 bytes will be type memory is saved as compared to
consumed/used by the compiler. char data type for every value in the
attributes of relation.
3 Differentiate ALTER TABLE and UPDATE command?
IS NULL and IS NOT NULL operators are used for filtering tuples from the table having or not
having NULL values in a specific attribute. E.g.
SELECT * FROM STUDENT WHERE DOB IS NULL;
SELECT * FROM STUDENT WHERE CLASS IS NOT NULL;
5. What is the use of LIKE operator in SQL?
Like operator is used for matching patterns of character values on specific attributes and filter
out the tuples on the basis of the given patterns. It uses two wildcard characters % and _
(Underscore) for specifying patterns.
6. What is the difference between where clause and having clause?
89
WHERE CLAUSE HAVING CLAUSE
It is used to apply conditions on individual rows. It is used to apply conditions on a group of
rows.
Example: Example:
Select * from customer where salary>2000; Select city,sum(salary) from customer group
by city having city=”jaipur”;
7. Explain Cartisian product/Cross join in SQL?
In a CARTESIAN JOIN there is a join for each row of one table to every row of another table.
This usually happens when the matching column or WHERE condition is not specified.
Example
Table1 Table2
A B A C D
1 XYZ 1 C1 10
2 PQR 2 C2 20
Cartesian product of Table 1 and Table 2 will be: SELECT * FROM Table1, Table2;
A B A C D
1 XYZ 1 C1 10
1 XYZ 2 C2 20
2 PQR 1 C1 10
2 PQR 2 C2 20
A natural join is a type of join operation that creates an implicit join by combining tables
based on columns with the same name and data type. Natural join automatically filters out
records based on equality on common attribute(s) and eliminates duplicated common
attribute(s) from the resultant table.
Example
Table1 Table2
A B A C D
1 XYZ 1 C1 10
2 PQR 2 C2 20
1 XYZ C1 10
2 PQR C2 20
90
KENDRIYA VIDYALAYA SANGATHAN, JAIPUR REGION
Class :- XII Session 2022-23
Computer Science (083)
Practice Paper- 1
Maximum marks: - 70 Time: - 3 Hr
General Instructions: -
• This question paper contains 5 sections. Section A to E
• All questions are compulsory
• Section A has 18 questions of 1 mark each.
• Section B has 7 questions very short answer type of 2 marks each
• Section C has 5 questions short answer type of 2 marks each
• Section D has 3 questions long answer type of 2 marks each
• Section E has 2 questions of 4 marks each. One internal choice is given in Q35
against part C only
• All programming questions are based on Python Programming language.
SECTION A
Q.1 State Ture of False 1
True is not False in [True, False]
Q.2 Which is unordered sequence 1
(a) tuple (b) list (c) dictionary (d) String
Q.3 What will be the content of dictionary d after executing the following 1
code
d={1:100,2:200}
t=(1,2,3)
d.fromkeys(t)
Q.4 What will be the output of the following code 1
3>2>1*5
(a) Ture (b) False (c) Error (d) None of all
Q.5 Predict the result of the following code 1
“@”.join(“abc-gmail.com”.split(“-“)
Q.6 Which open method of file handling does not require file to be close 1
explicitly.
Q.7 Which pair of SQL Statement is not from the same category of SQL 1
command
(a) create, alter
(b) insert, delete
(c) delete, drop
(d) update, delete
Q.8 Choose valid statement 1
(a) insert command is part of DDL
(b) insert command insert a row at beginning
(c) insert command can insert a row any where
(d) insert command insert many rows
Q.9 Mr khan has written following python code. Choose the one which will 1
not execute
(a) t=(10,20)+(30,40)
(b) t=(10,20)+(30)
(c) t=10+(10)
(d) t=(10,20)+(30,)
91
Q.10 A key of a table is not primary key but can be selected as primary key. 1
Choose the correct answer for the above given statement
(a) Secondary key (b) Alter table
(c) Candidate key (d) Foreign key
Q.11 Correct syntax to open a binary file in read mode is 1
(a) F=open(“abc.dat”,”b”,”r”)
(b) F=open(“abc.dat”,”br”)
(c) F=open(“abc.dat”,”rb”)
(d) F=open(“abc.dat”,”r”,”b”)
Q.12 The correct definition of column ‘alias’ is 1
(a) A permanent new name of column
(b) A new column of a table
(c) A view of existing column with different name
(d) A column which is recently deleted
Q.13 Fill in the blank 1
The service for remote login is called ____________
(a) Telnet
(b) Web browser
(c) Firewall
(d) Cookies
Q.14 Correct statement for ab is 1
(a) math.pow(a,b)
(b) a**b
(c) both a and b are correct
(d) math.sqrt(a,b)
Q.15 To view the list of tables of a database, the correct command is ____ 1
(a) list tables
(b) show tables
(c) display tables
(d) view tables
Q.16 Using python mysql connectivity the correct code to display all the 1
available databases of Mysql with the help of a cursor mcur is
(a) mcur.execute(“show database”)
(b) mcur.execute(“desc database”)
(c) mcur.execute(“show databases”)
(d) mcur.execute(“desc databases”)
Question 17 and 18 are ASSERTION AND REASONING based. Mark the
correct choice as
(a) A and R are True and R is correct explanation of A
(b) A and R are True and R is not correct explanation of A
(c) A is True but R is False
(d) A is False but R is True
Q.17 Assertion(A): if an existing file whose size was 50 Byte is opened in 1
write mode and after writing another 50 Byte into file it is closed. The
file size is 100 Byte after closing.
Reason(R) : File size will remain 50 Byte as it was not opened in
append mode so old content will be lost.
Q.18 Assertion(A): A function can take no argument or any number of 1
argument and writing of return keyword is not compulsory
Reason(R) : If we do not write return key word the function will return
None value.
92
SECTION B
Q.19 The following code has some error. Rewrite the code underling the 2
correction made.
def funpara(a=20,b=10,c)
if a>b:
print(“first is big”)
else:
print(“second is big”)
Return(“Third number is missing”)
1
(b) Write the correct output of following code
d={1:100,2:200}
for x,y in d:
print(x,d[x],end=’’)
Q.22 How many candidate key and primary key a table can have? Can we 2
declared combination of fields as a primary key?
Q.23 (a) Which protocol is used to upload files on web server? 2
(b) Expand the term TCP/IP
Q.24 Choose the best option for the possible output of the following code 2
import random
L1=[random.randint(0,10) for x in range(3)]
print(L1)
(a) [0,0,7] (b) [9,1,7] (c) [10,10,10] (d) All are possible
OR
import random
num1=int(random.random()+0.5)
What will be the minimum and maximum possible values of variable
num1
Q.25 Mrs sunita wrote a query in SQL for student table but she is not getting 2
desired result
select * from student where fee = NULL;
Rewrite the above query so she well gets desired result
OR
What is the difference between delete and drop command?
SECTION C
Q.26 (a) What is the difference between not-equi join and equi join. 1+2
(b) Consider the TEACHER table given below
TEACHER SUBJECT GENDER AGE
MANOJ SCIENCE MALE 38
NIKUNJ MATHS MALE 40
93
TARA SOCIAL FEMALE 38
SCIENCE
SUJAL SCIENCE MALE 45
RAJNI SCIENCE FEMALE 52
GEETA HINDI FEMALE 31
Patient
Pid Pname did Date_visit
P1 Lal singh D2 2022-04-25
P2 Arjun D1 2022-05-05
P3 Narender D4 2022-03-13
P4 Mehul D3 2022-07-20
P5 Naveen D2 2022-05-18
P6 Amit D1 2022-01-22
Q.29 Write a function exchange() that accept two list as parameter. The two 3
94
list contains integer values. The function should return a single list that
stores all the values of both list in sorted form. For example
L1=[4,20,9,15]
L2= [7,0,70]
The returned list should be [0,4,7,9,15,20,70]
Q.30 Two list Lname and Lage contains name of person and age of person 3
respectively. A list named Lnameage is empty. Write functions as details
given below
(i) Push_na() :- it will push the tuple containing pair of name and
age from Lname and Lage whose age is above 50
(ii) Pop_na() :- it will remove the last pair of name and age and
also print name and age of removed person. It should also
print “underflow” if there is nothing to remove
For example the two lists has following data
Lname=[‘narender’, ‘jaya’, ‘raju’, ‘ramesh’, ‘amit’, ‘Piyush’]
Lage=[45,23,59,34,51,43]
The code given below calculate the sum of marks of all student. Fill in
the blanks
import mysql.connector
con=_____________________.connect(host=’localhost’, user=’python’,
password=’test’, database=’student’) # statement 1
cur1=con.cursor()
cur1.____________(“select * from class”) # statement 2
total=0
for x in __________: # statement 3
total=total+int(x[2])
print(“total marks of all students :- “, total)
cur1.close()
OR
97
OR
(a) Define a function countresult() that count the total no of record
in “result.csv” file as described above
(b) Define a function finalstu() that reads the result.csv file as given
above and copy all the records into result.csv file except rollno 2
For example if result.cvs file contains
['1', 'amit', '40', '34', '90', '']
['2', 'bipin', '78', '34', '90', '']
['3', 'camal', '40', '45', '9', '']
The final.csv file will contain
['1', 'amit', '40', '34', '90', '']
['3', 'camal', '40', '45', '9', '']
SECTION E
Q.34 A table GAME has following structure and data 1+1
Gname NoPlayer Captain Won lost draw Location +2
Cricket 11 Dhoni 25 5 10 India
Cricket 11 Dhoni 10 5 3 Outside
TT 2 Vikash 17 20 5 India
TT 2 Vikash 4 20 7 Outside
Kabaddi 5 Suwan 30 3 1 India
Kabaddi 5 Suwan 10 1 0 Outside
import pickle
rec=[]
def writedata():
with open("library.dat","wb") as f:
98
for x in range(5):
bno=int(input("enter book no"))
title=input("enter title")
price=int(input("enter price"))
quantity=int(input("enter quantity")) 1
rec=[bno,title,price,quantity]
pickle.dump(_____________,f) # statement 1 1
def calculate_value():
with open("library.dat","_____________") as f: # statement 2 1
try:
sum1=_____________ # statement 3 1
while True:
_____________=pickle.load(f) # statement 4
sum1=sum1+ (int(rec[2]) * int(rec[3]))
print(“the cost of library is :- “,sum1)
except:
pass
99
Marking Scheme
Practice Paper-1
SECTION A
Q.1 True 1
Q.2 (c) dictionary 1
Q.3 d={1:None,2:None,3:None} 1
Q.4 (b)False 1
Q.5 [email protected] 1
Q.6 With open 1
Q.7 (c)delete,drop 1
Q.8 d) insert command insert many rows 1
Q.9 (b) t=(10,20)+(30) 1
Q.10 (c.) candidate key 1
Q.11 (c.) F=open(“abc.dat”,”rb”) 1
Q.12 ( c ) A view of existing column with different name 1
Q.13 ( a ) Telnet 1
Q.14 (c) Both a and b is correct 1
Q.15 (b) show tables 1
Q.16 (c) mcur.execute(“show databases”) 1
Q.17 IV. A is False but R is True 1
Q.18 (a) A and R are True and R is correct explanation of A 1
SECTION B
Q.19 def funpara(a=20, c, b=10) : # default parameter after non default and : 2
missing
if a>b:
print(“first is big”) # tab missing
else:
print(“second is big”)
return(“Third number is missing”) # return
½ mark for each error
Q.20 Circuit switching ensures ordered delivery of packets but it will not 2
allow others to use the path even no data is being sent.
OR
HTML Hyper Text Markup Language. Yes it has pre defined tags.
Q.21 (a) print(s1[::-1]) 1
(b) 1,100 2,100 1
Q.22 How many candidate key and primary key a table can have? Can we 2
declared combination of fields as a primary key?
Q.23 (a) FTP File Transfer Protocol 2
(b) Transmission Control Protocol/ Internet Protocol
Q.24 (d) All are possible 2
OR
Minimum 0 and maximum 1
Q.25 select * from student where fee IS NULL 2
OR
Delete is DML command and it deletes only data
Drop is DDL command it delete data as well entire structure of table
SECTION C
100
Q.26 (a) Non equi join is Cartesian product of two table where each row of 1+2
first table is joined with every row of second table. If m and n is total
number of rows in both table then non equi join will have m x n rows
Equi join is applied if there exist one common column in each tables
whose values can be matched.
(a) 4
(b) 3
3
(c) 45
52
(d) 3
Q.27 def readstar(): 3
f=open(“STORY.TXT”,”r”)
l=f.readlines() # it will return list of lines
count=0
for x in l:
count=count+1
if x in “*”:
print(“Line no “, count, “ has star”)
OR
def word5count():
f=open(“STORY.TXT”,”r”)
s=f.read()
l=s.split()
count=0
for x in l:
if len(x)>5:
count=count+1
print(“ total words having length more then 5 are “, count)
Q.28 (a) Consider the doctor and patient table and write the output of (i) to 3
(iv)
Doctor
Docid Dname Specialization Outdoor
D1 MANISH PHYSICIAN MONDAY
D2 PARESH EYE FRIDAY
D3 KUMAR ENT SATURDAY
D4 AKASH ENT TUESDAY
Patient
Pid Pname Did Date_visit
P1 Lal singh D2 2022-04-25
P2 Arjun D1 2022-05-05
P3 Narender D4 2022-03-13
P4 Mehul D3 2022-07-20
P5 Naveen D2 2022-05-18
P6 Amit D1 2022-01-22
(I) 3
(II) 1
1
2
(III)
101
Dname Pname
PARESH Lal singh
MANISH Arjun
AKASH Narender
KUMAR Mehul
PARESH Naveen
MANISH Amit
(V) MANISH
(d) Attribute:- A column or field of a table is called attribute
Q.29 def exchange(a,b): 3
c=a.extend(b)
return c.sort()
1 mark for defining function and return key word
1 mark for joining two list
1 mark for sorting list
Q.30 (i) 3
Lname=['narender', 'jaya', 'raju', 'ramesh', 'anita', 'Piyush']
Lage=[45,23,59,34,51,43]
Lnameage=[]
def push_na():
for x in range(len(Lname)):
if Lage[x]>50:
Lnameage.append((Lname[x],Lage[x]))
print(Lnameage)
push_na()
(ii)
def pop_na():
if len(Lnameage)==0:
print("Underflow")
else:
t=Lnameage.pop()
print("The name removed is ",t[0])
print("The age of person is ",t[1])
pop_na()
The code given below calculates the sum of marks of all students.
Fill in the blanks:
import mysql.connector
con=_____________________.connect( # statement 1
host=’localhost’,
user=’python’,
password=’test’,
database=’student’)
cur1=con.cursor()
rec=____________(“select * from class”) # statement 2
total=0
for x in __________: # statement 3
total=total+int(x[2])
print(“total marks of all students :- “, total)
cur1.close()
OR
(a) 12
30
65
(b) Mysql.connector # statement 1
price,product # statement 2
sqlquery # statement 3
Q.33 import csv 5
def createcsv():
103
f=open("result.csv","w", newline="")
w=csv.writer(f)
w.writerow([1,'amit',40,34,90,""])
w.writerow([2,'bipin',78,34,90,""])
w.writerow([3,'camal',40,45,9,""])
f.close()
import csv
def copycsv():
f=open("result.csv","r")
f1=open("final.csv","w",newline="")
w1=csv.writer(f1)
r=csv.reader(f)
for x in r:
x[5]=int(x[2])+int(x[3])+int(x[4])
w1.writerow(x)
f.close()
f1.close()
OR
Import csv
(a) def countresult():
f.open(“result.csv”,”r”)
count=count+1
r=csv.reader(f)
for x in r:
count=count+1
print(“ total records are “, count)
OR
(i) Alter table drop draw
(ii) Update game set noplayer=6 where gname=’Kabaddi’
105
KENDRIYA VIDYALAYA SANGATHAN, JAIPUR REGION
Class: XII Session: 2022-23
Computer Science (083)
Practice Paper -2
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice
isgiven in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.
106
7 The attribute which have al the properties of primary key.
(a) foreign key (b)alternate key 1
(c) candidate key (d) Both (a) and (c)
8 Which command is used to change some values in existing rows?
(a) UPDATE (b) ORDER (c) ALTER (d) CHANGE 1
107
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct choice as-
(a) Both A and R are true and R is the correct explanation for A
1
(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
17 Assertion (A):- key word arguments are related to the function calls.
Reasoning (R):- when you use keyword arguments in a function call, the 1
caller identifies the arguments by parameter name.
18 Assertion (A): CSV stands for Comma Separated Values
Reason (R): CSV files are a common file format for transferring and storing 1
data.
SECTION-B
19 Observe the following Python code very carefully and rewrite it after 2
removing all syntactical errors with each correction underlined.
DEF execmain():
x = input("Enter a number:")
if (abs(x)== x)
print("You entered a positive number")
else:
x=*1
print("Number made positive:" x )
20 Write two points of difference between Packet Switching and Message 2
Switching.
OR
Write two points of difference between XML and HTML.
21 (a)Given is a Python string declaration: 1+1 =2
S=”python rocks”
Write the output of: print(S[7:11]*3)
(b) 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.keys())
22 Differentiate between Primary Key and Candidate Key. 2
23 (a) Write the full forms of the following: 1+1=2
(i)IMAP (ii) POP
(b) Define VoIP?
24 Predict the output of the Python code given below: 2
def Alter(P=15,Q=10):
P=P*Q
Q=P/Q
print(P,"#",Q)
return Q
A=100
108
B=200
A=Alter(A,B)
print(A,"$",B)
B=Alter(B)
print(A,"$",B)
A=Alter(A)
print(A,"$",B)
OR
109
ii. SELECT DISTINCT Class FROM SPORTS.
iii. SELECT MAX(Class) FROM SPORTS;
iv. SELECT COUNT(*) FROM SPORTS GROUP BY Game1;
27 Write a method in Python to read lines from a text file DIARY.TXT, and 1+2
display those lines, which are starting with an alphabet ‘A’.
For 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 display() function should display the output as:
An apple a day keeps the doctor away.
A marked difference will come in our country.
OR
Write a method/function DISPLAYWORDS() in python to read lines from
a text file STORY.TXT, and display those words, which are less than 4
characters.
28 (a) consider the following tables School and Admin and answer the following 2+1=3
(a) questions: TABLE: SCHOOL
CODE TEACHER SUBJECT DOJ PERIODS EXPERIENCE
1001 RAVI ENGLISH 12/03/2000 24 10
1009 PRIYA PHYSICS 03/09/1998 26 12
1203 LISA ENGLISH 09/04/2000 27 5
1045 YASH RAJ MATHS 24/08/2000 24 15
1123 GAGAN PHYSICS 16/07/1999 28 3
1167 HARISH CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16
TABLE : ADMIN
CODE GENDER DESIGNATION
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD
110
(b) Write SQL command to delete a table from database.
Aalia has a list containing 10 integers. You need to help him create a program
with separate user defined functions to perform the following operations
based on this list.
➢ Traverse the content of the list and push the even numbers into a stack.
➢ Pop and display the content of the stack.
For example:
If the sample content of the list is as follows:
N=[12,13,34,56,21,79,98,22,35,38]
Sample output of the code should be:
38 22 98 56 34 12
SECTION – D
31 Trine Tech Corporation (TTC) is a professional consultancy company. The 5
company is planning to set up their new offices in India with its hub at
Hyderabad. As a network adviser, you have to understand their requirement
and suggest them the best available solutions. Their queries
are mentioned
as (i) to (v) below.
111
a) Which will be the most appropriate block, where TTC should plan to
install their server?
b) Draw a block to block cable layout to connect all the buildings in the
most appropriate manner for efficient communication.
c) What will be the best possible connectivity out
of the following, you will suggest to connect the new setup of offices in
Bengalore with its London based office.
● Satellite Link
● Infrared
● Ethernet
d) Which of the following device will be suggested by you to connect each
computer in each of the buildings?
● Switch
● Modem
● Gateway
e) Company is planning to connect its offices in Hyderabad which is less
than 1 km. Which type of network will be formed?
32 (a) Write the output of the code given below: 5
p=25
def
sum(q,r=3):
global p
p=r+q*
*2
print(p, end= '#')
a=6
b=4
sum(a,b)
sum(r=5,q=1)
(c) The code given below inserts the following record in the table
mobile:
import mysql.connector
mycon = mysql.connector.connect (host = “localhost”, user = “Admin”,
passwd = “Admin@123”, database = “connect”)
cursor = mycon. () # Statement 1
sql = “INSERT INTO Mobile (Name, Model, Price, Qty) VALUES (%s, %s, %s,
%s)” val = (“Samsung”, “Galaxy Pro”, 28000, 3)
cursor… (sql,val) #Statement 2
mycon. #Statement 3
112
Write the missing statement: Statement1 , Statement2 and Statement3
OR
(a) Predict the output of the code given below:
L1 = [100,900,300,400,500]
START = 1
SUM = 0
for C in range (START,4):
SUM = SUM + L1[C]
print (C,":",SUM)
SUM = SUM + L1[0]*10
print (SUM)
(b) The code given below reads the following record from the tablenamed
student and displays only those records who have marks greater than
80:
RollNo – integer
Name – string
Clas – integer
Marks – integer
Note the following to establish connectivity between Python andMYSQL:
• Username is root
• Password is tiger
• The table exists in a MYSQL database named kvs.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those
students whose marks are greater than 80.
Statement 3- to read the complete result of the query (records whose
marks are greater than 80) into the object named data, from thetable
studentin the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",passwo
rd="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)
33 a. What is the advantage of using a csv file for permanent storage? 1+2+2=5
b. Write a Program in Python that defines and calls the following user
defined functions:
(i) ADD() – To accept and add data of a student to a CSV file
‘record.csv’. Each record consists of a list with field elements as sid,
name and class to store student_id, student _name and class
respectively.
(ii) COUNTR() – To count the number of records present in the CSV file
named ‘record.csv’.
113
OR
a. Write difference between a binary file and a csv file.
b. Write a Program in Python that defines and calls the following user
defined functions:
(i) add() – To accept and add data of an employee to a CSV file
‘empdata.csv’. Each record consists of a list with field
elements as eid, ename and salaryto store empid, emp name
and emp salary respectively.
(ii) search()- To display the records of the emp whose salary is more
than 10000.
SECTION -E
34 Mayank creates a table RESULT with a set of records to maintain the marks 4
secured by students in sub1, sub2, sub3 and their GRADE. After creation of
the table, he has entered data of 7 students in the table.
Table : RESULT
ROLL_NO SNAME sub1 sub2 sub3 GRADE
101 KIRAN 366 410 402 I
102 NAYAN 300 350 325 I
103 ISHIKA 400 410 415 I
104 RENU 350 357 415 I
105 ARPITA 100 75 178 IV
106 SABRINA 100 205 217 II
107 NEELIMA 470 450 471 I
103 ISHIKA 400 410 415 I
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as
Primary key.
(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?
(iii) Write the statements to:
a. Insert the following record into the table
Roll No- 108, Name- Aaditi, sub1- 470, sub2-444, sub3- 475,
Grade– I.
b. Increase the sub2 marks of the students by 3% whose name
begins with ‘N’.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of students securing Grade-IV.
b. Add a column REMARKS in the table with datatype as varcharwith 50
characters.
35 Anamika is a Python programmer. She has written a code and created a 4
binary file data.dat with sid, sname and marks. The file contains 10 records.
She now has to update a record based on the sid entered by the user and
update the marks. The updated record is then to be written in the file
extra.dat. The records which are not to be updated also have to be written
to the file extra.dat. If the sid is not found, an appropriate message should
to be displayed.
As a Python expert, help him to complete the following code based on
requirement given above:
114
import ……………. #Statement 1
def update_data():
rec={}
fin=open("data.dat","rb")
fout=open(" ") #Statement 2
found=False
eid=int(input("Enter student id to update their marks :: "))
while True:
try:
rec= #Statement 3
if rec["student id"]==sid:
found=True
rec["marks"]=int(input("Enter new marks:: "))
pickle. #Statement 4
else:
pickle.dump(rec,fout)
except:
break
if found==True:
print("The marks of student id ",sid," hasbeen updated.")
else:
print("No student with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement1)
(ii) Write the correct statement required to open a temporary file
named extra.dat. (Statement 2)
(iii) Which statement should Anamika fill in Statement 3 to read the
data from the binary file, data.dat and in Statement 4 towrite the updated
data in the file, extra.dat?
115
Class: XII Session: 2022-23
Computer Science (083)
Answer Key- Practice Paper-2
Q.No. Answer Marks
1 Eval 1
2 Class 1
3 True#False 1
4 False 1
5 0 3 6 9 12 15 1
6 rw 1
7 . (d) Both (a) and (c) 1
8 UPDATE 1
9 (d) both b and c 1
10 (b)Foreign Key 1
11 (a) split() 1
12 (b) DESC,ASC 1
13 (b) message switching 1
14 (c) 23 1
15 (b) Null values 1
16 (b) cursor.fetchall() 1
17 Option (a) is correct 1
18 Option (b) is correct 1
19 Ans: def execmain(): 2
x = input("Enter a number:")
if (abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive:",x )
½ mark for each error correction
20 Write two points of difference between Packet Switching and Message
Switching. 2
OR
Write two points of difference between XML and HTML.
21 (a) Ans: rockrockrock
(b) dict_keys(['name', 'age', 'address'])
22 Differentiate between Primary Key and Candidate Key.
23 a) i. Internet Mail Access Protocol
ii. Post office Protocol
(b) Ans: VoIP(Voice over Internet Protocol ) refers to a way to carry
telephone calls over an IP data network. It offers a set of facilities to
manage the delivery of voice information over internet in digital form.
24 Ans: 2
20000 # 100.0
100.0 $ 200
2000 # 200.0
116
100.0 $ 200.0
1000.0 # 100.0
100.0 $ 200.0
OR
Ans:
(‘Python’)
1
3
25 Ans: DDL provides statements for creation and deletion of the database
tables, views, etc. The DDL provides a set of definitions to specify the
storage structure in a database system. Some DDL statements are as follows
(i) CREATE used to create new table in the database.
(ii) DROP used to delete tables from the database.
(iii) ALTER used to change the structure of the database table. This
statement can add up additional column, drop existing, and even
change the data type of columns involved in a database table.
(iv) RENAME used to rename a table.
DML provides statements for manipulating the database objects. It is used
to query the databases for information retrieval. Some DML statements are
as follows-
(i) INSERT used to insert data into a table.
(ii) SELECT used to retrieve data from a database.
(iii) UPDATE used to update existing data within a table.
(iv) DELETE used to delete all records from a table
OR
Ans: The difference between WHERE and HAVING clause is that WHERE
condition are applicable on individual rows whereas HAVING condition are
applicable on groups as formed by GROUP BY clause.
117
27 Ans: 3
def COUNTLINES():
c=0
f=open(‘STORY.TXT’)
l=f.readlines()
for i in l:
if i[0]==’A’ or i[0]= =’a’:
#or if i[0] in [“A”,”a’]
c=c+1
print(“Total lines “,c)
f.close()
OR
30 Books=[] 3
Def Addnew (books,name):
Books.append(name)
Print(“book1:”,name,”inserted”)
Def remove(books):
If books==[]:
Print(“stack is empty”)
Else:
Print(“book:”,books.pop(), “deleted”)
1 marks for each correct definition
1 marks for each statement
OR
N=[12,12,34,56,21,79,98,22,35,38]
118
def PUSH(S,N):
S.append()
def POP(S):
If S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%2==0
PUSH(ST,k)
while True:
If ST![]:
print(POP(ST),end=“ ”)
else:
break
31 (i) TTC should install its server in finance block as it is having
maximum number of computers.
(ii) The layout is based on minimum cable length required, which is 120
metres in the above case.
import csv
def ADD():
fout=open("record.csv","a",newline="\n")
wr=csv.writer(fout)
119
empid=int(input("Enter student id :: "))
name=input("Enter name :: ")
mobile=int(input("Enter marks :: "))
lst=[sid,name,mobile] ---------1/2 mark
wr.writerow(lst) ---------1/2 mark
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()
OR
Ans: Difference between binary file and csv file: (Any one
difference may be given) 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("empdata.csv","a",newline='\n')
wr=csv.writer(fout)
fid=int(input("Enter Emp Id :: "))
fname=input("Enter Emp name :: ")
fprice=int(input("Enter psalary :: "))
FD=[eid,ename,salary]
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()
(iv) Ans: ROLL_NO
120
(v) Ans: New Degree: 8 New Cardinality: 5
(vi) a. INSERT INTO RESULT VALUES (108, ‘Aadit’, 470, 444, 475, ‘I’);
b. UPDATE RESULT SET SEM2=SEM2+ (SEM2*0.03) WHERE SNAME
LIKE “N%”;
OR (Option for part iii only)
DELETE FROM RESULT WHERE DIV=’IV’;
c. ALTER TABLE RESULT ADD (REMARKS VARCHAR(50));
(iv) pickle
(v) fout=open(‘temp.dat’, ‘wb’)
(vi) Statement 3: pickle.load(fin)
(vii) Statement 4: pickle.dump(rec,fout)
121
Class: XII Session: 2022-23
Computer Science (083)
Practice Paper -3
Maximum Marks: 70 Time Allowed: 3
hoursGeneral Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Sections A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice
isgiven in Q.35 against Part-C only.
8. All programming questions are to be answered using Python Language only.
SECTION-A
1. Name the Python library module needed to be imported to invoke 1
following functions:
a. floor ( )
b. randomint ( )
2. To use function of any module, we have to use ____________ (command) 1
before the use of function of a module
3. Identify the key and values from the dictionary given below? 1
a. D = {“Rohan”:{“Manager”:427, “SBI”, 05884 } }
4. Which of the following is/are not assignment operator? 1
a) **= b) /= c) == d) %=
5. Find the output of the code: 1
num = 7
def func ( ) :
num = 27
print(num)
6. Which statement is used to retrieve the current position within the file: 1
a. fp.seek( ) b. fp.tell( ) c. fp.loc d. fp.pos
7. Clause used in select statement to collect data across multiple records and 1
group the results by one or more columns:
a. order by
b. group by
c. having
d. where
8. Which keyword eliminates redundant data from a SQL query result? 1
9. What does the following code print to console? 1
if True:
print(50)
else:
print(100)
a. True b. False c.50 d.100
122
10. Fill in the blank: 1
No. of rows in a relation is called ………………….. .
(a) Degree b. Domain c. Cardinality d. Attributes
11. Which of the following is not a correct Python statement to open a test file 1
“Students.txt” to write content into it :
a. f= open(“Students.txt”, ‘a’)
b. f= open(“Students.txt”, ‘w’)
c. f= open(“Students.txt”, ‘w+’)
d. f= open(“Students.txt”, ‘A’)
123
21. Write the output after evaluating he following 1
expressions:
a) k= 7 + 3 **2 * 5 // 8 – 3
print(k)
b) m= (8>9 and 12>3 or not 6>8) 1
print(m)
22. What do you understand by table constraint in a table? Give a suitable 2
example in support of your answer.
23. Expand the following terms: 2
a. PAN b. HTML c. URL d. POP
24. Predict the output of the Python code given below: 2
def func(n1 = 1, n2= 2):
n1= n1 * n2
n2= n2 + 2
print(n1, n2)
func( )
func(2,3)
OR
SECTION C
26. (a) Observe the following table and answer the question accordingly 1+2
Table:Product
Pno Name Qty PurchaseDate
101 Pen 102 12-12-2011
102 Pencil 201 21-02-2013
103 Eraser 90 09-08-2010
109 Sharpener 90 31-08-2012
113 Clips 900 12-12-2011
What is the degree and cardinality of the above table?
124
(b) Write the output of the queries (i) to (iv) based on the table, STUDENT
given below:
S.NO NAME STIPEND SUBJECT AVERAGE DIV
1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP Sc 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II
(i) Select MIN(AVERAGE) from STUDENT where SUBJECT=”PHYSICS”;
(ii) Select SUM(STIPEND) from STUDENT WHERE div=2;
(iii) Select AVG(STIPEND) from STUDENT where AVERAGE>=65;
(iv) Select COUNT(distinct SUBJECT) from STUDENT;
27. Write a definition of a function calculate () which count the 3
number of digits in a file “ABC.txt”.
OR
Write a function count( ) in Python that counts the number of “the” word
present in a text file “STORY.TXT”.
If the “STORY.TXT” contents are as follows:
This is the book I have purchased. Cost of the book was Rs. 320.
Then the output will be : 2
28. (a)Write the outputs of the SQL queries (i) to (iii) based on the tablesEmp: 3
125
30. Write a function in Python push(S,item), where S is stack and item is 3
element to be inserted in the stack.
OR
Write a function in Python pop(S), where S is a stack implemented by a
list of items. The function returns the value deleted from the stack.
SECTION-D
31. A software organization has to set up its new data center in Chennai. It has
four blocks of buildings – A, B, C and D.
Distance Between Blocks No. of Computers
Block A to Block B 50m Block A 25
Block B to Block C 150m Block B 50
Block C to Block D 25m Block C 125
Block A to Block D 170m Block D 10
Block B to Block D 125m
Block A to Block C 90m
1
(i) Suggest a cable layout of connection between the blocks (Diagram).
1
(ii) Suggest the most suitable block to host the server along with the reason.
(iii) Where would you place Repeater devices? Answer with justification. 1
(iv) The organization is planning to link its front office situated in the city
in a hilly region where cable connection is not feasible, suggest 1
an economic way to connect it with reasonably high speed. 1
(v) Where would you place Hub/Switch? Answer with justification.
32. (a) Find and write the output of the following python code: 2+3
def change(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'is'
print(m)
change('kv@onTHEtop')
(b) The given program is used to connect with MySQL abd show the name
of the all the record from the table “stmaster” from the database
“oraclenk”. You are required to complete the statements so that the
code can be executed properly.
import .connector pymysql
dbcon=pymysql. (host=”localhost”,
user=”root”, =”kvs@1234”)
if dbcon.isconnected()==False
print(“Error in establishing connection:”)
cur=dbcon. ()
126
query=”select * from stmaster”
cur.execute( )
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.________()
OR
(a) Write output of the following code:
def func(a):
s=m=n=0
for i in (0,a):
if i%2==0:
s=s+i
elif i%5==0:
m=m+i
else:
n=n+i
print(s,m,n)
func(15)
(b) Avni is trying to connect Python with MySQL for her project. Help her to
write the python statement on the following:-
(i) Name the library, which should be imported to connect MySQL with
Python.
(ii) Name the function, used to run SQL query in Python.
(iii) Write Python statement of connect function having the arguments
values as:
Host name :192.168.1.101
User : root
Password: Admin
Database : KVS
33. Divyanshi writing a program to create a csv file “a.csv” which contain 5
user id and name of the beneficiary. She has written the following code.
As a programmer help her to successfully execute the program.
import #Line 1
with open('d:\\a.csv','w') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(['user_id','beneficiary'])
newFileWriter. ([1,'xyz']) #Line2
newFile.close()
128
35. (a) What is the difference between 'w' and 'a' modes? 1+1+2
Anshuman is a Python learner, who has assigned a task to write python
Codes to perform the following operations on binary files. Help him in
writing codes to perform following tasks (b) & (c):
(b) Write a statement to open a binary file named SCHOOL.DAT
in read mode. The fileSCHOOL.DAT is placed in D: drive.
(c) Consider a binary file “employee.dat” containing details such
as empno:ename:salary (separator ':'). Write a python function
to display details of those employees who are earning between 20000
and 30000 (both values inclusive).
129
Class: XII Session: 2022-23
Marking Scheme Practice Paper-3
SECTION A
1. 1
floor ( ) ----- math
a. randomint ( ) ---- random
2. import or from import 1
3. 1
Key:- Rohan, Values :- “Manager”:427, “SBI”, 05884
4. 1
c) ==
5. Output: 7 1
6. (b) fp.tell( ) 1
7. b. Group by 1
8. Distinct 1
9. (c) 50 1
10. (c) Cardinality 1
11.
(d) f= open(“Students.txt”, ‘A’)
12. b.HAVING
18. (b) Both A and R are true and R is not the correct explanation for A 1
SECTION B
19. 2
Marks=int(input(“enter marks”))
temperature = int(input(“enter temperature”))
if marks < 80 and temperature >= 40:
print(“Not Good”)
else:
print(“OK”)
20. Web hosting is a service that allows us to put a website or a web page onto 2
the Internet, and make it a part of the World Wide Web. Once a website is
created, we need to connect it to the Internet so that users across the globe
can access.
OR
TCP breaks the message into packets and IP decides the destination
address for packets .
130
21. a) Ans: 9 1
b) Ans: True 1
22. Constraints are the rules enforced on data or columns on a table. These are 2
used to restrict the values that can be inserted in a table.
(a) NOT NULL Constraint
(b) UNIQUE Constraint
(c) PRIMARY Key
(d)CHECK Constraint
23. a. Personal Area Network 2
b. Hyper Text Markup Language
c. Uniform Resource Locator
d. Post office Protocol
24. 2 4 2
65
OR
47.0
35.0
54.0
26.0
25 2
a. Display the structure of table (DDL or DML)
Ans: desc student ---- DML
b. Increase the size of column FeeAmount by 5 (DDL or DML)
Ans: alter table student modify FeeAmount(7) ---- DDL
OR
char(n): stores a fixed length string between 1 and 255 Characters if the
value is of smaller length, adds blank spaces some space is wasted
OR
131
myfile=open("story.txt","r") # file story.txt is opened
count=0
line=myfile.read()
word=line.split()
for i in word:
if i=="the" or "The" or "THE":
count=count+1
print("total count= ",count)
myfile.close()
28. a. (i) Select ename, salary from emp where name like ‘%r%’
Ename Salary
Priya 60000
(ii) Select count(salary) from emp where joindate>’2019-11-28’
Count(salary)
4
(iii) Select max(joindate), min(joindate) from emp
max(joindate) min(joindate)
2020-02-16 2019-10-11
(b) Show databases;
29. def MSEARCH(STATES):
for i in STATES:
if i[0]==’M’:
print(i)
30. def push(s,a): 3
s.append(a)
return(s)
OR
def pop(s):
a=s.pop()
print("deleted item= ",a)
return(s)
SECTION-D
31. (i) (1 Mark for any of the above layouts)
(ii) The most suitable place / block to house the server of this organisation
would be Block C, as this block contains the maximum number of
computers. Placing the server in Block C will reduce the external traffic.
(iii) Repeater is to be placed between buildings where the distance is quite
large (in layouts)
(iv).The most economic way to connect it with a reasonable high speed
132
would beto use radio wave transmission, as they are easy to install, can
travel long distances, are omni-directional and can penetrate buildings
easily.
(v).Hub/Switch is to placed inside every block for internal connectivity
among computers.
32. (a) KVisONtheTOP 2+3=5
(b) import mysql.connector as pymysql
dbcon=pymysql.connect(host=”localhost”, user=”root”, passwd=”
kvs@1234”)
if dbcon.isconnected()==False
print(“Error in establishing connection:”)
cur=dbcon.cursor()
query=”select * from stmaster”
cur.execute(query)
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.close()
OR
(a) 0 15 0
(b) (i) import mysql.connector
(ii) execute (<sql query >)
(iii)mysql.connector.connect(host=”192.168.1.101”,user=”root”,passwd=”Ad
min”,datababase=”KVS”)
33. (a) import csv 5
(b) newFileWriter.writerow([1,'xyz'])
(c) newFileReader = csv.reader(newFile)
b) User_Id Beneficiary
1 xyz
(d) newFile.close()
OR
(a) csv
(b) “r”
(c) data=csv.reader(f)
(d) f.close()
(e) Comma Separated Values
34. (a) C_ID 1+1+2
(b) degree =7 and cardinality=4
(c) (i) DELETE FROM COMPANY WHERE C_ID= C24;
(ii) UPDATE COMPANY SET Fees=Fees+500;
OR
(i) ALTER TABLE COMPANY ADD(PLACE Varchar(20));
(ii) SELECT * FROM COMPANY;
133
35. (a) “w” mode opens a file for writing only. it overwrites if file already 1+1+2
exist but “a” mode appends the existing file from end. It does not overwrites
the file.
(b) f=open(“D:\ SCHOOL.DAT”,’r’)
(c) def Readfile():
i=open( “Employee.dat” ,
“rb+”)
x=i .readline()
while(x):
I= x.split(‘:’)
if ( (float (I[2]) >=20000) and (float
I[2])<=40000):print(x)
x= i.readline()
134
Class: XII Session: 2022-23
Computer Science (083)
Practice Paper - 4
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
2. All questions are compulsory.
3. Section A have 18 questions carrying 01 mark each.
4. Section B has 07 Very Short Answer type questions carrying 02 marks each.
5. Section C has 05 Short Answer type questions carrying 03 marks each.
6. Section D has 03 Long Answer type questions carrying 05 marks each.
7. Section E has 02 questions carrying 04 marks each. One internal choice
isgiven in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. State True or False 1
“Name of Variable come always after the assignment operator in python.
2. Which of the following is valid datatype in Python? 1
(a) tuple (b) None (c) float (d)All the options
3. Give the output: 1
dic1={‘r’:’red’,’g’:’green’,’b’:’blue’}
for i in dic1:
print (i,end=’’)
a. rgb
b. RGB
c. RBG
d. rbg
4. Consider the given expression: 1
not True or False and True
Which of the following will be correct output if the given expression is
evaluated?
(a) True
(b) False
(c) NONE
(d) NULL
5. Select the correct output of the code: 1
a = "Year 3033 at All the best"
a = a.split('3')
b = a[0] + ". " + a[1] + ". " + a[2]
print (b)
(a) Year . 0. at All the best
(b) Year 0. at All the best
(c) Year . 0.
(d) Year . 0. all the best
135
6. Which of the following mode, file should be open if we want to add new 1
contents in in existing file contents?
(a) a (b) r (c) w (d) None of the above
136
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
15. Which one of the following function is an invalid multiple row function? 1
(a) sum()
(b) total()
(c) count(*)
(d) avg()
16. Which function should be used to display the number of records as per need 1
of a user during interface with python and SQL database.
(a) fetchone()
(b) fetchmany()
(c) fetchall()
(d) fetchshow()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the
correct
choice as
(a) Both A and R are true 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
17. Assertion (A): A function is block of organized and reusable code that is 1
used to perform a single, related action.
Reasoning (R):- Function provides better modularity for your application and
a high degree of code reusability.
18. Assertion (A): Access mode ‘a’ opens a file for appending. 1
Reason (R): The file pointer is at the end of the file if the file exists.
SECTION-B
19 Harsh has written a code to input a number and find a table of any
number.His code is having errors. Rewrite the correct code and
underline the corrections made.
def table():
n=int(("Enter number which table U need: ")
for i in (1,11):
print("Table of Enter no=”,i*i)
Table()
20 Identify the switching technique according to the given statement.
(i) A methodology of implementing a telecommunication network in
which two network nodes establish a dedicated communication
channel.
(ii) the message gets broken into small data packets and Store and
forward technique used.
OR
What is web browser? Give any two examples of it which you used in your
life.
21. (a) Given is a Python string declaration: 1
137
(b) Write the output of the code given below:
my_dict = {"name": "Aman", "age": 26} 1
my_dict['age'] = 27
my_dict['address'] = "Delhi"
print(my_dict.values())
22 Explain the use of ‘Primary Key’ in a Relational Database Management
System. Give example to support your answer.
23. (a) Write the full forms of the following: 2
(i) VoIP (ii) TCP/IP
(b) If we want to access remote computer than which command should be
used in networking?
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=' ')
OR
Predict the output of the Python code given below:
tuple1 = (1, 11, 22, 33, 44 ,55)
list1 =list(tuple1)
new_list = []
for i in list1:
if i%3==0:
new_list.append(i)
new_tuple = tuple(new_list)
print(new_tuple)
25. Differentiate between count() and count(*) functions in SQL with 2
appropriate example.
OR
Categorize the following commands as DDL or DML:INSERT, ALTER, DROP,
DELETE,UPDATE,CREATE
138
26 (a) Consider the following tables – LOAN_Account and Branch:
Table: Bank_Account
ACode Name Type
A01 Amrita Savings
A02 Parthodas Current
A03 Miraben Current
Table: Branch
ACode City
A01 Delhi
A02 Mumbai
What will be the output of the following statement?
SELECT * FROM LOAN_Account JOIN Branch;
(b) Write the output of the queries (i) to (iv) based on the table,COURSE
given below:
Table: COURSE
CID CNAME FEES STARTDATE TID
C201 Animation and VFX 12000 2022-07-02 101
C202 CADD 15000 2021-11-15 NULL
C203 DCA 10000 2020-10-01 102
C204 DDTP 9000 2021-09-15 104
C205 Mobile Application 18000 2022-11-01 101
C206 Digital marketing 16000 2022-07-25 103
139
The Count() function should display the output as:
It might rain today.
it is mentioned on weather sites
I or i: 2
28 Write SQL commands for (i) to (vi) on the basis of table STUDENT:
Table : STUDENT
ADMNO NAME STREAM FEES AGE SEX
1 RAEESH SCIENCE 3000 15 MALE
2 SATISH ARTS 2000 14 MALE
3 SUMAN SCIENCE 4000 14 FEMALE
4 SURYA COMMERCE 2500 13 FEMALE
5 SURESH ARTS 2000 13 MALE
(i) List the name of all the students, who have taken stream as science.
(ii) To count the number of female students.
(iii) To display the number of students, stream wise.
(iv) To display all the records in sorted order of name.
(v) To display the stream of student whose name start from ‘s’.
(vi) To display the name and fees of students whose fees range from
3000 to 4000(both values of fees included)
29 Write a function LShift(Arr,n) in python, which accepts a list Arr of numbers
and n is a numeric value by which all elements of the list are shifted to left.
Sample Input Data of the list.
Arr=[10,20,30,40,12,11], n=2 Output Arr=[30,40,12,11,10,20]
30 ICCI has created a dictionary containing top players and their runs as key
value pairs of cricket team. Write a program, with separate user defined
functions to perform the following operations:
Push the keys (name of the players) of the dictionary into a stack, where
the corresponding value (runs) is greater than 50.Pop and display the
content of the stack.
For example:
If the sample content of the dictionary is as follows:
SCORE={"KAPIL":40, "SACHIN":55, "SAURAV":80, "RAHUL":35,
"YUVRAJ":110, }
The output from the program should be: SACHIN SAURAV YUVRAJ
OR
Vikram has a list containing 10 integers. You need to help him create a
program with separate user defined functions to perform the following
operations based on this list. Traverse the content of the list and push
the ODD numbers into a stack. Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[14, 15, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be: 15,21,79,35
Section- D
31 StartIndia Corporation, an Jharkhand based IT training company, is
planning to set up training centers in various cities in next 2 years. Their
first campus is coming up in Ranchi district. At Ranchi campus, they are
planning to have 3 different blocks for App development, Web designing
140
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.
(i) to (v), keeping in mind the distances between various blocks/locations
and other given parameters.
Block Distance
App development to Web designing 38 m
App development to Movie editing 105 m
Web designing to Movie editing 42 m
Ranchi Campus to Gumla Campus 232 km
Number of computers:
Block Number of Computers
App development 65
Web designing 40
Movie editing 70
Name="PythoN3.1"
R=" "
for x in range(len(Name)):
if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
(b) The code given below reads the following record from the tablenamed
student and displays only those records who have marks greater than
142
or equal to 90:
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
Statement 2 – to execute the query that extracts records of those
students whose marks are less than or equal to 90.
Statement 3- to read the complete result of the query (records whose
marks are less than or equal to 90) into the object named data, from
the table studentin the database.
import # Statement-1
144
Class: XII Session: 2022-23
Marking Scheme Practice Paper-4
1. FALSE MARKS-1
2. (D)- ALL THE OPTIONS MARKS-1
3. (A) rgb MARKS-1
4. (B) FALSE MARKS-1
5. (C) Year . 0. MARKS-1
6. (A) a MARKS-1
7. (D) DELETE MARKS-1
8. (C) DESCRIBE TABLE NAME MARKS-1
9. (B) STATEMENT-4 MARKS-1
10. (B) FOREIGN KEY MARKS-1
11. (B) SEEK MARKS-1
12. (B) ALL MARKS-1
13. (B) SMTP MARKS-1
14. (B) 14.0 MARKS-1
15. (B) TOTAL() MARKS-1
16. (B) FETCHMANY() MARKS-1
17. (A) Both A and R are true and R is the correct explanation for A MARKS-1
18. (A) Both A and R are true and R is the correct explanation for A MARKS-1
SECTION-B
19. def table(): MARKS-1/2
Each
n=int(input("Enter number which table U need: "))
for i in range(1,11):
print("able of Enter no=",i*n)
table()
20. (i) CIRCUIT SWITCHING (ii) PACKET SWITCHING MARKS-1 Each
OR
Web browser: Web browser is a software which will help to access the web
page/web-site
Example:- Mozilla fire fox and internet explorer etc.
21. (A) THE OUTPUT WILL BE- @2 ina B# MARKS-1
(B) THE OUTPUT WILL BE- dict_values(['Aman', 27, 'Delhi']) MARKS-1
22. Primary Key gives unique row values from given relation MARKS-1 Each
and as constraint it removed delicacy of data as input.
23. (A)Full Form: VoIP:- Voice over internet protocol MARKS-1/2 Each
TCP/IP :- Transmission control Protocol/Internet protocol.
(B) TELNET Command MARKS-1
24. OUTPUT: -22 # 756 # -9 # 230 # MARKS-2
OR
OUTPUT:- (33,)
25 count():- It will count the values of attribute without empty valuesMARKS-1 Each
Count(*):- It will count the values of attribute with empty values
OR
DDL: ALTER,DROP,CREATE and DML: INSERT,DELETE,UPDATE MARKS-1 Each
SECTION-C
26. (A) MARKS-1
Acode Name Type Acode City
A01 Amrita Saving A01 Delhi
A01 Amrita Saving A02 Mumbai
145
A02 Parthodas Current A01 Delhi
A02 Parthodas Current A02 Mumbai
A03 Miraben Current A01 Delhi
A03 Miraben Current A02 Mumbai
(B) (i) (ii) MARKS: ½ Each
TID TID COUNT() MAX(FEES)
101 101 2 18000
NULL
102
104
103
(iii) CNAME: Mobile Application, Development Digital marketing
(iv) SUM(FEES) :- 49000
27. def COUNTWORDS():
file = open ('test.txt', 'r')
lines = file.read()
data=lines.split()
count=0
for w in data :
if (w[0]).lower() not in 'd':
count = count + 1
print ("The number of lines not starting with : ", count)
file.close()
COUNTWORDS()
OR
def COUNT():
file = open ('TEST.txt', 'r')
lines = file.readlines()
count=0
for w in lines :
if (w[0])=='I' or (w[0])=='i':
count = count + 1
print ("The number of lines starting with I or i : ", count)
file.close()
COUNT()
28. (I) SELECT NAME FROM STUDENT WHERE STREAM=”SCIENCE”;
(II) SELECT COUNT(*) FROM STUDENT WHERE SEX=’FEMALE’;
(III) SELECT COUNT(*) FROM STUDENT GROUP BY STREAM;
(IV) SELECT * FROM STUDENT ORDER BY NAME ASC;
(V) SELECT STREAM FROM STUDENT WHERE STREAM LIKE”S%”;
(VI) SELECT NAME,FEES FROM STUDENT WHERE FEES BETWEEN 3000 AND 4000;
OR
SELECT NAME,FEES FROM STUDENT WHERE FEES >= 3000 AND FESS<=4000;
29. L=[10,20,30,40,12,11]
m=2
def Lshift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[x]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
146
print(Arr)
Lshift(L,m)
30. SCORE={"KAPIL":40, "SACHIN":55,"SAURAV":80, "RAHUL":35, "YUVRAJ":110,}
def PUSH(S,R):
S.append(R)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in SCORE:
if SCORE[k]>50:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
OR
N=[14, 15, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if(k%2!=0):
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end="")
else:
break
31. (i) Movie editing block is the most appropriate to house the server as it has the maximum
number
of computers.
(ii) Firewall
(iii) Ethernet Cable:
(iv) Switch/hub will be placed in all blocks to have connectivity within the block.
Repeater is required between the blocks as the distance is more than 100 mts.
(v) Protocol: VoIP
32. (a) The output :- 105#6#
(b) Statement 1: mysql.connect() Statement 2: con1.cursor()
Statement 3: mycursor.execute(querry)
OR
(a) pYTHOnN#.
(b) Statement 1: con1.cursor()
Statement 2: mycursor.execute("select * from student where Marks>=90")
147
Statement 3: mycursor.fetchall()
33. Statement-1:- csv module Statement-2:- ‘a’ -append mode.
Statement-3:- f.close() Statement4: reader()
Statement-5:- INDIA NEW DELHI
CHINA BEIJING
OR
Difference between binary file and csv file: (Any one difference may be given)
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
import csv
def add():
fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout)
ed=int(input("Enter Furniture Id :: "))
ename=input("Enter Furniture name :: ")
esalary=int(input("Enter price :: "))
FD=[eid,ename,esalary]
wr.writerow(FD)
fout.close()
add()
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])<70000:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
print("Now displaying")
search()
34. (i) Most appropriate column as primary key: Watchid
(ii) After deleted 2 columns and 2 row new degree-4 and cardinality-7
(iii) (a) INSERT INTO STORE VALUES(‘W006’,’Prime Time’,12000,’Ladies’,120)
(b) UPDATE STORE SET PRICE=PRICE+5000 WHERE BRAND=’RADO’;
OR
(a) DELETE FROM STORE WHERE TYPE=UNISEX;
(b) ALTER TABLE STORE ADD Wdiam int;
35. (a) Binary file should be use when we want to read images, audio, video pdf files or we
Can say non-human readable codes.
(b) def DisplayAvgMarks(sub):
f=open("TEST.dat","rb")
count=0
sum=0
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if rec[1]==sub:
sum+=rec[3]
count+=1
except:
f.close()
print("AVG Marks:",sum/count)
DisplayAvgMarks(sub)
148
Class: XII Session: 2022-23
Computer Science (083)
Practice Paper -5
SECTION-A
Q. Question Marks
No.
1. State True or False 1
“continue keyword skips remaining part of an iteration in a loop”
2. Which of the following is an invalid operator in Python? 1
(a) == (b) ** (c) += (d)=-
3. Given the following dictionaries 1
dict_fruit={"Kiwi":"Brown", "Cherry":"Red"}
dict_vegetable={"Tomato":"Red", "Brinjal":"Purple"}
Which statement will merge the contents of both dictionaries?
a. dict_fruit.update(dict_vegetable)
b. dict_fruit + dict_vegetable
c. dict_fruit.add(dict_vegetable)
d. dict_fruit.merge(dict_vegetable)
4. Consider the given expression: 1
not False and False or True
Which of the following will be correct output if the given expression is
evaluated?
a. True b.False c. NONE d. NULL
5. Select the correct output of the code: 1
a = "Python! is amazing!"
a = a.split('!')
b = a[0] + "." + a[1] + "." + a[2]
print (b)
(a) Python!. is amazing!. (b) Python. is amazing.
(c) Python. ! is amazing.! (d) will show error
6. Which of the following mode in file opening statement do not overwrite 1
the existing content?
(a) a+ (b) r+ (c) w+ (d) None of the above
7. Fill in the blank: 1
command is used to delete the table from the database of SQL.
(a) update (b)remove (c) alter (d) drop
8. Which of the following commands will use to change the structure of 1
table in MYSQL database?
(a) DELETE TABLE (C)DROP TABLE
149
(b) REMOVE TABLE (d)ALTER TABLE
9. Which of the following statement(s) would give an error after 1
executing the following code?
Q="Humanity is the best quality" # Statemen1
print(Q) # Statemen2
Q="Indeed. # Statement3
Q[0]= '#' # Statement4
Q=Q+"It is." # Statement5
(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5
10. Fill in the blank: 1
is a non-key attribute, , used for referential integrity in
the database of MYSQL..
(a) Primary Key
(b) Foreign Key
(c) Candidate Key
(d) (d) Alternate Key
11. The tell() function returns: 1
(a) Number of bytes remaining to be read from the file
(b) Number of bytes already read from the file
(c) Number of the byte written to the file
(d) Total number of bytes in the file
12. Fill in the blank: 1
The SELECT statement when combined with_________function,
returns number of rows present in the table.
(a) DISTINCT
(b) UNIQUE
(c) COUNT
(d) AVG
13. Fill in the blank: 1
is a communication protocol responsible to control the
transmission of data over a network.
(a) TCP (b) SMTP (c) PPP (d)HTTP
14. What will the following expression be evaluated to in Python? 1
print(21.5 // 4 + (8 + 3.0))
(a) 16 (b)14.0 (c) 15 (d) 15.5
15. Which function is used to display the unique values of a column of a 1
table?
(a) sum()
(b) unique()
(c) distinct()
(d) return()
16. To establish a connection between Python and SQL database, connect() 1
is used. Which of the following value can be given to the keyword
argument – host, while calling connect ()?
(a) localhost
(b) 127.0.0.1
(c) any one of (a) or (b)
(d) localmachine
150
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice
as
(a) Both A and R are true 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
17. Assertion (A):- If the arguments in function call statement are provided in 1
the format parameter=argument, it is called keyword arguments.
Reasoning (R):- During a function call, the argument list first contain
keyword argument(s) followed by positional argument(s).
18. Assertion (A): CSV (Comma Separated Values) is a file format for data 1
storage with one record on each line and each field is separated by comma.
Reason (R): The format is used to share data between cross platform as text
editors are available on all platforms.
SECTION-B
19. Observe the following Python code very carefully and rewrite it after 2
removing all syntactical errors with each correction underlined.
import math
x = input("Enter a number:")
if (abs(x)= x):
print("You entered a positive number")
else:
x=*-1
print("Number made positive : ",x)
20. Write two differences between Coaxial and Fiber transmission media. 2
OR
Write components of data communication.
21. (a) Given is a Python string declaration: 1
message="Bring it on!!!"
Write the output of: print(message[::-2])
(b) Write the output of the code given below:
book_dict = {"title": "You can win", “copies”:15} 1
book_dict['author'] = “Shiv Khera”
book_dict['genre'] = "Motivation"
print(book_dict.items())
22. Explain the use of GROUP BY clause in a Relational Database Management 2
System. Give example to support your answer.
23. (a) Write the full forms of the following: 2
(i) HTTP (ii) IP
(b) What is the use of TELNET?
24. Predict the output of the Python code given below: 2
def Swap (a,b ) :
if a>b:
print(“changed ”,end=“”)
return b,a
else:
print(“unchanged ”,end=“”)
return a,b
data=[11,22,16,50,30]
for i in range (4,0,-1):
print(Swap(data[i],data[i-1]))
OR
151
Predict the output of the Python code given below:
P = (10, 20, 30, 40, 50 ,60,70,80,90)
Q =list(P)
R = []
for i in Q:
if i%3==0:
R.append(i)
R = tuple(R)
print(R)
25. Differentiate between Where and Having clause in SQL. 2
OR
Define DDL AND DML and give 2-examples for each.
SECTION-C
26. (a) Consider the following tables – Employee and Office: 1+2
Table: Employee
Emp_Id Name Salary
E01 Lakshya 54000
E02 Ravi NULL
E03 Neeraj 32000
E04 Brijesh 42000
Table: Office
Emp_Id Dept DOJ
E01 Computer 05-SEP-2007
E02 Physics 05-JAN-2008
E03 Sports 30-DEC-2000
E04 English 05-SEP-2012
28. (a) Write the outputs of the SQL queries (i) to (iv) based on the relations 3
CLUB and STUDENT given below:
Table : CLUB
COACHID CNAME AGE SPORTS DATEOFAPP PAY GENDER
1 KUKREJA 35 KARATE 27/03/1996 1000 M
2 RAVINA 34 KARATE 20/01/1998 1200 F
3 KARAN 34 SQUASH 19/02/1998 2000 M
4 TARUN 33 BASKETBALL 01/01/1998 1500 M
5 ZUBIN 36 SWIMMING 12/01/1998 750 M
6 KATAKI 36 SWIMMING 24/02/1998 800 F
7 ANKITA 39 SQUASH 20/02/1998 2200 F
8 ZAREEN 37 KARATE 22/02/1998 1100 F
9 KUSH 41 SWIMMING 13/01/1998 900 M
10 SHAILYA 37 BASKETBALL 19/02/1998 1700 M
Table : STUDENT
COACHID SNAME STIPEND STREAM MARKS GRADE CLASS
1 KARAN 400.00 MEDICAL 78.5 B 12B
12 VINNET 450.00 COMMERCE 89.2 A 11C
13 VIVEK 300.00 COMMERCE 68.6 C 12C
4 DHRUV 350.00 HUMANITIES 73.1 B 12C
15 MOHIT 500.00 NONMEDICAL 90.6 A 11A
6 ANUJ 400.00 MEDICAL 75.4 B 12B
17 ABHAY 250.00 HUMANITIES 64.4 C 11A
18 PAYAL 450.00 NONMEDICAL 88.5 A 12A
19 DIKSHA 500.00 NONMEDICAL 92.0 A 12A
10 RISHIKA 300.00 COMMERCE 67.5 C 12C
For example:
If L contains [9,4,0,3,11,56]
OR
SECTION-D
31. KVS is planning to connect its Bikaner KV NAL Campus with its head office 5*1
KVS RO Jaipur. Its Bikaner KV NAL Campus is spread across an area of
approx. 1 square kilometers consisting of 3 blocks. Human Resources,
Academics and Administration. You as a network expert have to suggest
answers to the four queries (i) to (v) raised by them.
Administration Academics
(i) Suggest the most suitable block in the KV NAL Campus to host the
server. Give a suitable reason with your suggestion.
(ii) Suggest the cable layout among the various blocks within the KV
NAL Campus for connecting the blocks.
(iii) Suggest the placement of the following devices with appropriate
reasons:
a. Switch / Hub
b. Repeater
(iv) Suggest a protocol that shall be needed to provide Video
Conferencing solution between KVS RO JAIPUR Office and Bikaner
NAL KV campus.
(v) Suggest a device that helps to strengthen the weak signals in a
155
network.
32. (a) Write the output of the code given below: 2+3
a=5
def add(b=2):
global a
a=a+b
print(a,'#',b)
return a
b=add(a)
print(a,'#',b)
b=add(b)
print(a,'#',b)
(b) The code given below inserts the following record in the table
Employee:
EmpNo – integer
Name –
string
Department
– string
Salary –
integer
156
OR
(a) The code given below reads the following record from the table
named items and displays only those records who have price
greater than 100:
ItemNo –
integer
Name – string
Price – integer
157
3. (b) Write a Program in Python that defines and calls the following user
defined functions:
(i) InsertRow() – To accept and insert data of an student to a CSV file
‘class.csv’. Each record consists of a list with field elements as
rollno, name and marks to store roll number, student’s name and
marks respectively.
(ii) COUNTD() – To count and return the number of students who
scored marks greater than 75 in the CSV file named ‘class.csv’.
OR
import csv
def CSVOpen():
with open('books.csv','_____',newline='') as csvf: #Statement-1
cw=_____________#Statement-2
__________________#Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=_________________#Statement-4
for r in cr:
if : #Statement-5 print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()
SECTION-E
3 Mubarak creates a table STORE with a set of records to maintain the 1+1
4. details of items. After creation of the table, he has entered data of 7 items +2
158
in the table.
Table: STORE
ItemNo Item Scod Qty Rate LastBuy
e
2005 Sharpener Classic 23 60 8 31-JUN-09
2003 Balls 22 50 25 01-FEB-10
2002 Gel Pen Premium 21 150 12 24-FEB-10
2006 Gel Pen Classic 21 250 20 11-MAR-09
2001 Eraser Small 22 220 6 19-JAN-09
2004 Eraser Big 22 110 8 02-DEC-09
2009 Ball Pen 0.5 21 180 18 03-NOV-09
Based on the data given above answer the following questions:
(i) Identify the most appropriate column, which can be considered as
Primary key.
(ii) If 2 columns are added and 2 rows are deleted from the table
STORE, what will be the new degree and cardinality of the above
table?
(iii) Write the statements to:
a. Insert the following record into the table as (2022, Diary, 23, 10,
250, 18-OCT-2022).
b. Increase the rate of the items by 5% whose name begins with
‘G’.
OR (Option for part iii only)
(iii) Write the statements to:
a. Delete the record of items having rate less than 10.
b. Add a column REMARKS in the table with datatype as
varchar with 50 characters
3 Reshabh is a programmer, who has recently been given a task to write a
5. 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.
He has succeeded in writing partial code and has missed out certain
statements, so he has left certain queries in comment lines. You as an
expert of Python have to provide the missing statements and other related
queries based on the following code of Reshabh.
import pickle
def AddStudents():
_____________________# statement 1 to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
159
L = [Rno, Name, Percent]
__________________#statement 2 to write the list L into the file
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:
___________________ #statement 3 to read from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("No student has percentage more than 75")
print("average percent of class = ",_____________) #statement 4
AddStudents()
GetStudents()
(i) Which of the following commands is used to open the file
“STUDENT.DAT” for writing only in binary format? (marked as #1
in the Python code) 1
(ii) Which of the following commands is used to write the list L into
the binary file, STUDENT.DAT? (marked as #2 in the Python code) 1
(iii) Which of the following commands is used to read each record from
the binary file STUDENT.DAT? (marked as #3 in the Python code) 1
(iv) What expression will be placed in statement 4 to print the average
1
percent of the class.
160
Marking Scheme
Practice Paper-5
SECTION-A
QN. Answer of Question
1. Ans. True 1
2. Ans. (d)=- 1
3. Ans: (a) dict_fruit.update(dict_vegetable) 1
4. Ans. (a) True 1
5. Ans. (b) Python. is amazing. 1
6. Ans: (b) a+ 1
7. Ans. (d) drop 1
8. Ans. (d) ALTER TABLE 1
9. Ans. (b) Statement 4 1
10 Ans. (b) Foreign Key 1
.
11 Ans: (b) Number of bytes already read from the file 1
.
12 Ans. Count 1
13 Ans. (a) TCP 1
14 Ans. (a) 16 1
15 Ans. (c) distinct( ) 1
16 (c) any one of (a) or (b) 1
17 Ans. (c) 1
18 Ans: (a) Both A and R are true and R is the correct explanation for A 1
SECTION-B
19 import math 2
. x =int(input("Enter a number:") )
if (math.abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive : ",x)
20 Coaxial Fiber 2
. 1. Relatively cheaper 1. Relatively costly
2. less reliable 2. More reliable
OR
Sender, Receiver, transmission media, protocol, message
21 (a) !!ot nr 1
. (b) dict_items((‘title’,‘you can win’),(‘copies’,15),(‘author’,‘Shiv
Khera’),(‘genre’,‘Motivation’)) 1
22 Ans. GROUP BY clause is used to get the summary data based on one or 2
. more groups. The groups can be formed on one or more columns. For
example, the GROUP BY query will be used to count the number of
employees in each department, or to get the department wise total
salaries.
SELECT COUNT(ENAME), SUM(SALARY), DEPT
FROM EMPLOYEES
GROUP BY DEPT;
23 Ans. (a) (i) Hyper Text Transfer Protocol (ii) Internet Protocol 2
161
. (b) Telnet is a network protocol used to virtually access a computer and
to provide a two-way, collaborative and text-based communication
channel between two machines.
b)
(i) TO
Delhi
Pune
Guwahati
ii) TO COUNT(*) MIN(FARE)
Guwahati 2 10000
iii) FNAME
INDIGO
AIR ASIA
Kingfisher
iv) AVG(FARE)
7166.66
27 Ans: 3
. def COUNTLINES() :
file = open ('TESTFILE.TXT', 'r')
List = file.readlines()
count=0
for line in List:
words=line.split()
if words[0].lower() in (‘a’,‘an,‘the’):
count = count + 1
print("The number of lines starting with any article are :", count)
file.close
162
()
OR
Ans:
def GPCount() :
file = open ('STORY.TXT', 'r')
content = file.read()
for i in content:
if i.lower()== 'g':
countG = countG + 1
if i.lower()== 'p':
countP = countP + 1
print ("The number of G or g : ", countG)
print ("The number of P or p : ", countP)
file.close()
Note: Any other relevant and correct code may be marked
28 Ans. (a) 3
. i) Give 1 mark each correct output
SPORTS
Karate 1000
Squash 2000
Basketball 1500
Swimming 750
OR
def Push(EventDetails):
163
BigEvents=[]
count=0
for i in EventDetails:
if EventDetails[i]>200:
BigEvents.append(i)
count+=1
print(“The count of elements in the stack is”,count)
SECTION-D
31 Ans. (i) Academics because it has maximum number of computers 5*1
. (ii) Star topology (any appropriate block diagram)
(iii) Switch need to be installed in each of the block
(iv) VoIP
(v) Repeater/Amplifier
32 Ans. (a) 2+3
. 10 # 5
10 # 10
20 # 10
20 # 20
Ans: (b)
Statement 1:
con.cursor()
Statement 2:
mycursor.execute(query)
Statement 3:
con.commit()
OR
Ans. (b)
Statement 1: con.cursor()
Statement 2: mycursor.execute(“select Name from items where
price>100”)
Statement 3: mycursor.fetchall()
33 (a) Comma separated value 5
. (b) (i)
def InsertRow():
import csv
f=open("class.csv","a+",newline="")
rno=int(input("Enter roll no. :"))
name=int(input("Enter name :"))
marks=int(input("Enter marks :"))
wo=csv.writer(f)
wo.writerow([rno, name, marks])
f.close()
(b)(ii)
def COUNTD():
import csv
count=0
164
f=open("class.csv","r")
ro=csv.reader(f)
for i in ro:
if i[2]>75:
count+=1
return count
OR
Which statement will be used to create a csv writer object in Statement 2.
(vi) Choose the correct option for Statement 3 to write the names
of the column headings in the CSV file, BOOKS.CSV.
(vii) Which statement will be used to read a csv file in Statement
4.
(viii) Fill in the appropriate statement to check the field Title
starting with ‘R’ for Statement 5 in the above program.
(i) a
(ii) csv.writer(csvf)
(iii) cw.writerow(['Title','Author','Price'])
(iv) csv.reader(csvf)
(v) r[0][0]=='R'
SECTION-E
34 Ans. (i) ItemNo 1+1
. (ii) Cardinality=5 and Degree=8 +2
(iii)
a) Insert into Store values (2022, ‘Diary’, 23, 10, 250, ‘2022-OCT-18’);
b) Update Store
Set Rate=Rate+(Rate*0.05)
Where Item like ‘G%’;
OR
iii) Delete From Store where rate<10;
b) Alter table Store Add column (Remarks Varchar(50));
35 (i) F= open("STUDENT.DAT",'wb') 1
. (ii) pickle.dump(L,F) 1
(iii) R = pickle.load(F) 1
(iv) Total / Countabove75 1
165
Computer Science (083)
CBSE Sample Question Paper with marking scheme
Class: XII
Session: 2022-23
Maximum Marks: 70 Time Allowed: 3 hours
SECTION A
(1 mark to be awarded for every correct answer)
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: (d) Real
3. Given the followingdictionaries 1
dict_exam={"Exam":"AISSCE", "Year":2023} 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)
4. Consider the given expression: 1
not True and False or True
Which of the following will be correct output if the given expression isevaluated?
a. True b. False c. NONE d.NULL
Ans: (a) 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 . 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
6. Which of the following mode in file opening statement results or generates an 1
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 a table in SQL.
(a) update (b)remove (c) alter (d)drop
Ans: (c) alter
166
8. Which of the following commands will delete the table from MYSQL 1
database?
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 the 1
following code?
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. a. Statement 3 b. Statement 4 c. Statement 5 d. Statement 4 and 5
Ans: (b) – Statement 4
10. Fill in the blank:
is a non-key attribute, whose values are derived from the primary
keyof some other table.
a. Primary Key b. Foreign Key c. Candidate Key d. Alternate Key
Ans: (b) Foreign Key
167
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true 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
17. Assertion (A):- If the arguments in a function call statement match the number 1
and order of arguments as defined in the function definition, such argumentsare
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
18. Assertion (A): CSV (Comma Separated Values) is a file format for data storage 1
which looks like a text file.
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 2
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
(½ mark for each correct correction made and underlined.)
20 Write two points of difference between Circuit Switching and Packet Switching. 2
168
OR
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
(1 mark for each correct difference - Any two)
21 a. Given is a Python string declaration:
myexam="@@CBSE Examination 2022@@"
Write the output of: print(myexam[::-2])
Ans: @20 otnmx SC@
(1 mark for the correct answer)
b. 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')])
(1 mark for the correct answer)
169
22 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
TRAINERtable but foreign key in COURSE table.
COURSE
Ans: 22 # 40 # 9 # 13 #
(½ mark for the correct digit with a #)
OR
170
Predict the output of the Python code given below:
B. Write the output of the queries (i) to (iv) based on the table,
TECH_COURSE given below:
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 anyvowel: ", count)
file.close()
COUNTLINES()
( ½ mark for correctly opening and closing the file
½ for readlines()
½ mar for correct loop
½ for correct if statement
½ mark for correctly incrementing count
½ mark for displaying the correct output)
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
173
(½ mark for correctly opening and closing the file
½ for readlines()
½ mark for correct loops
½ for correct if statement
½ mark for correctly incrementing counts
½ mark for displaying the correct output)
Note: Any other relevant and correct code may be marked
28 (a) Write the outputs of the SQL queries (i) to (iii) based on the relations
Teacher and Placement given below:
Table : Teacher
Ans:
stackItem=[]
def Push(SItem):
count=0
for k in SItem:
if (SItem[k]>=75): stackItem.append(k)
count=count+1
print("The count of elements in the stack is : ",count)
176
i. Suggest the most appropriate block/location to house the SERVER inthe
Kashipur campus (out of the 3 blocks) to get the best and effective
connectivity. Justify your answer.
Ans: Movie editing block is the most appropriate to house the server asit has the
maximum number of computers.
(1/2 mark for naming the server block and ½ mark for correct reason.)
ii. Suggest a device/software to be installed in the Kashipur Campus totake care of
data security.
Ans: Firewall(1 mark for the correct answer)
iii.Suggest the best wired medium and draw the cable layout (Block to Block) to
economically connect various blocks within the Kashipur Campus.Ans: Ethernet
Cable Layout:
177
v.Suggest the protocol that shall be needed to provide Video Conferencingsolution
between Kashipur Campus and Mussoorie Campus.
Ans: Protocol: VoIP (1 mark for the correct answer)
Ans:
Statement 1:
con1.cursor()
Statement 2: mycursor.execute(querry)
Statement 3:con1.commit()
(1 mark for each correct answer)
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
(1 mark for first 5 characters, 1 mark for next 5 characters)
b. The code given below reads the following record from the table named
studentand displays only those records who have marksgreater 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
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 studentinthe
database.
import mysql.connector as mysqldef
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
179
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()
( 1 mark for each correct statement)
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:
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
mobileto store employee id, employee name andemployee 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] --------
-1/2 mark
wr.writerow(lst) ---------1/2 mark
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
()
(1 mark for advantage ½ mark for importing csv module 1 ½ marks each for
correct definition of ADD() andCOUNTR() ½ mark for function call statements)
OR
Give any one point of difference between a binary file and a csv file.
180
Write a Program in Python that defines and calls the following user defined
functions:
(1 mark for difference ½ mark for importing csv module 1 ½ marks each for
correct definition of add() andsearch() ½ mark for function call statements )
SECTION-E
181
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 creationof the
table, he has entered data of 7 students in the table.
Table: RESULT
182
35 Aman is a Python programmer. He has written a code and created a binary file
record.datwith employeeid, ename and salary. The file contains 10records.
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 messageshould 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 beenupdated.")
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(1 mark for correct module)
ii. Write the correct statement required to open a temporary file named
temp.datfor writing the updated data. (Statement 2)
Ans: fout=open(‘temp.dat’, ‘wb’)(1
mark for correct statement)
iii. Which statement should Aman fill in Statement 3 to read the data
from the binary file, record.datand in Statement 4 to write theupdated
data in the file, temp.dat?
Ans: Statement 3: pickle.load(fin)
Statement 4: pickle.dump(rec,fout)
(1 mark for each correct statement)
183