Studymaterial Cs Xii 2022 23 Robbsr
Studymaterial Cs Xii 2022 23 Robbsr
BHUBANESWAR REGION
PATRON
COORDINATOR
SH. S. K. DASH
VICE PRINCIPAL, KV NO.3, BHUBANESWAR
AND PRINCIPAL I/C, KV, NAYAGARH
ASSOCIATE COORDINATOR
CONTENT CONTRIBUTION
2
INDEX
S. NO. NAME OF THE CHAPTER/UNIT PAGE NO
1 REVIEW OF PYTHON 7 - 19
2 FUNCTIONS 20 - 27
4 DATA STRUCTURE 35 - 39
5 COMPUTER NETWORKS 40 - 64
3
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
5. Practical
5
6. Suggested Practical List:
Python Programming
● Read a text file line by line and display each word separated by a #.
● Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file.
● Remove all the lines that contain the character 'a' in a file and write it to another file.
● Create a binary file with name and roll number. Search for a given roll number and display the name, if not
found display appropriate message.
● Create a binary file with roll number, name and marks. Input a roll number and update the marks.
● Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
● Write a Python program to implement a stack using list.
● Create a CSV file by entering user-id and password, read and search the password for given user- id.
Database Management
● Create a student table and insert data. Implement the following SQL commands on the student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
● Similar exercise may be framed for other cases.
● Integrate SQL with Python by importing suitable module.
8. Project
The aim of the class project is to create something that is tangible and useful using Python file handling/
Python-SQL connectivity. This should be done in groups of two to three students and should be started by
students at least 6 months before the submission deadline. The aim here is to find a real world problem that is
worthwhile to solve.
Students are encouraged to visit local businesses and ask them about the problems that they are facing. For
example, if a business is finding it hard to create invoices for filing GST claims, then students can do a project
that takes the raw data (list of transactions), groups the transactions by category, accounts for the GST tax
rates, and creates invoices in the appropriate format. Students can be extremely creative here. They can use a
wide variety of Python libraries to create user friendly applications such as games, software for their school,
software for their disabled fellow students, and mobile applications, of course to do some of these projects,
some additional learning is required; this should be encouraged. Students should know how to teach
themselves.
The students should be sensitised to avoid plagiarism and violations of copyright issues while working on
projects. Teachers should take necessary measures for this.
6
REVIEW OF PYTHON
Introduction to Python
• Python is a free and open-source, object-oriented, high-level programming language
developed by Guido van Rossum in 1990.
• Python is easy to learn and use, interactive, portable programming language.
• Python is Dynamic Typing, does not need type declaration, variable assumes data type based on
value assigned
• It is an interpreted language, as Python programs are executed by an interpreter.
• Python is case-sensitive. For example, NUMBER and number are not same in Python.
• There are two ways to use the Python interpreter: Interactive mode and Script mode
Tokens(Lexical unit)
Smallest individual unit of a python program. There are 5 types of Tokens in Python.
i) Keyword
ii) Identifiers
iii) Literals
iv) Operators
v) Punctuators
1. Keywords- Keywords are reserved words which conveys the special meaning to the Python interpreter.
List of keywords in Python is given in Appendix-1
2. Identifiers-Names given to any variable, constant, function or module etc. The rules for naming an
identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
• This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_).
• No special symbols can be used except underscore _ in identifiers. An identifier should not start with
a digit.
• Keyword can’t be used as an identifier.
String literals:
A string literal is a group of Characters surrounded by a single(‘’), double(“ ”), or triple quotes.
Example:
# in single quote
7
s = 'Hello Welcome to KVS'
# in double quotes
t = "'Hello Welcome to KVS "
# in tripple quotes
t = "'Hello\
Welcome to\
KVS "
# multi-line String
m = '''geek
for
geeks'''
Numeric literals:
They are immutable and there are three types of numeric literal: Integer, Float , Complex
Integer literal:
Both positive and negative whole numbers without fractional part. It can be written in Decimal, Binary,
Octal and Hexadecimal format.
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)
Output
20 50 208 299
Complex literal :
The numerical will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part.
Example:
z = 7 + 5j
k = 7j
print(z, k)
OUTPUT:
(7+5j) 7j
Boolean literal:
There are only two Boolean literals in Python. They are True and False. In Python, True represents
the value as 1 and False represents the value as 0.
8
Example:
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7
print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)
OUTPUT:
a is True
b is False
c: 4
d: 7
Special literal:
Python contains one special literal (None). ‘None’ is used to define a null variable. If ‘None’ is
compared with any variable other than a ‘None’, it will return False.
Example:
EMPTY = None
VAR=10
if VAR != None:
print(“TRUE”)
print (EMPTY)
Output:
TRUE
None
Data types ( Type of data ) - Provide information about domain of values and operations that can be
performed on data.
Type Value
bool True or False
int Whole number
float Numbers with fractional part
9
complex Numbers having real and imaginary part( x+yj)
string text enclosed in single or double quote
list list of comma separated values of any data type between square [ ]
brackets
tuple list of comma separated values of any data type between parenthesis ( ) .
dictionary Unordered set of comma-separated key:value pairs , within braces { }
Strings
• Strings are homogeneous sequence of characters, represented by enclosing within single, double or
triple quotes.
• String is immutable. String elements cannot be changed in-place.
• Characters in a String are indexed and can be accessed by their position - forward indexing 0 to
len(String)-1 and backward indexing from -1 to -len(String)
• Strings can be manipulated using operators like concatenation (+), repetition (*) and membership (in
and not in).
Example
s = 'Welcome to KVS'
forward indexing 0 1 2 3 4 5 6 7 8 9 10 11 12 13
W e l c O m e t o K V S
backward indexing -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Lists
• A list is a heterogeneous sequence of data values (items) of same or different type
within square brackets.
• Lists are mutable. List elements can be accessed using index. Indexing is similar to
string – both forward and backward indexing is used.
• List may be Empty list, Long List, Nested List
Examples:
L=[ ] #empty List
L=[12,35,68,90]
L=[123, “Hello”, 6.8]
Examples:
T=( ) #empty tuple
T=10,
T=(10,)
T=(123, “Hello”, 6.8)
Dictionary
• Python Dictionaries are unordered collection of key:value pairs and are represented by
enclosing within braces {}
• Dictionaries are mutable (values can be changed, however keys should be
immutable type)
Examples:
D1={ } # empty dictionary
D2 = dict( ) # empty dictionary
D3 = { 1: “Rohan”, 2: “Sohan”, 3:”Mohan” }
D4={'empno':1,'name':'Shivam','dept':'sales', 'salary':25000}
1 Mark Questions
6. Which of the following statement(s) would give error on executing the following code?
T=(10, "Harish" , 2500) #Statement1
S="Thank you" #Statement2
T=T+("Odisha" , "Hockey") #Statement3
S=S+T #Statement4
print(S,T) #Statement5
(a) Statement 3
(b) Statement 4
(c) Statement 5
(d) Statement 4 and 5
10. Identify the valid arithmetic operator in Python from the following.
a) & b) = c) ** d) or
11. Suppose a tuple T is declared as T = (10, 13, 63, 39), which of the following isincorrect?
a) print(T[1])
b) T[2] = -51
c) print(max(T))
d) print(len(T))
13
12. Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values are Monday,
Tuesday and Wednesday respectively.
13. Name the built-in mathematical function / method that is used to return absolute value of a
number.
14. If the following code is executed, what will be the output of the followingcode?
name="Computer Science with Python"
print(name[-2:-10:-2])
17. Name the Python Library modules which need to be imported to invoke the following functions:
(i) tan() (ii) randrange ()
19. Find and write the output of the following python code:
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
23. List L is defined as L=[1,2,3,4,5], Which of the following statement/statements removes the middle
element 3 from it so that the list L equals [1,2,4,5] ?
(a) del L[2] (b) L[2:3] = [ ] (c) L[2 : 2]=[ ] (d) L[ 2 ] = [ ] (e) L.remove(3)
14
24. Identify the invalid logical operator in Python from the following.
a) and b) or c) not d)booean
25. __________method of list is used to delete a given element from the list.
(i) del (ii) pop(0 ) (iii) remove( ) (iv) pop( )
26. If the following code is executed, what will be the output of the following code?
Title="Python Programming Language"
print(Title[5:9], Title[-2:-6:-1])
(a) n Pr gaug (b) Error (c) n Pro gaug d) n Pro guag
29. Suppose list1 is [12, 33, 22, 14, 25], What is list1[:-1]?
a) [12, 33, 22, 14] b) Error c) 25 d) [25, 14, 22, 33, 12]
32. Suppose d = {“john”:40, “peter”:45}, to delete the entry for “john” which command do we use?
a) d.delete(“john”:40) b) d.delete(“john”)
c) del d[“john”] d) del d(“john”:40)
41. What will be the output of the following Python code snippet?
print(‘abcdefcd’.replace(‘cd’,’12’))
a) ab12ef12 b) abcdef12 c) ab12efcd d) None
42. A=[12,23,[20,30],[27,56,4],30]
A.remove(30)
print(A[:2:-1])
44. dc1={}
dc1[2]=6
dc1['10']=2
dc1[2.0]=5
s=0
for i in dc1:
s+=dc1[i]
print(s)
47. mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
print(mydict.keys())
print(mydict.values())
48. d1={1:100,2:200,3:300,4:400}
d2={1:111,2:222,5:555,4:444}
d1.update(d2)
print(d1)
49. key=('Eno','Ename','Sal')
value=[1]
value.append(2)
d1=dict.fromkeys(key,value)
print(d1)
2 Mark Questions
8. Rewrite the following code in Python after removing all syntax error(s).Underline each correction
done in the code.
val = input("Value:")
adder = 0
for C in range(1,Val,3)
adder+=C
if C%2=0:
print (C*10)
else:
print (C*)
18
print (adder)
9. Rewrite the following code in Python after removing all syntax error(s).Underline each correction
done in the code.
25=Val
for I in the range(0,Val)
if I%2=0:
print( I+1)
Else:
print (I‐1)
19
FUNCTIONS
Functions – Need and Benefits:
• Large programs are often difficult to manage, thus large programs are divided into smaller units
known as functions.
• A function is simply a group of statements under any name i.e. function name and can be invoked
(call) from other part of program.
• Set of functions is stored in a file called MODULE and the process of diving program into
manageable units called functions is known as MODULARIZATION, makes program easier to
understand, test and maintain.
• Commonly used modules that contain source code for generic need are called LIBRARIES.
• Modules contains set of functions. Functions is of mainly two types:
o Built-in Functions
o User-Defined Functions
Built-in functions: Built in functions are the function(s) that are built into Python and can be accessed by a
programmer. These are always available and for using them, we don’t have to import any module (file).
Name of the function Description Example
abs (x) It returns distance between x and zero, >>>abs(-45)
where x is a numeric expression. 45
>>>abs(119)
119
max( x, y, z, .... ) It returns the largest of its arguments: >>>max(80, 100, 1000)
where x, y and z are numeric 1000
variable/expression. >>>max(-80, -20, -10)
-10
min( x, y, z, .... ) It returns the smallest of its arguments; >>> min(80, 100, 1000)
where x, y, and z are numeric 80
Variable/expression. >>>min(-80, -20, -10)
-80
range(start, stop[, This is a versatile function to create >>> range(10)
step]) lists containing arithmetic progressions. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
It is most often used in for loops. The >>> range(1, 11)
arguments must be plain integers. If the [1,2, 3, 4, 5,6, 7, 8, 9, 10]
step argument is omitted, it defaults to >>>range(0, 30, 5)
1. If the start argument is omitted, it [0, 5, 10,15,20, 25]
defaults to 0. The full form returns a list >>> range(0, 10, 3)
of plain integers [start,start + step, start [0,3, 6, 9]
+ 2 * step, ...]. Step must not be zero >>> range(0, -10, -1)
(or else Value Error is raised). [0,-1,-2, -3, -4, -5, -6, -7, -8, -
9]
>>> range(0)
[]
>>> range(1, 0)
[]
round( x [, n] ) It returns float x rounded to n digits >>>round(80.23456, 2)
from the decimal point, where x and n 80.23
are numeric expressions. If n is not >>>round(-100.000056, 3)
provided then x is rounded to 0 decimal -100.0
digits. >>> round (80.23456)
80
20
User Defined Functions:
A function is a set of statements that performs a specific task. a common structuring element that allows you
to use a piece of code repeatedly in different part of program. Functions are also known as sub-routine,
methods, procedure or subprogram.
Syntax to create USER DEFINED FUNCTION
def function_name([comma separated list of parameters]):
statements….
statements….
KEYWORD FUNCTION DEFINITION
Points to remember
• Keyword def marks the start of function header
• Function name must be unique and follows naming rules same as for identifiers
• Function can take arguments. It is optional
• A colon(:) to mark the end of function header
• Function can contains one or more statement to perform specific task
• An optional return statement to return a value from the function.
• Function must be called/invoked to execute its code
User Defined function can be of following types:
1. Function with no arguments and no return
2. Function with arguments but no return value
3. Function with arguments and return value
4. Function with no argument but return value
Parameters and Arguments in Function
o Parameters are the value(s) provided in the parenthesis when we write function header. These
are the values required by function to work
o If there are more than one parameter, it must be separated by comma(,)
o An Argument is a value that is passed to the function when it is called. In other words
arguments are the value(s) provided in function call/invoke statement
o Parameter is also known as FORMAL ARGUMENTS/PARAMETERS
o Arguments is also known as ACTUAL ARGUMENTS/PARAMETER
o Function can alter only MUTABLE TYPE values
Types of Arguments
o There are 4 types of Actual Arguments allowed in Python:
▪ Positional arguments
▪ Default arguments
▪ Keyword arguments
▪ Variable length arguments
Rules for combining all three type of arguments
o An argument list must first contain positional arguments followed by keyword arguments
o Keyword arguments should be taken from the required arguments
o You cannot specify a value for an argument more than once
Scope of Variables : SCOPE means in which part(s) of the program, a particular piece of code or data is
accessible or known. In Python there are broadly 2 kinds of Scopes:
o Global Scope
o Local Scope
Global Scope : A name declared in top level segment(__main__) of a program is said to have global
scope and can be used in entire program. Variable defined outside all functions are global variables.
Local Scope : A name declare in a function body is said to have local scope i.e. it can be used only
within this function and the other block inside the function. The formal parameters are also having
local scope.
21
Multiple choice Questions (1 mark)
1. Which of the following keyword is used to define a function
a. def b. define c. definition d. none of above
2. How is a function declared in Python?
a. def function function_name():
b. declare function function_name():
c. def function_name():
d. declare function_name():
3. Write the output of the following:
a=(10, 12, 13, 12, 13, 14, 15)
print(max(a) + min(a) + a.count(2))
a. 13 b. 25 c. 26 d. Error
4. Find the output of the following:
a=10
y=5
def myfunc ():
y=a
a=2
print("y=",y, "a=",a)
print ("a+y=", a+ y)
return a+ y
print ("y=",y, "a=",a)
print(myfunc())
print("y=",y, "a=",a)
a. y= 5 a= 10 b. y= 10 a= 5 c. y= 5 a= 12 d. No Output (Error)
5. _________________ can be defined as a named group of instructions that accomplish a specific task
when it is invoked/ called.
a. Function b. Datatype c. Token d. Operator
a. 16 b. 18 c. 27 d. 24
13. A variable that is defined inside any fuction or a block is known as a _______
a. Global variable
b. Local Variable
c. Function Variable
d. Inside Variable
15. Which of the following number can never be generated by the following code:
random.randrange(0,100)
a. 0 b. 1 c. 99 d.100
18. Amar wants to import only sqrt() function of math module. Help him to write the correct code.
23
a. import math
b. from math import sqrt
c. import sqrt from math
d. import sqrt
19. Which of the fllowing options can be the output for the following code?
import random
List=[“Delhi”,”Mumbai”,”Chennai”,”Kolkata”]
for y in range(4):
x=random.randint(1,3)
print(List[x],end=”#”)
a. Delhi#Mumbai#Chennai#Kolkata
b. Mumbai#Chennai#Kolkata#Mumbai#
c. Mumbai#Mumbai#Mumbai#Delhi#
d. Mumbai#Mumbai#Chennai#Mumbai#
1. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program
from the following code? Also specify the maximum values that can be assigned to each of the
variables FROM and TO.
import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”#“)
(i) 10#40#70# (ii) 30#40#50#
(iii) 50#60#70# (iv) 40#50#70#
5. Rewrite the following code is Python after removing all syntax errors(s). Underline each correction
done in the code.
def display()
for Name in [Ramesh, Suraj, Priya]
if Name [0] = ‘S’:
Print (Name)
6. Observe the following Python code very carefully and rewrite it after 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)
execmain()
9. Write definition of a method/function DoubletheOdd(Nums) to add and display twice of odd values
from the list of Nums.
For example :
If the Nums contains [25,24,35,20,32,41]
The function should display
Twice of Odd Sum: 202
10. Write definition of a method/function AddOddEven(VALUES) to display sum of odd and even
values separately from the list of VALUES.
For example : If the VALUES contain [15, 26, 37, 10, 22, 13] The function should display Even
Sum: 58 Odd Sum: 65
11. Write a function OCCURRENCE() to count occurrence of a character in any given string. here
function take string and character as parameters.
12. Write a Python function to search an element in a list using binary search.
14. Find and write the output of the following python code:
def fun(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:
26
m=m+'bb'
print(m)
fun('school2@com')
16. Write a python function showlarge() that accepts a string as parameter and prints the words whose
length is more than 4 characters.
Eg: if the given string is “My life is for serving my Country” The output should be
serving
Country
27
DATA FILE HANDLING
• FILE HANDLING is a mechanism by which we can read data of disk files in python program or
write back data from python program to disk files.
• So far in our python program the standard input in coming from keyboard an output is going to
monitor i.e. no where data is stored permanent and entered data is present as long as program is
running BUT file handling allows us to store data entered through python program permanently in
disk file and later on we can read back the data
• It contains data pertaining to a specific application, for later use.
• The data files can be stored in two ways –
o Text File
o Binary File
Text File
o Text file stores information in ASCII OR UNICODE character. In text file everything will be
stored as a character for example if data is “computer” then it will take 8 bytes and if the data
is floating value like 11237.9876 it will take 10 bytes.
o In text file each like is terminated by special character called EOL. In text file some
translation takes place when this EOL character is read or written. In python EOL is ‘\n’ or
‘\r’ or combination of both.
Binary files
o It stores the information in the same format as in the memory i.e. data is stored according to
its data type so no translation occurs.
o In binary file there is no delimiter for a new line
o Binary files are faster and easier for a program to read and write than text files.
o Data in binary files cannot be directly read, it can be read only through python program for
the same.
Opening File : File can be opened for either – read, write, append.
SYNTAX:
file_object = open(filename)
OR
file_object = open(filename, mode) default mode is “read”
28
w wb Write only If file not exists, file is
created If file exists, python
will truncate existing data
and overwrite the file.
a Ab Append File is in write mode only,
new data will be added to
the end of existing data i.e.
no overwriting. If file not
exists it is created
r+ rb+ Read and write File must exists otherwise
error is raised Both reading
and writing can take place
w+ wb+ Write and read File is created if not exists,
if exists data will be
truncated, both read and
write allowed
a+ ab+ Write and read Same as above but previous
content will be retained and
both read and write.
Closing file : As reference of disk file is stored in file handle so to close we must call the close()
function through the file handle and release the file.
Syntax: fileobj.close()
29
• If we want to write a structure such as list or dictionary to a file and read it subsequently we need to
use the Python module pickle.
• Pickling is the process of converting structure to a byte stream before writing to a file and while
reading the content of file a reverse process called Unpickling is used to convert the byte stream
back to the original format.
Steps to perform binary file operations
o First we need to import the module called pickle.
o This module provides 2 main functions:
▪ dump() : to write the object in file which is loaded in binary mode
Syntax :
dump(object_to_write, filehandle)
▪ load() : dumped data can be read from file using load() i.e. it is used to read object
from pickle file.
Syntax: object = load(filehandle)
30
Method 3 (direct from python programme):
1. import csv module
2. Use open() to open CSV file by specifying mode “w” or “a”, it will return file
object.
3. “w” will overwrite previous content
4. “a” will add content to the end of previous content.
5. Pass the file object to writer object with delimiter.
6. Then use writerow() to send data in CSV file
1. Which of the following statements correctly explain the function of tell() method?
a. tells the current position within the file.
b. tell the name of file.
c. move the current file position to a different location.
d. it changes the file position only if allowed to do so else returns an error.
2. Which of the following statements correctly explain the function of seek() method?
a. tell the current position within the file.
b. indicate that the next read or write occurs from that position in a file.
c. determine if you can move the file position or not.
d. move the current file position to a different location at a defined offset.
3. Which of the following command is used to open a text file “c:\temp.txt” in append-mode?
a. outfile = open(“c:/temp.txt”, “a”)
b. outfile = open(“c:\\temp.txt”, “ab”)
c. outfile = open(“c:\temp.txt”, “ab+”)
d. outfile = open(“c:\\temp.txt”, “a”)
4. Which of the following commands can be used to read “n” number of characters from a file using
the file object <file>?
a. file.read(n)
b. n = file.read()
c. file.readline(n)
d. file.readlines()
5. Which of the following commands can be used to read the entire contents of a file as a string using
the file object <tmpfile>?
a. tmpfile.read(n)
b. tmpfile.read()
c. tmpfile.readline()
d. tmpfile.readlines()
2. Write a Python program to count all the line having 'a' as last character
3. Write a method/function Count() to count numbers of words having 4 characters from a text file
“notes.txt”.
4. Write a function disp() to in python to read lines from a text file and display those lines starting with
‘G’ or ‘g’ along with line number from the text file “Story.txt”.
5. A text file contains alphanumeric text (say an.txt). Write a program that reads this text file and prints
only the numbers or digits from the file.
6. Write a function remove_lowercase( ) that accepts two filenames, and copies all lines that do not
start with a lowercase letter from the first file into the second.
11. A binary file “emp.dat” has structure [empid,empname]. Write a function delrec(empid) in python
that would read contents of the file “emp.dat” and delete the details of those employee number is
passed as argument.
13. write a program to add/insert records in file “data.csv”. Structure of record is roll number, name and
class.
14. Write a programme to display all the record from data.csv whose marks is more then 70. Format of
record stored in data.csv is rollno, name , class and marks
15. Amar is a Python programmer. He has written a code and created a binary file emprecord.dat with
employeeid, ename and salary. The file contains 10 records. He now has to update a record based on
the employee id entered by the user and update the salary. The updated record is then to be written in
the file temp.dat. The records which are not to be updated also have to be written to the file temp.dat.
If the employee id is not found, an appropriate message should to be displayed. As a Python expert,
help him to complete the following code based on the requirement given above:
33
except:
break
if found==True:
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement1)
(ii) Write the correct statement required to open a temporary file named temp.dat. (Statement 2)
(iii) Which statement should Aman fill in Statement 3 to read the data from the binary file, record.dat
and in Statement 4 to
(iv) write the updated data in the file, temp.dat?
34
DATA STRUCTURE
DATA STRUCTURE is physical implementation that clearly defines a way of storing, accessing and
manipulation of data stored in data structure. Every data structure has a specific way of insertion and
deletion like STACK work on LIFO i.e. all operation will take from one end i.e. TOP where as QUEUE
works on FIFO i.e. item inserted first will be removed first and new item will always added to the end
of QUEUE. In python we will use LIST as a data structure for implementation of stack.
OPERATIONS DESCRIPTION
INSERTION Addition of new data to data structure
DELETION Removal of data element from data structure
SEARCHING Finding specific data element in data structure
TRAVERSAL Processing all data elements one by one
SORTING Arranging data elements in ascending or descending order
MERGING Combining elements of two similar data structure to form a new
data structure.
Operation on Stacks:
• Stack( ): It creates a new stack that is empty. It needs no parameter and returns an empty stack.
• push(item): It adds a new item to the top of the stack.
• pop( ): It removes the top item from the stack.
• peek( ): It returns the top item from the stack but does not remove it.
• isEmpty( ): It tests whether the stack is empty.
• size( ): It returns the number of items on the stack
35
PUSH Operation:
• The process of adding one element or item to the stack is represented by an operation called
as the PUSH operation.
• The new element is added at the topmost position of the stack.
POP Operation:
• The process of deleting one element or item from the stack is represented by an operation
called as the POP operation.
Application of Stacks:
• It is used to reverse a word. You push a given word to stack – letter by letter and then pop letter
from the stack.
• “Undo” mechanism in text editor.
• Backtracking: This is a process when you need to access the most recent data element in a series of
elements. Once you reach a dead end, you must backtrack.
• Language Processing: Compiler’ syntax check for matching braces in implemented by using stack.
• Conversion of decimal number to binary.
• Conversion of infix expression into prefix and postfix.
• Quick sort
• Runtime memory management.
8. If the name of linear list of 10 elements is LIL, then its element will be referenced
a) LIL[0], LIL[1], LIL[2]………LIL[9]
b) LIL[0],LIL[1],LIL[2]………LIL[10]
c) LIL(0),LIL(1),LIL(2)………LIL(9)
d) LIL(0),LIL(1),LIL(2)………LIL(10)
9. what is searching?
a) Involves searching for the specified data element in a data structure.
b) it data structure means processing all the data elements of it .
c) Arranging data elements of a data structure in a specified order.
d) Combining elements of two similar data structures to form a new data structures of same type
10. Which search technique searches the given ITEM in minimum possible comparisons in a sorted
linear list.
a) Linear search
b) Binary search
c) Double search
d) trinary search
12. Python provides a __________ method that itself takes care of shifting of elements and removing
the corresponding material.
a) add
b) insort
c) remove
d) bisect
13. Lst=[[2,3,4],[22,32,43],[50,60,70],[9,10,11]]
what will be the output of
print(Lst[:2])
a)[1,2,3,4,5]
b)[[1,2],[3,4]]
c)[[2,3,4],[22,32,43]]
d)[[50,60,70],[9,10,11]]
37
14. What is the situation when one tries to push an item in stack that is full.
a) peek
b) underflow
c) overflow
d) pop
15. What is called when one tries to pop/delete an item from an empty stack.
a) peek
b) underflow
c) overflow
d) pop
4. Write the function sumAlternate(MYLIST) as argument and calculate the sum of all alternate
elements of MYLIST and print it
For e.g. if the elements are
[5, 11, 17, 19, 25, 29, 30, 32, 56, 90]
Output should be : Total=133
5. Write a function EvenOdd(MYLIST), which doubles each Odd elements of MYLIST and half each
Even element of MYLIST.
For e.g. if MYLIST = [10,11,40,4,17,23,45,100,80]
output should be [5,22,20,2,34,46,90,50,40]
7. Write a function in python, Push(Employee) and Pop(Employee) to add a new Employee and delete
a Employee from a List of Employee Names, considering them to act as push and pop operations of
the Stack data structure.
8. Write a Python function/method SwapMiddle(Codes) to swap the first half of the content of the list
Codes with second half of the list Codes and display the swapped values.
For e.g. if the list Codes contains : [22,44,55,66,88,11] then function should swap and display as:
[66,88,11,22,44,55]
9. Write a function in python, Push(Package) and Pop(Package) to add details of employee contain
information (Empid, Ename and Salary) in the form of tuple in Package and delete a Package from a
List of Package Description, considering them to act as push and pop operations of the Stack data
structure
39
COMPUTER NETWORKS
Introduction
Connections among computers makes computer networks. In a computer network, two or more autonomous
computing devices are connected to each other to exchange information orshare resources.
Advantages
• Resources such as printer, scanner, projector, etc. are shared among deviceswhich is cheaper than
buying separatelyfor each computer
• Software can be installed centrally ratherthan on each computer. It's cheaper thanbuying licenses for
every computer
• Shared storages can be used to accessfiles and data from any machine on thenetwork
Disadvantages
• Systems are more complex to run. Specialists might be required for managing which increases the
cost
• If networks are badly managed, it can become unusable and productivity mayfall
• If the central server fails, it becomes impossible for other machines to carryout any work.
• Files' security is harder to implement, e.g.protection from viruses
Network Basics
• Host or node or workstation refers to the computers/devices that are attached to thenetwork.
• A server is the computer which facilitates the sharing of data, software and hardware resourceson the
network. A server serves the requests ofthe clients.
• A client is a host computer thatrequests for services from a server.
• Other than wiring and computers, Network Hardware consists of : NIC(Network Interface Unit) :
Network Card connected to the host to establish networkconnections, Hub, Switch, Router.
• Hosts in a network interact with other hosts and server(s) through a Communication Channel which can
be:
Wired : When connections are through guided media like twisted-pair, coaxial, optical fiber.
Wireless : When connections are through unguided media like Microwaves, radio waves,
satellites, infrared waves, lasers etc.
Types of Networks
Local Area Network (LAN)
Small computers networks that are confined to a localized area. Data, information,
programs,printers, storage, modems, etc. are shared.
e.g. office, building, industry.
Wide Area Network (WAN)
These networks spread across countries or on a very big geographical area. It can even be
agroup of LANs that are spread across several locations. Internet is the largest WAN.
Metropolitan Area Network (MAN)
These networks spread across an area as big as a city. Now, this term has become
redundant.WAN is generally used.
40
Personal Area Network(PAN)
It's an interconnection of devices within the range of an individual person, typically within
a range of 10m.
Wired Networks
As the name suggests hosts and other devices are connected by wires or cables. Mostly used
in LANs. Although, these days there are wireless LAN too.
a. Twisted Pair Cable : It's a pair of insulated wires that are twisted together to improve
electromagnetic capability and to reduce noise from outside sources.
These are available in CAT1, CAT2, CAT3, CAT4, CAT5, CAT6.
b. Coaxial Cable(coax) : It consists of a solid wire core surrounded by one or more foilor wire
shields, each separated by some kind of plastic insulator.
Most commonly used are thicknet, thinnet.
c. Fiber Optic Cable/ Optic Fiber Cable : It consists of a bundle of glass threads, eachthread is
capable of transmitting information modulated onto light waves.
Common Fiber Optic Cables are single node and multi-node.
Wireless Networks
Information is transferred using electromagnetic waves like IR(Infrared), RF(Radio frequencies),
satellite, etc. through environment/air as the media.
Wi-fi in home is an example of Wireless LAN. Satellites are used for Wireless WAN.Most
commonly used transmission media in wireless networks are :
a. Microwave : These are high frequency waves that can be used to transmit data overlong
distances. There's a transmitter, receiver & atmosphere.
e.g. Mobile phone calls
b. Radio waves : These are waves of frequency range 30Hz - 300GHz, used to transmit
television & radio. All radios use continuous sine waves to transmit information.
e.g. Wi-Fi also uses radio waves to transmit between devices and router.
c. Satellite(Satellite Microwave) : It's a microwave relay system which uses synchronoussatellite
to relay the radio signal transmitted from ground station. Communication satellites owned
by both govt. and pvt. organizations have been places in stationary orbits about 22,300
miles above the earth's surface. Satellite accepts signals transmitted from earth station,
41
amplify them, and return them to another earth station. It's used when we need to transmit data
over a very large distance.
d. Infrared : It uses infrared light to send data. This is found in everyday life - TV remotes,
automatic doors, wireless speakers. It transmits data through the air and canpropogate
throughout a room(bouncing off surfaces), but can't penetrate walls. It's become common in
PDAs (Personal Digital Assistant). It's considered to be a secure one.
e.g. hand held devices like palm pilots, etc.
Switching Techniques
1. Circuit Switching
The complete physical connection between two computers is established and then data is transmitted from
the source computer to the destination computer. A proper end-to-end path (connection) using a physical
copper wire is made.
2. Message Switching
Source computer sends data or the message to the switching office first, which stores the datain its
buffer. It then looks for a free link to another switching office and then sends the data to this office. This
process is continued until the data is delivered to the destination computers.
This is also known as store and forward.
3. Packet Switching
In Message switching, there's no limit on block size. Packet switching places a tight upper limiton block
size. Also in message switching, data packets are stored on the disk in message switching whereas in
packet switching, all packets of fixed size are stored in main memory.
This improves the performance as the access time is reduced, thus the overall performance of the
network is improved.
Bandwidth
Bandwidth(Width of allocated band of frequencies) is the difference between the highest and lowest
frequencies. High bandwidth channels are called Broadband. Low bandwidth channels are called
narrowband channels. It's unit is Hertz(same as frequency) which represents cycles per second. A
kilohertz(KHz) represents a thousand Hertz(Hz).
1 MegaHertz(MHz) = 1000 KiloHertz(KHz)
1 GigaHertz(GHz) = 1000 MegaHertz(MHz)
1 TetraHertz(THz) = 1000 GigaHertz(MHz)
Network Topology
The pattern of interconnection of nodes in a network is called Network Topology.
Star topology
42
It consists of a central node to which all other nodes are connected by a single path.
e.g. data processing, voice communication, etc.
• It is easy to install and wire.
• If one node fails, network stays stable.
• Connecting or removing devices doesn't affect the network.
• Diagnosis is easy.
Disadvantages
• Requires more cable length.
• If hub, switch, or concentrator fails, nodes attached are disabled.
More expensive than linear topology.
Mesh Topology
Each node is connected to more than one node, which provides and alternative route in thecase host
is either down or busy. It's excellent for long distance networking as it provides back-up &
rerouting which is ideal for distributed networks.
• Each connection can carry its own data load.
• It can mange high traffic as multiple devices can transmit work simultaneously.
• It's robust, provides security and privacy.
• Diagnosis is easy.
• Installation, configuration & Management is difficult.
Bulk wiring is required, cables cost is more.
• Chances of redundancy is high which leads to higher cost and lower effeciency.
43
Tree or Expanded Star Topology
It's the combination of linear bus and star topologies. Groups of star-configured workstations
connected to a linear bus backbone.
• It provides high security.
• Scalability is high as more leaf nodes(star-configured nodes) can be added.It uses point-to-
point wiring for individual segments.
• It's supported by several hardware and software vendors.If backbone
falls, individual star groups keep on working.
Disadvantages
• Overall cable length increases.
• If backbone falls all leaf nodes gets disconnected. Difficult to configure and wire than other
topologies. If hub, switch or concentrator fails, attached nodes gets disconnected.
NETWORK TERMINOLOGIES
NIC (Network Interface Card)
It's a special device attached to each node and the server which helps them establish all important
connections with the network. Each node's NIC has a unique number identifying it,known as the node
address.
NIC is also known as Terminal Access Point(TAP) or Network Interface Unit(NIU).
MAC address
Manufacturers assigns a unique physical address to each NIC card known as MAC address(Media
Access Control Address). It's a 6-byte address, each byte separated by a colon.
80 : 1A : 04 : 36 : 8E : 21
WiFi card
It's either an internal or external LAN(Local Area Network) adapter with a built-in wireless radioand
antenna. There are multiple types. Most common Wi-Fi cards used in desktop computers are PCI-
Express Wi-Fi cards made to fit the slot in motherboards.
44
MODEM(Modulator Demodulator)
This device is used to convert the digital signals into analog
signals(Audio Frequency tones)and vice versa. Mainly used to
connect telephone/radio lines to a computer terminal.
Internal modems are fixed within the computer. External
modems are connected externally as other nodes.
Ethernet Card
It's a NIC that connects a computer to a computer network. In most of t he new
computers the ethernet port is built into computer, whereas in the earlier
computer it was available on an expansion card that used to be plugged
into the motherboard.
Router
As the name suggests, it handles routes of the data packets. It's a networking device,
that forwards data packet between computer networks. This creates an overlay i
nternet connection which connects multiple independent networks. It's basic role
is to determine best possible route(shortest path) for the data packets to be
transmitted.
Hub
A hub is a connecting device which connects multiple computers together to form a LAN. It
connects multiple devices through RJ45 connectors in a star topology.
Signal entering any port is broadcasted out on all other ports.
Switch
It's a multi-ported device which connects multiple computers together
to form a LAN similarto hub, but switch is a smart hub. It has the
intelligence to send the data directly to the destination rather than broadcast
to whole network. Data packets received from one end are refreshed and
delivered to address of the destination.
Gateway
It's a device that connects dissimilar networks. As the name suggests it acts as an entrance toanother
network(maybe with different protocol structure). It's also called protocol converter as it convert data
packets from one protocol to other. It also conceals the IP address of the user sending out information,
outsiders can only see the IP address of the gateway.
Network Protocol
A protocol means the rules that are applicable for a network. It defines standardized formats for data
packets, techniques for detecting and correcting errors and so on. It's a formal description of message
formats and rules that devices must follow to exchange data seamlessly without any interruptions and
contradictions.
Remote Login(Telnet)
It's a program that allows user to establish a virtual terminal connection between two machines
using TCP/IP. It's an internet utility that lets you log onto remote computer systems.
Internet
It's a worldwide network of computer networks that evolved from the first network ARPANET. It's an
interconnection of large and small networks around the globe that allows all the computers to exchange
information with each other.
To accomplish connections between all computers there must be a common set of rules for
communication, known as protocols.
Wireless/Mobile Communication
It refers to the method of transferring information between devices without any physical
connection. e.g. Wi-Fi, Bluetooth, Radio Waves, etc.
46
GSM(Global System for Mobile communication) is a wide area wireless communications system that uses
digital radio transmission to provide voice, data, and multimedia communication services. It's one of the
leading digital cellular system. It uses TDMA(Time Division Multiple Access), which allows eight
simultaneous calls on the same radio frequency.
1G
1G networks(NMT, C-Nets, AMPS, TACS) are considered to be the first analog cellular systemsstarted
in 1980s. It was purely designed for voice calls with almost no consideration of data services.
2G(GSM)
2G networks(GSM, CDMAOne, D-AMPS) are the first digital cellular systems launched early 1990s,
offering improved sound quality, better security and higher total capacity. In CDMAtechnology,
data and voice packets are separated using codes and then transmitted using a wide frequency range.
2.5G
2.5G networks(GPRS, CDMA2000 1x) are enhanced versions of 2G networks with data rates upto
144kbps. GPRS offered first always-on data service.
3G
3G networks(UMTS FDD and TDD, CDMA2000 1x EVDO, CDMA2000 3x, TD-SCDMA, Arib
WCDMA, EDGE, IMT-2000 DECT) are 3rd generation wireless technologies with enhancements like
high-speed transmission, advanced multimedia access and global roaming. Stationary speedsof 2Mbps
and mobile speeds of 384kbps for a true 3G.
4G
4G is an improved version of 3G but only in terms of fast web-experience. It offers downlink data
rates over 100Mbps, low latency, very efficient spectrum use and low-cost implementations. It's also
referred as MAGIC(Mobile Multimedia, Anywhere, Global Mobility, Integrated Wireless & Customized
Services). 4G is convergence of wired and wireless networks, including GSM, WLAN and bluetooth as
well as computers, communication devices and others.
5G
5G is the fifth generation of broadband cellular networks began worldwide in 2019. 5G's service area
is divided into small geographical areas called cells. Devices in a cell are connectedto network by radio
waves through a local antenna in the cell. Greater bandwidth and higher download speeds eventually
47
upto 10Gbps. This increased speed is achieved partly by using higher frequency radio waves than
previous cellular networks. However they have a shorter range, requiring smaller geographic cells.
Mobile Processors
A mobile processor is a CPU chip designed for portable computers/mobile phones. It's typically housed
in a smaller chip package without fan, in order to run cooler it uses lower voltages than other
components. They have more sleep mode capabilities to conserve powerand prolonged battery life.
e.g. Qualcomm Snapdragon 865, Exynos 990, Apple A14, etc.
Chat
It's an application to communicate with a person, group on internet in real time by typing text. We type a
message in our device which is immediately received by the recipient, then recipient can respond to our
message, which is received by us immediately.
Video Conferencing
It's a two-way video conversation between two or more participants on the internet or a private
network. Each user has a video camera, microphone and speaker on his/her computer,participants
speak to one another, they hear each other's voices and see a video image of otherparticipants.
Wi-Fi(Wireless Fidelity)
Wi-Fi is a family of wireless network protocols, based on IEEE 802.11 family of standards, which are
commonly used for local area networking of devices and internet access. Wi-Fi is a trademarkof Wi-Fi
Alliance, it's not a technical term, alliance has enforced its use to describe only a narrowrange of
connectivity technologies including wireless local area network(WLAN).
WiMAX
WiMAX(Worldwide Interoperability for Microwave Access) is a family of wireless broadband
digital communication system. It can provide broadband wireless access(BWA) up to 50km for
fixed stations and 5-15km for mobile stations which is significantly larger than WiFi(30- 100m).
WiMax requires a tower called WiMax Base Station, similar to a cellphone tower, which is
connected to the Internet using a standard wired high-speed connection.
48
URL(Uniform Resource Locator)
URL is a complete web address used to find a particular web page. It depends on several factors such as
type of server or protocol, name/address of the server on the internet, location of the file on the server.
e.g. www.cbse.nic.in
Domain Name
Domain name is a component of a URL, it's the identification string that defines the name of theparticular
website.
Website
A website is a collection of web pages usually containing hyperlinks to each others representing
information of a company or individual on the World Wide Web. It's a location on a net server which has
a unique URL.
Web Browser
It's a client software that is used to access various kinds of internet resources using HTTP which also helps us
navigate through World Wide Web and display web pages.
e.g. Google Chrome, Mozilla Firefox, Opera, Safari, etc.
Web Servers
It's a computer that stores data and makes them available to rest of the world(Internet). Aserver may be
dedicated, meaning its sole purpose is to be a web server. A non-dedicated server can be used for
basic computing in addition to acting as a server. It responds to the requests made by web browsers.
Web Hosting
It's a service that allows user to upload and store a website's HTML documents and other data on a web
server. It makes the file available on the World Wide Web to be used by public. It's also known as
site hosting.
6 Central Computer which is more powerful than other computers in the network is called
_____________.
(a) Client
(b) Server
(c) Hub
(d) Switch
7 Network in which every computer is capable of playing the role of a client, or a server or
both at same time is called
(a) peer-to-peer network
(b) local area network
(c) dedicated server network
(d) wide area network
13 Hub is a
(a) Broadcast device
(b) Uni-cast device
(c) Multi-cast device
(d) None of the above
14 Switch is a
(a) Broadcast device
(b) Uni-cast device
(c) Multi-cast device
(d) None of the above
16 Protocols are
(a) Agreements on how communication components and devices are to communicate
(b) Logical communication channels for transferring data
(c) Physical communication channels used for transferring data
(d) None of above
18 A firewall is
(a) An established network performance reference point.
(b) Software or hardware used to secureagainstrd a private network from a public
network.
(c) A virus that infects macros.
(d) A predefined encryption key used to encrypt and decrypt data transmissions.
21 What factors should be considered when selecting the appropriate cable for connecting a
PC to a network? (Choose two)
(a) type of system bus
(b) motherboard model
(c) computer manufacturer
(d) distance of cable and speed of transmission
22 Which cable connectors are used to connect a cat6 cable from a router's console port to a
PC?
(a) RJ-11
(b) RJ-12
(c) RJ-45
(d) none
24 Which of the following devices can be used at the centre of a star topology?
(a) Router
(b) Repeater
(c) Modem
(d) Hub
25 Data is converted in a form so as to travel over telephone lines using this device.
(a) Modem
(b) Hub
(c) Switch
(d) Router
26 Network device that regenerates and retransmits the whole signal is _____.
(a) Modem
(b) Hub
(c) Repeater
(d) Bridge
29 Networks devices that sends the data over optimizing paths through connected hops is
(a) Hub
(b) Router
(c) Bridge
(d) Gateway
31 Which portion of the URL below records the directory or folder of the desired resource ?
http://www.somestore.com/firstfloor/shoes.htm
(a) http
(b) firstfloor
(c) shoes.htm
(d) www.somestore.com
53
37 A_______is a data communication system within a building, plant, orcampus, or between
nearby buildings.
a) MAN
b)LAN
c)WAN
d) None of the above
38 Bluetooth is an example of
a) Wide area network
b) Virtual private network
c) Local area network
d) Personal area network
42 Which of the following protocol is used for remote terminal connection service?
a) RARP
b) UDP
c) FTP
d) TELNET
44 It allows a visited website to store its own information about a user on the user’s
computer:
a) Spam
b)cookies
c)Malware
d)Adware
45 In which of the following switching methods, the message is divided into small
packets?
54
a) Message switching
b) Packet switching
c) Circuit switching
d) None of these
48 Which of the following cable consist of a solid wire core surrounded by one or more
foil or wire shields?
a) Ethernet Cables
b)Coaxial Cables
c)Fibre Optic Cables
d)Power Cable
Expanded form
1. ARPANET: Advanced Research Projects Agency NETwork
2. NSFnet: National Science Foundation network
3. Internet: Inter networking
4. TCP/IP: Transmission Control Protocol / Internet Protocol
5. NIU: Network Interface Unit
6. TAP: Terminal Access Point
7. NIC: Network Interface Card
8. MAC Address: Media Access Control Address
9. bps: bits per second
10. Bps: Bytes per second
11. kbps: kilo bits per second
12. Kbps: Kilo bytes per second
13. mbps: mega bits per second
55
14. Mbps: mega bytes per second
15. kHz: kilohertz
16. MHz: megahertz
17. GHz: gigahertz
18. THz: terahertz
19. LAN: Local Area Network
20. UTP: Unshielded Twisted Pair Cable
21. CAT1: Category 1 UTP cable (same acronym for other CATs)
22. STP: Shielded Twisted Pair Cable
23. LEDs: Light Emitting Diodes
24. LDs: Laser Diodes
25. PDAs: Personal Digital Assistants / Personal Data Assistant
26. WAN: Wide Area Network
27. MAN: Metropolitan Area Network
28. PAN: Personal Area Network
29. P-P link: Point to Point Link
30. Modem: Modulator – Demodulator
31. RTS: Request To Send
32. RJ-45: Registered Jack-45
33. DEC: Digital Equipment Corporation (company that made Ethernet)
34. RJ-11: Registered Jack-11
35. BNC: Bayone-Neill-Concelman
36. AUI connector: Attachment Unit Interface (15 pin connector)
37. subnets: subnetworks (also called LAN segments)
38. SNA: Systems Network Architecture
39. ISP: Internet Service Provider
40. OSI model: Open Systems Interconnection Model
41. IP address: Internet Protocol Address
42. FDDI networks: Fiber Distributed Data Interface networks
43. NOSS: Networking Operating System Software
44. ISDN: Integrated Services Digital Network
45. AP: Access Point
46. NFS: Network File System
47. HTTP: Hypertext Transfer Protocol
48. WWW: World Wide Web
49. URI: Uniform Resource Identifier
50. URL: Uniform Resource Locator
51. URN: Uniform Resource Name
52. MIME: Multipurpose Internet Mail Extensions
53. SMTP: Simple Mail Transfer Protocol
54. NNTP: Network News Transfer Protocol
55. FTP: File Transfer Protocol
56. PPP: Point to Point Protocols
57. GSM: Global System for Mobile communications
58. SIM: Subscriber Identification Module / Subscriber Identity Module
59. CDMA: Code-Divison Multiple Access
60. WLL/WiLL: Wireless in Local Loop
61. PBX: Private Branch Exchange
62. PSTN: Public Switched Telephone Network
63. GPRS: General Packet Radio Service
64. LTE: Long Term Evolution
65. SMS: Short Message Service
56
66. VoIP: Voice over Internet Protocol
67. Wi-Fi: Wireless Fidelity
68. WiMAX: Worldwide Interoperability for Microwave Access
69. EDGE: Enhanced Data rates for GSM Evolution
70. Telnet: Teletype Network
71. HTML: Hypertext Markup Language
72. DNS: Domain Name System
73. POP: Post Office Protocol
74. XML: eXtensible Markup Language
75. DHTML: Dynamic HTML
76. SSL: Secure Socket Layer
4.What is RJ 45 connector?
• Used with twisted pair cable
• Full form is Registered Jack
• Plugin to network devices
• Primarily for LANs
9. What is repeater?
• Repeater is a network device used to boost the signal.
• Used to boost the signals to send for long distance.
• Also known as signal booster.
• Its task is to amplify the signal.
MODEM stands for Modulator/Demodulator. It is device used to convert analog signal to digital signal
and vice versa. It is basically used to run internet on your computer/device.
RJ45 stands for Registered Jack 45. It is an 8 wire connector used to connect computers on a. LAN or
Ethernet Card.
A switch is a device used to interconnect computers on a network but it provides dedicated bandwidth to
all connected computers.
A bridge is a network device used to interconnect two networks that follow same protocols.
A router is a network device used to interconnect networks having different protocols. Router forwards
data from one computer to another by shortest path.
A WiFi card is an internal or external Local area network adapter with a builtin wireless radio and antenna.
23. Define the term bandwidth. Give any one unit of bandwidth.
Answer:
Bandwidth is referred as the volume of information per unit of time that a transmission medium (like an
internet connection) can handle.
OR
The amount of data that can be transmitted in a fixed amount of time is known as bandwidth. For digital
devices, the bandwidth is usually expressed in bits per second (bps) or bytes per second. For analog
devices, the bandwidth is expressed in cycles per second, or Hertz (Hz).
59
24. What is the difference between LAN and MAN?
Answer:
LAN: It is Local Area Network. The diameter is not more than a single building.
WAN: It is Metropolitan Area Network. LAN spans a few kms while MAN spans 5-50 km diameter and
is larger than a LAN.
Q1. An App. Development Company has set up its new center at Bhubaneswar for its office and web based
activities. It has 4 blocks of buildings named Block A, Block B, Block C, Block D.
a) Suggest the most suitable place (i.e. block) to house the server of this companywith a suitable reason.
b) Suggest the ideal layout to connect all the blocks with a wired connectivity.
c) Which device will you suggest to be placed/installed in each of these blocks to efficiently connect all the
computers within these blocks.
d) Suggest the placement of a repeater in the network with justification.
e) Suggest the best topology for block C if available hub/switch maximum number of port is 24.
Q2. AIIMS is setting up its center in Bhubaneswar with four specialized departments for Orthopedics,
Neurology and Pediatrics along with an administrative office in separate buildings. The physical distances
between these department buildings and the number of computers to be installed in these departments and
administrative office are given as follows.
You, as a network expert, have to answer the queries as raised by them in (i) to (iv).
Shortest distances between various locations in metres :
Administrative Office to Orthopedics Unit 55
Neurology Unit to Administrative Office 30
Orthopedics Unit to Neurology Unit 70
Pediatrics Unit to Neurology Unit 50
Pediatrics Unit to Administrative Office 40
Pediatrics Unit to Orthopedics Unit 110
Number of Computers installed at various locations are as follows
Pediatrics Unit 40
Administrative Office 140
Neurology 50
Orthopedics Unit 80
(i) Suggest the most suitable location to install the main server of this institution to get
efficient connectivity.
60
(ii) Suggest the best cable layout for effective network connectivity of the building having
server with all the other buildings.
(iii) Suggest the devices to be installed in each of these buildings for connecting computers
installed within the building out of the following:
• Switch
• Gateway
(iv) Suggest a device/software to be installed in the given network to take care of data security.
(v) Suggest an efficient as well as economic wired medium to be used within each unit for
connecting computer systems out of the following network cable : Co-axial Cable, Ethernet
Cable, Single Pair Telephone Cable.
Q3. Pixel Design and Training Institute is setting up its centre in Jodhpur with four specialised units for
Design, Media, HR and Training in separate buildings. The physical distances between these units and the
number of computers to be installed in these units are given as follows.
You as a network expert, have to answer the queries as raised by the administrator as given in (i) to (v).
Shortest distances between various locations in metres :
Design Unit to Media Unit 60
Design Unit to HR Unit 40
Design Unit to Training Unit 60
Media Unit to Training Unit 100
Media Unit to HR Unit 50
Training Unit to HR Unit 60
Number of computers installed at various locations are as follows :
Design Unit 40
Media Unit 50
HR Unit 110
Training Unit 40
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 building having
server with all the other units.
(iii) Suggest the devices to be installed in each of these buildings for connecting computers installed within
each of the units.
(iv) Suggest an efficient as well as economic wired medium to be used within each unit for connecting
computer systems out of the following network cable :
Co-axial Cable, Ethernet Cable, Single Pair Telephone Cable.
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between Jodhpur and
HQ which is situated in Delhi.
Q4. Dal-Tech is planning to start their offices in four major cities in India to provide regional IT infrastructure
support in the field of Education and Culture. The company has planned to setup their head office in New
Delhi in three locations and have name their New Delhi office as “Sales Office”, “Head Office” and “Tech
Office”. The company’s regional offices are located in “Coimbatore”, “Kolkata”, and “Ahmedabad”.
Approximate distance between these office as per network survey team is as follows:
a) Suggest network type for connecting each of the following set of their offices:
• Head Office and Tech Office
• Head Office and Coimbatore Office
b) Which device you will suggest to be procured by the company for connecting all the computers with in
each of their offices.
c) Which of the following communication media, you will suggest to be procured by the company for
connecting their local offices in New Delhi for very effective and fast communication.
Telephone Cable ii) Optical fibre iii) Ethernet cable
d) Suggest a Cable /Wiring layout for connecting the company’s local offices located in New Delhi.
e) Suggest the most suitable location to install the main server of this institution to get efficient connectivity.
Q5. Don Corporation is a professional IT company. The company is planning to set up their new offices in
India with its hub at Delhi. The company has 03 Block named Conference Block, Finance Block, and Human
Resource Block.
Suggest them the best available solutions based on the queries (i) to (v) as mentioned below :
Block to Clock distance in Meters :
• Human Resource to Conference Block – 55 mtr.
• Human Resource to Finance – 110 mtr
• Conference to Finance – 90 mtr.
No. of computers to be installed in each block :-
• Human Resource – 150
• Finance - 45
• Conference – 75
(i) What will be the most appropriate block, where Don Corporation should plan to house the
server?
(ii) Suggest the cable layout to connect all the buildings in the most appropriate manner for
efficient communication.
(iii) What will the best suitable connectivity out of the following to connect the offices in
Bangalore with its New York based office.
(a) Infrared (b) Satellite Link (c ) Ethernet Cable
(b) Suggest the placement of the following devices with justification.
(c) Hub / Switch (b) Repeater
(iv) Which service / protocol will be most helpful to conduct the live interactions of Experts from
New York to Human Resource Block.
(v) Suggest a device/software to be installed in the given network to take care of data security.
Hint/Answer Q1:
a) Block C. Reason: Highest number of computer.
b)
62
c) Switch
d) Between A and C, because length is more than 100 Mtrs.
e) Tree topology
Hint/Answer Q2:
(i) Administrative Office. Reason: Highest number of computer.
(ii)
(iii) Switch
(iv) Firewall
(v) Ethernet Cable
Hint/Answer Q3:
(i) HR Unit. Reason: Highest number of computer.
(ii)
(iii) Switch/Hub
(iv) Ethernet Cable
(v) VoIP (Voice over Internet Protocol)
Hint/Answer Q4:
a)
LAN : Head Office and Tech Office
WAN: Head Office and Coimbatore Office
b) Switch/Hub
c) Ethernet cable
d)
e) Head Office
Hint/Answer Q5:
(i) Human Resource. Reason: Highest number of computer.
(ii)
63
(iii) (b) Satellite Link
(iv) VoIP (Voice over Internet Protocol)
(v) Firewall
64
DATABASE MANAGEMENT
Introduction to database
• It is a collection of data about one particular enterprise (school, hospital, college, bank etc).
• It is basically a record keeping system, where all the data of the enterprise is stored at one place.
• Each application uses one or the other database at backend to store data generated by the app.
RDBMS terminology:-
• Relation- data arranged in rows and columns which is also known as a table.
• Tuple/record- row of a relation is known as a tuple/record.
• Attribute/ field- column of a relation is known as an attribute/field.
• Degree- number of attributes in a relation is called degree of a relation.
• Cardinality- number of tuples in a relation (excluding header row) is called cardinality of a relation
• Domain-it is set of valid values from which actual values appearing in a field are drawn.
eg. House color of a student in school
65
• Examples of commonly used RDBMS:
• Mysql
• Postgresql
• Sqlite
• Microsoft sql server
• Oracle
• Dbms tools for mobile devices:-
• Sqlite, sql anywhere, db2 everywhere, sqlbase
Exercise I:
• What is a primary key? Explain with an example. 2
• Define referential integrity. 2
• What is candidate and alternate key? Give an example 2
• Identify the degree and cardinality of the Student relation given below . 1
• Identify the foreign key in given below Student and Department relations. 1
66
SQL - STRUCTURED QUERY LANGUAGE
• SQL is a domain-specific language used in programming and designed for managing data held in
a relational database management system (Relational DBMS).
• SQL is essentially a declarative language (4GL), which emphasizes on “WHAT TO DO” rather than
“ HOW TO DO” (programming language).
• It is case insensitive.
• SQL consists of many types of statements, which may be classified as:-
UPDATE <table_name>
SET <column1>= <value1>, <column2> = <value2>
WHERE <condition>;
Eg:- UPDATE student
SET dob=“2001-12-27”
WHERE admn=1234;
7. The ALTER TABLE statement is used to add, delete, or modify columns in an existing table and
can also be used to add and drop various constraints on an existing table.
Eg1:- query to add a column “f_name” of data type varchar (with size 20 and constraint NOT
NULL) ,in the table student.
ALTER TABLE student ADD f_name varchar(20) NOT NULL;
Eg2:- query to modify the column name, increase the size of column from 20 to 30
ALTER TABLE student MODIFY COLUMN name varchar(30) not null;
Eg3: query to drop the column dob
ALTER TABLE student DROP COLUMN dob;
10. The SELECT statement is used to select data from a database.The data returned is stored in a
result table, called the result-set.
i. The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:
SELECT CustomerName, City
FROM Customers;
ii. The following SQL statement selects all the columns from the "Customers" table:
SELECT * FROM Customers;
iii. The following SQL statement selects only the DISTINCT values from the Country" column
in the "Customers" table:
SELECT DISTINCT Country FROM Customers;
iv. The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city is "Berlin":
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
v. The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
vi. The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
SELECT * FROM Customers
WHERE NOT Country='Germany';
vii. The following SQL statement selects all fields from "Customers" where country is
"Germany" AND city must be "Berlin" OR "München" (use parenthesis to form complex
expressions):
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
viii. The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
SELECT * FROM Customers
ORDER BY Country;
69
ix. The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
SELECT * FROM Customers
ORDER BY Country DESC;
x. The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column.
This means that it orders by Country, but if some rows have the same Country, it orders them
by CustomerName:
SELECT * FROM Customers
ORDER BY Country, CustomerName;
xi. The following SQL statement selects all customers from the "Customers" table, sorted
ascending by the "Country" and descending by the "CustomerName" column:
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
xii. 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.
The HAVING clause is used to filter groups based on the specified conditions.
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
xiii. The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
xiv. The following SQL statement lists the number of customers in each country. Only include
countries with more than 5 customers:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
xv. Condition Based on Pattern Matches:-using LIKE operator, pattern matching on strings is
possible.
• Percent (%)- used for matching any substring
• Underscore(_) - used for matching one character.
Eg1. Query to display records of employees whose name begin with ‘A’ and
ends with ‘T’.
SELECT *
FROM TABLE
WHERE name like “A%T”;
Eg2. Query to display records of employees whose name has second letter as
‘n’.
SELECT *
70
FROM TABLE
WHERE name like “_d%”;
xvi. A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based
on the common columns in the two tables being joined. Common columns are columns that
have the same name in both tables.
Eg. Query to display the item details and company from where the items are bought.
SELECT company_id, itme_id, item_name, item_unit, company_name, company_city
FROM table1 T1, table2 T2
WHERE T1.comapny_id=T2.company_id
Exercise 2:
• Write difference between Data Definition Language and Data Manipulation Language. 1
• Differentiate the following statement 1
i. DELETE FROM <table_name>;
ii. DROP TABLE <table_name>;
• Consider the above given table EXAM of database CBSE and write SQL queries for the following :-
5
i. To display the name of all Subjects in descending order of their subject codes.
ii. To display the content of the EXAM table in alphabetic order of SubjectName whose
exam date is on or after 20-Mar-2014.
iii. To display Subjectname and NumberofStudents from the table EXAM.
iv. To display NumberofStudents whose avgMarks in the range 90 to 250
v. To display lowest and highest marks scored.
Scode SubjectName NOS AvgMarks ExamDate
083 Computer Sc 67 95 22-Mar-2014
301 English 110 85 01-Mar-2014
041 Maths 110 80 20-Mar-2014
042 Physics 100 90 05-Mar-2014
043 Chemistry 100 85 11-Mar-2014
• Consider the following tables PRODUCT & CLIENT. Write SQL commands for the statement
(i) to (v) and give outputs for SQL queries (vi) to (vii) 6
Table: PRODUCT
PID Pname Manufacturer Price
HP01 Complan HLL 195
FW01 Face Wash Himalaya 65
BS01 Bar Soap Patanjali 12
CC01 Cold Cream Ponds 55
HL01 Horlicks TDH 215
Table: CLIENT
CID Cname City PID QTY
56 Gopal & Sons Varanasi FW01 120
48 Paradise For You Delhi BS01 80
14 Beauty Collection Lucknow CC01 100
18 Dreamz Varanasi HL01 200
10 Dhanuka Stores Kolkata HP01 150
71
i. To display the details of the clients of Varanasi & Kolkata in descending order of Cname.
ii. To display all the products whose price ranges between Rs. 1-100.
iii. To display Pname, Price and their corresponding Cname, City
iv. To decrease the price of all products produced by Ponds by 15%.
v. To display Pname and Price in descending order of QTY ordered.
vi. SELECT COUNT(Distinct City) FROM CLIENT;
vii. SELECT Manufacturer, Max(Price), SUM(Price) FROM PRODUCT Group
• Consider the following tables Items. Write SQL commands for the statements (i) to (vi).6
Table: Items
No ItemName CostPerItem Qua Date_of_purcha Warrant Operation
. ntity se y al
1 Computer 60000 9 21/5/96 2 7
MYSQL FUNCTIONS
STRING FUNCTIONS
Function Description
Char() Returns the character for each integer passed
Concat() Returns concatenated string
Lower()/lcase Returns the argument in lowercase
Substring()/substr() Returns the specified sbustring
Upper()/ucase() Converts to uppercase
Ltrim() Removes leading spaces
Rtrim Removes trailing spaces
Trim Removes leading and trailing spaces
Instr() Returns the index of the first occurrence of substring
Length() No of characters in a string
Left() Returns leftmost no. of characters
Right() Returns the specified right most no. of characters
Mid() Returns a substring starting from the specified position
Numeric functions
Mod() Returns the remainder of one expression after dividing by another
Power()/pow() Returns the value of on exp raised to the power of another
72
Round() Returns numeric expression rounded to an integer. Can be used to
round an exp to a number of decimal points
Sign() Returns the sign of a given number
Sqrt() Returns the non-negative square root of a numeric expression.
Truncate() Returns numeric exp1 truncated to exp2 decimal places. If exp2
is 0, then the result will have no decimal places.
Exercise 3:
• Write the output of the following queries: 1x10
i. SELECT ROUND(15.193,1);
ii. SELECT MOD(11,4);
iii. SELECT MOD(-9,4);
iv. SELECT SUBSTR(“COMPUTER SCIENCE”, 6,3);
v. SELECT INSTR(“CORPORATE FLOOR”, “OR”);
vi. SELECT TRUNCATE(15.79,1);
vii. SELECT CONCAT(“I”, “LIVE”, “IN”,”DELHI”);
viii. SELECT MONTH(“2022-02-03”);
ix. SELECT CURDATE();
x. SELECT MONTHNAME(“2022-06-03”)
• Identify the statement to add a column phone char(10) to the table students. 1
i. ALTER TABLE STUDENTS ADD PHONE VARCHAR(10);
ii. ADD PHONE;
iii. UPDATE ADD COLUMN PHONE;
iv. NONE
• Which of the following will select only one copy of each set of duplicate rows from a table?
1
i. SELECT UNIQUE
ii. SELECT DICTINCT
iii. SELECT DIFFERENT
iv. ALL OF THESE
• The following query is to display salary from greater to smaller and name in alphabetical order
1
SELECT * FROM EMPLOYEE ORDER BY salary _________, name __________;
Identify the correct option to complete the query:
73
i. ASCENDING,DESCENDING
ii. ASC, DESC
iii. DESC, ASC
iv. DESCENDING, ASCENDING
• Which query will display details of students whose name begin with “Ab”? 1
i. SELECT * FROM student WHERE name LIKE “Ab%”;
ii. SELECT * FROM student WHERE name LIKE “Ab_”;
iii. SELECT * FROM student WHERE name LIKE “Ab”;
iv. SELECT * FROM student WHERE name LIKE “%Ab”;
• In SQL, name the clause that is used to display the tuples in ascending order of an attribute.
• In SQL, write the query to display the list of tables stored in a database. 1
• Which of the following types of table constraints will prevent the entry of duplicate rows? 1
Unique b) Distinct c) Primary Key d) NULL
• A departmental store MyStore is considering to maintain their inventory using SQL to store the data.
As a database administer, Abhay has decided that :
• Name of the database - mystore
• Name of the table – STORE
• The attributes of STORE are as follows:
74
ItemNo - numeric
ItemName – character of size 20
Scode - numeric
Quantity – numeric
• Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting given
below: 3
Table : Teacher
T_ID Name Age Department Date_of_join Salary Gender
• Which function is used to display the total number of records from table in a database?
(a) sum(*)
(b) total(*)
(c) count(*)
(d) return(*)
Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur
76
Interface Python with MySQL
Database connectivity refers to connection and communication between an application and a database
system. The term “front-end” refers to the user interface created using any programming language and
“back-end” means the server, the database application and database that used to manage data and deliver
information to the user. For establishing connection between Python and MySQL we need to install
connectivity package named mysql.connector – the Library or package to connect from python to
MySQL.
77
The records retrieved from the database using SQL select query has to be extracted as record from the
resultset using the fetchall() , fetchone() , fetchmany() methods. rowcount provides the number of
records retrieved in the resultset.
fetchall()- Fetches all (remaining) rows of a query result, returning them as a sequence of sequences (a
list of tuples)
fetchone()-Fetches the next row of a query result set, returning a single sequence or None when no more
data is available
fetchmany (n)-Fetches the next set of ‘n’ rows of a query result, returning a sequence of sequences. It
will return number of rows that matches to the size argument.
Example-7 SELECT QUERY WITH WHERE CLAUSE & VIEW MULTIPLE RECORDS
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system", database=" STUD_DB")
cur=con.cursor()
cur.execute("select * from student where marks>90")
res=cur.fetchall()
count=cur.rowcount
print("total no of rows:",count)
for rec in res :
print(rec)
79
Questions based of DB connectivity (2/3 marks)
2. The given program is used to connect with MySQL and show the all the records from the table “master”
from the database “test”.
Write the following missing statements to complete the code:
Statement 1 – to import the library object
Statement 2 – to connect with existing local database server
Statement 3 - to form the cursor object
import _____.connector as pymysql # Statement 1
dbcon=pymysql._____________(host=”localhost”, user=”root”, passwd =“root”, database= “test”) #
Statement 2
if dbcon.isconnected()==False:
print(“Error in establishing connection:”)
cur=dbcon.______________() # Statement 3
query=”select * from master”
cur.execute(query)
resultset=cur.fetchmany(3)
for row in resultset:
print(row)
dbcon.close()
3. The given program is used to connect with MySQL and show the all the records from the table “Student”
from the database “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 students whose marks are greater than 75.
Statement 3- to read the complete result of the query (records whose marks are greater than 75) into
the object named data, from the table student in the database.
81
SAMPLE PAPER - 1
Class- XII (Computer Science (083))
M.M.:70 Time: 3 hrs.
Instructions:
1. This question paper contains two parts A and B. Each part is compulsory.
2. Both Part A and Part B have choices.
3. Part-A has 2 sections:
a. Section – I is short answer questions, to be answered in one word or one line.
b. Section – II has two case studies questions. Each case study has 4 case-based sub- parts.
An examinee is to attempt any 4 out of the 5 subparts.
4. Part - B is Descriptive Paper.
5. Part- B has three sections
a. Section-I is short answer questions of 2 marks each in which two questions have
internal options.
b. Section-II is long answer questions of 3 marks each in which two questions have internal
options.
c. Section-III is very long answer questions of 5 marks each in which one question has
internal option.
6. All programming questions are to be answered using Python Language only
PART-A
Section-I
Select the most appropriate option out of the options given for each question. Attempt any 15
questions from question no 1 to 21.
1. Find the invalid identifier from the following
1
a) def b) For c)_bonus d)First_Name
2. Given the lists Lst=[‘C’,’O’,’M’,’P’,’U’,’T’,’E’,’R’] , write the output of:
print(Lst[3:6]) 1
3. Function of writer object is used to send data to csv file to store. 1
4. What will be the output of following program:
a='hello' b='virat' 1
for i in range(len(a)): print(a[i],b[i])
5. Give Output:
colors=["violet", "indigo", "blue", "green", "yellow", "orange", "red"]
del colors[4]
1
colors.remove("blue")
colors.pop(3)
print(colors)
6. Which statement is correct for dictionary?
(i) A dictionary is a ordered set of key:value pair
(ii) each of the keys within a dictionary must be unique 1
(iii) each of the values in the dictionary must be unique
(iv) values in the dictionary are immutable
7. Identify the valid declaration
of Rec:
1
Rec=(1,‟Vikrant,50000)
(i)List (ii)Tuple (iii)String (iv)Dictionary
8. Find and write the output of the following python code:
def myfunc(a): 1
a=a+2
82
a=a*2
return a
print(myfunc(2))
9. Name the protocol that is used to transfer file from one computer to another. 1
10. Raj is a social worker, one day he noticed someone is writing insulting or
1
demeaning comments on his post. What kind of Cybercrime Raj is facing?
11. Which command is used to change the existing information of table? 1
12. Expand the term: RDBMS 1
13. Write an Aggregate function that is used in MySQL to find No. of Rows in the
1
database Table
14. For each attribute of a relation, there is a set of permitted values, called the of that
attribute.
a. Dictionaries
1
b. Domain
c. Directory
d. Relation
15. Name the Transmission media which consists of an inner copper core and a second
1
conducting outer sheath.
16. Identify the valid statement for list L=[1,2,”a”]:
(i) L.remove("2")
(ii) L.del(2) 1
(iii) del L[2]
(iv) del L[“a”]
17. Find and write the output of the following python code:
x = "Python"
print(x[ : :-1]) 1
print(x)
18. In SQL, write the query to display the list of databases stored in MySQL. 1
19. Write the expanded form of GPRS? 1
20. Which is not a constraint in SQL?
a) Unique
b) Distinct 1
c) Primary key
d) Check
21. Define Bandwidth? 1
Section-II
Both the Case study based questions are compulsory. Attempt any 4 sub parts
from each question. Each question carries 1 mark
22. Observe the following table and answer the question (a) to (e) (Any 04)
TABLE: VISITOR
VisitorID VisitorName ContactNumber
V001 ANAND 9898989898
V002 AMIT 9797979797
V003 SHYAM 9696969696
V004 MOHAN 9595959595
(a) Write the name of most appropriate columns which can be considered as
1
Candidate keys?
(b) Out of selected candidate keys, which one will be the best to choose as Primary
1
Key?
83
(c) What is the degree and cardinality of the table? 1
(d) Insert the following data into the attributes VisitorID, VisitorName and
ContactNumber respectively in the given table VISITOR.
1
VisitorID = “V004”, VisitorName= “VISHESH” and ContactNumber=
9907607474
(e) Remove the table VISITOR from the database HOTEL. Which command will
he used from the following:
a) DELETE FROM VISITOR;
1
b) DROP TABLE VISITOR;
c) DROP DATABASE HOTEL;
d) DELETE VISITOR FROM HOTEL;
23. Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has
written the following code to read the content of file emp.csv and display the
employee record whose name begins from “S‟ also show no. of employee with first
letter “S‟ out of total record. As a programmer, help her to successfully execute the
given task.
Consider the following CSV file (emp.csv):
1,Peter,3500 2,Scott,4000
3,Harry,5000 4,Michael,2500
5,Sam,4200
import ________ # Line 1
def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile, delimiter=',') # Line 3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)
(a) Name the module he should import in Line 1 1
(b) In which mode, Priti should open the file to print data. 1
(c) Fill in the blank in Line 2 to open the file. 1
(d) Fill in the blank in Line3 to read the data from a csv file. 1
(e) Write the output he will obtain while executing the above program. 1
PART-B
Section-I
24. If given A=2,B=1,C=3, What will be the output of following expressions:
(i) print((A>B) and (B>C) or(C>A)) 2
(ii) print(A**B**C)
25. What is Trojan? Any two type of activities performed by Trojan
OR 2
What is the difference between HTML and XML?
26. Expand the following terms:
2
a. HTTP b. POP3 c. VOIP d.TCP
27. What do you understand the default argument in function? Which function
2
parameter must be given default argument if it is used? Give example of function
84
header to illustrate default argument
OR
Ravi a python programmer is working on a project, for some requirement, he has to
define a function with name CalculateInterest(), he defined it as:
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above
function and what is the solution.
28. Rewrite the following Python program after removing all the syntactical errors (if
any), underlining each correction:
def checkval:
x = input("Enter a number")
if x % 2 =0:
2
print (x, "is even")
elseif x<0:
print (x, "should be positive")
else;
print (x, "is odd")
29. What possible outputs(s) are expected to be displayed on screen at the time of
execution of the program from the following code? Also specify the maximum
values that can be assigned to each of the variables FROM and TO.
import random
AR=[20,30,40,50,60,70]
FROM=random.randint(1,3) 2
TO=random.randint(2,4)
for K in range(FROM,TO):
print (AR[K],end=”#“)
(i)10#40#70# (ii)30#40#50#
(iii)50#60#70#(iv)40#50#70#
30. Define Primary Key of a relation in SQL. Give an Example using a dummy table. 2
31. Consider the following Python code is written to access the record of CODE
passed to function: Complete the missing statements:
def Search(eno):
#Assume basic setup import, connection and cursor is created
2
query="select * from emp where empno=________".format(eno)
mycursor.execute(query)
results = mycursor._________
print(results)
32. Differentiate between DDL and DML with one Example each.2 2
33. What will be the output of following program:
s="welcome2kv"
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'): 2
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()
85
else:
m = m +'#'
print(m)
Section-II
34. Write code in Python to calculate and display the frequency of each item in a list.
Ex. A[5,2,7,3,4,5,1,7,5]
Out will as :
5-→ 3
3
2-→1
7-→2
3-→ 1
1 --→ 1
35. Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT”
and count the number of times “AND” occurs in the file. (include AND/and/And in
the counting)
OR 3
Write a function DISPLAYWORDS( ) in python to display the count of words
starting with “t” or “T” in a text file ‘STORY.TXT’.
36. Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL
and ADMIN given below:
TABLE: SCHOOL
CODE TEACHERNAME SUBJECT DOJ PERODS EXPERIENCE
Section-III
38. PVS Computers decided to open a new office at Ernakulum, the office consist of
Five Buildings and each contains number of computers. The details are shown
below.
Building-2
Building-1 Building-3
87
1001 RAVISHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYA RAI PHYSICS 03/09/1998 26 12
1203 LISA ANAND ENGLISH 09/04/2000 27 5
1045 YASHRAJ MATHS 24/08/2000 24 15
1123 GANAN PHYSICS 16/07/1999 28 3
1167 HARISH B 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
88
SAMPLE PAPER -2
General instructions:
• This question paper contains five sections, Section A to E.
• All questions are compulsory.
• Section A have 18 questions carrying 01 mark each.
• Section B has 07 Very Short Answer type questions carrying 02 marks each.
• Section C has 05 Short Answer type questions carrying 03 marks each.
• Section D has 03 Long Answer type questions carrying 05 marks each.
• Section E has 02 questions carrying 04 marks each. One internal choice is given in Q35 against part
C only.
• All programming questions are to be answered using Python Language only.
Section – A
Q01. State True or False (1)
“Tuple is datatype in Python which contain data in key-value pair.”
Q20. Write two points of difference between Bus topology and star topology. (2)
OR
Write two points of difference between XML and HTML.
Q22. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give (2)
example to support your answer.
Q24. Predict the output of the Python code given below: (2)
data=["L",20,"M",40,"N",60]
times=0
alpha=""
add=0
for c in range(1,6,2):
times = times + c
alpha = alpha + data [c-1] + "@"
add = add + data[c]
print (times, add, alpha)
91
OR
Q25. Differentiate between order by and group by clause in SQL with appropriate example. (2)
OR
LAYS ONION 10 5
LAYS TOMATO 20 12
UNCLE CHIPS SPICY 12 10
UNCLE CHIPS PUDINA 10 12
HALDIRAM SALTY 10 20
HALDIRAM TOMATO 25 30
(i) Select BRAND_NAME, FLAVOUR from CHIPS where PRICE <> 10;
(ii) Select * from CHIPS where FLAVOUR=”TOMATO” and PRICE > 20;
(iii) Select BRAND_NAME from CHIPS where price > 15 and QUANTITY < 15;
(iv) Select count( distinct (BRAND_NAME)) from CHIPS;
(v) Select price , price *1.5 from CHIPS where FLAVOUR = “PUDINA”;
(vi) Select distinct (BRAND_NAME) from CHIPS order by BRAND_NAME desc;
Q27. Write a function countINDIA() which read a text file ‘myfile.txt’ and print the frequency (3)
of the words ‘India’ in it (ignoring case of the word).
Example: If the file content is as follows:
OR
Write a function countVowel() in Python, which should read each character of a text file
“myfile.txt” and then count and display the count of occurrence of vowels (including small
92
cases and upper case).
Example:
If the file content is as follows:
Table: ISSUED
BID QTY_ISSUED
HIST66 10
COMP11 5
LITR88 15
(i) Display book name and author name and price of computer type books.
(ii) To increase the price of all history books by Rs 50.
(iii) Show the details of all books in ascending order of their prices.
(iv) To display book id, book name and quantity issued for all books which have been
issued.
OR
Write a function in Python, Push(SItem) where, SItem is a dictionary containing the details
of stationary items– {Sname:price}.
The function should push the names of those items in the stack who have price greater than
25. Also display the count of elements pushed into the stack.
For example:
If the dictionary contains the following data:
Ditem = {“Rubber”:5, "Pencil":5, "Pen":30, "Notebook": 60, "Eraser":5, “Watch”: 250}
The stack should contain
Pen
Notebook
Watch
The output should be:
The count of elements in the stack is 3
Section – D
Q31. Aryan Infotech Solutions has set up its new center at Kamla Nagar for its office and web (5)
based activities. The company compound has 4 buildings as shown in the diagram below:
Orbit
Building
Sunrise
Jupiter
Building
Building
Oracle
Building
94
Sunrise Building to Jupiter Building 170 Mtrs.
Jupiter Building to Oracle Building 125 Mtrs.
Orbit Building to Sunrise Building 45 Mtrs.
#main-code
a=10
b=5
printMe(a,b)
printMe(r=4,q=2)
(B) The code given below inserts the following record in the table Student:
RollNo Name Clas Marks
Integer String Integer Integer
Note the following to establish connectivity between Python and MySQL:
* Username is root
* Password is toor@123
* The table exists in a “stud” database.
* The details (RollNo, Name, Clas and Marks) are to be accepted from the user.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the command that inserts the record in the table Student.
Statement 3 - to add the record permanently in the database
import mysql.connector as mysql
def sqlData():
con1=mysql.connect(host="localhost",user="root", password="toor@123",
database="stud")
mycursor = ________________ #Statement 1
rno=int(input("Enter Roll Number :: "))
95
name=input("Enter name :: ")
clas=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
querry="insert into student values({},'{}',{},{})".format(rno,name,clas,marks)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")
OR
(A) Predict the output of the code given below:
s="C++VsPy"
m=""
for i in range(0, len(s)):
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)
(B) The code given below reads the following record from the table named student and
displays only those records who have marks greater than 90:
RollNo Name Clas Marks
Integer String Integer Integer
Q33. What is the advantage of using a csv file for permanent storage? (5)
96
Write a Program in Python that defines and calls the following user defined functions:
(i) ADD() – To accept and add data of a teacher to a CSV file ‘teacher.csv’. Each record
consists of a list with field elements as tid, name and mobile to store teacher id, teacher
name and teacher mobile number respectively.
(ii) COUNTRECORD() – To count the number of records present in the CSV file named
‘teacher.csv’.
OR
Give any one point of difference between a binary file and a csv file.
Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of an employee to a CSV file ‘employee.csv’. Each
record consists of a list with field elements as eid, name and salary to store employee id,
employee name and employee salary respectively.
(ii) search()- To display the records of the employee whose salary is more than 40000.
Section – E
Q34. Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation of (1+
the table, she has entered data of 8 items in the table. 1+
2)
Table : STOCK
stockid Dopurchase Name make Price
101 2020-07-06 CPU ACER 12000
102 2020-09-01 CPU ACER 12750
103 2020-09-01 MONITOR ACER 7500
104 2016-08-03 PROJECTOR GLOBUS 37250
105 2016-05-26 VISUALIZER GLOBUS 17500
106 2020-07-23 WIFI RECEIVER ZEBION 450
107 2015-02-18 PRINTER LEXMARK 38000
108 2020-07-23 HEADPHONE BOAT 750
Q35. Vishnu is a Python programmer. He has written a code and created a binary file record.dat (1+
with studentid, subjectcode and marks. The file contains 10 records. 1+
He now has to update a record based on the studentid id entered by the user and update the 2)
marks. 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 student id is not found,
an appropriate message should to be displayed.
As a Python expert, help him to complete the following code based on the requirement
given above:
import _______ #Statement 1
97
def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
sid=int(input("Enter student id to update his marks :: "))
while True:
try:
rec = ______________ #Statement 3
if rec["studentid"]==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 studentid ", sid ," has been updated.")
else:
print("No student with such id is not found")
fin.close()
fout.close()
98
SAMPLE PAPER -3
CLASS-XII
SUBJECT – COMPUTER SCIENCE (083)
SECTION A
1 State True or False: 1
“Python is a dynamically typed language”.
Which of the following will be correct output if the given expression is evaluated?
a) True b) False c) NONE d) NULL
a) [1,2,3]
b) ["One", "Two", "Three"]
c) [2,3]
d) ["Two", "Three"]
6 Which of the following mode in the file opening statement creates a new file if the file does not exist? 1
99
a) r+ b) w+ c) a+ d) Both (b) and (c)
7 ______ command is used to add primary key in an existing table in MySQL. 1
a) update b) remove c) alter d)drop
10 In the relational model, relationships among relations/table are created by using _______ keys. 1
a) composite b) alternate c) candidate d) foreign
11 The correct statement to place the file handle fp1 to the 10th byte from the current position is: 1
a) fp1.seek(10) b) fp1.seek(10, 0) c) fp1.seek(10, 1) d) fp1.seek(10, 2)
14 Suppose str1= 'welcome'. All the following expression produce the same result except one. Which 1
one?
a) str[ : : -6] b) str[ : : -1][ : : -6] c) str[ : :6] d) str[0] + str[-1]
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
100
17 Assertion (A): Leading whitespace at the beginning of a statement in Python is called indentation. 1
Reason (R): In Python, the same level of indentation associates statements into a single block of code.
SECTION B
19 Identify the errors in the program segment given below. Rewrite the corrected code and underline 2
each correction.
250=Number
WHILE Number <= 1000:
if Number => 750:
print(Number)
Number = Number+100
else
print(Number*2)
Number = Number+50
def Findoutput():
L="Program"
X=""
L1=[]
count = 1
for i in L:
if i in ['a', 'e', 'i', 'o', 'u']:
X=X+i.swapcase()
else:
if count%2 != 0:
X=X+str(len(L[:count]))
else:
X=X+i
count=count+1
print(X)
Findoutput()
OR
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2!=0:
101
m=m+str[i-1]
else:
m=m+"$"
print(m)
Display('[email protected]')
21 Write two points of difference between HTTP and FTP. 2
OR
State two advantages and two disadvantages of star topology over bus topology?
23 What do you understand by Candidate keys in a table? Give a suitable example of Candidate keys 2
from a table containing some meaningful data.
25 Differentiate between DROP and DELETE commands in SQL with appropriate example. 2
OR
Differentiate CHAR and VARCHAR datatypes of SQL with appropriate example.
SECTION C
26 a) Consider the following two tables: 1+2
EMPLOYEE DEPARTMENT
ENO ENAME DOJ DNO DNO DNAME
E1 RASMI 2005-05-12 D1 D1 ACCOUNTS
E2 ANUP 2006-07-10 NULL D2 HR
E3 RITESH 2005-07-28 D3 D3 ADMIN
b) Write the output of the queries (i) to (iv) based on the table Crockery given below:
Table: CROCKERY
FID NAME DATEOFPURCHASE COST DISCOUNT
B001 CUP 03-Jan-2018 4500 10
T010 PLATE 10-Mar-2020 5100 5
B004 SPOON 19-Jul-2021 2200 0
C003 GLASS 30-Dec-2016 1200 3
102
T006 KNIFE 17-Nov-2019 1500 12
B006 TRAY 01-Jan-2021 2800 14
OR
Write a function in Python which reads the content of a text file Nature.txt and prints all the lines
containing the word THE (ignore case sensitivity).
28 a) Write SQL queries for (i) to (iv) based on the tables: 2+1
TABLE: CUSTOMER
CNO CNAME ADDRESS
101 Richa Jain Delhi
102 Surbhi Sinha Chennai
103 Lisa Thomas Bangalore
104 Imran Ali Delhi
105 Roshan Singh Chennai
TABLE: TRANSACTION
TRNO CNO AMOUNT TYPE DOT
T001 101 1500 Credit 2017-11-23
T002 103 2000 Debit 2017-05-12
T003 102 3000 Credit 2017-06-10
T004 103 12000 Credit 2017-09-12
T005 101 1000 Debit 2017-09-05
i) To display the details of all transactions of TYPE Credit from the table TRANSACTION.
ii) To display all CNO, CNAME and DOT (date of transaction) of those CUSTOMERS from tables
CUSTOMER and TRANSACTION who have done transactions more than or equal to 2000.
iii) To display the last date of transaction (DOT) from the table TRANSACTION for the customer
having CNO as 103.
iv) To display the total number of transactions and sum of amount from the table TRANSACTIONS
for different customers.
29 Write the definition of a method SUM5_7(X), which receives a number list X and displays the sum of 3
all those numbers which are multiple of 7 but not a multiple of 5.
Ex: if X is [7, 14, 35, 43, 40]
The function should display:
Sum is: 21
30 Vedika has created a dictionary containing names and marks as key-value pairs of 10 students. Write 3
a program, with separate user-defined functions to perform the following operations:
103
• Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 90.
• Pop and display the content of the stack.
OR
Ridhima has a list of numbers (complex, integer and floating point). Write a program, with separate
user-defined functions to perform the following operations:
• Traverse the content of the list and push all the positive integers of the list into a stack.
• Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows: N=[2+3j, -78, 45, 34, -23, 36.75, 62+9j, 23.7, 69, 10.5]
Sample Output of the code should be:
45 34 69
SECTION D
31 Alpha Pvt Ltd is setting up the network in Chennai. There are four blocks- Block A, Block B, Block C &
Block D.
Distance between various blocks are as given Number of computers in each block are given
below: below:
i) Suggest the most suitable block to place the server with a suitable reason. 1
ii) Suggest the cable layout for connections between the various blocks. 1
iii) Suggest the placement of following devices: 1
(a) Switch/Hub (b) Repeater
iv) The organization is planning to link its front office situated in the city to a hilly region (30 KM away 1
from front office) where cable connection is not possible. Suggest an economic way to connect
with reasonably high speed.
1
104
v) Out of following which type of Network PAN/LAN/MAN/WAN will be formed if the front office is
connected to hilly region.
OR
Text1="AISSCE,2023"
Text2=""
I=0
while I<len(Text1):
if Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
105
Val = Val + 1
Text2=Text2 + str(Val)
elif Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 + (Text1[I+1])
else:
Text2=Text2 + "*"
I=I+1
print (Text2)
b) The code given below Searches and displays the details of customers of a particular city, from the
table Customer. Customer table contains records of type:
CustNo – integer
CustName – string
CustCity – string
Mobile – char(10)
106
(b) SEARCH() – To count and display the number of patients of age between 40 to 50 (both
inclusive) from the file ‘PATIENT_RECORD.CSV’
SECTION E
34 Consider the table ITEMS 4
(1+1+2)
ItemNo ItemName SuppCode Quantity
2005 Notebook Classic 23
2003 Ball Pen 0.25 24 50
2002 Get Pen Premium 21 150
2006 Get Pen Classic 25 60
2001 Eraser Small 26 220
35 Alia has written a code and created a binary file EMPLOYEE.DAT with employeeid, ename and salary. 4
The file contains 10 records. She 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 UPDATEEMP.DAT.
The records which are not to be updated also have to be written to the file UPDATEEMP.DAT. If the
employee id is not found, an appropriate message should be displayed. As a Python expert, help her
to complete the following code based on the requirement given above:
import pickle
def update_data():
rec=[]
fin=open(___________________) #Statement 1
fout=open("UPDATEEMP.DAT ", "wb")
found=False
eid=int(input("Enter employee id to update their salary : "))
while True:
try:
rec=______________ #Statement 2
if rec["employeeid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary :: "))
pickle.dump(rec,fout)
else:
___________________ #Statement 3
except:
break
if _____________________: #Statement 4
107
print("The salary of employee id ",eid," has been updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
i) Write the correct statement to open the file EMPLOYEE.DAT to read the records of the file.
(Statement 1)
ii) Write the statement to read the data from the binary file EMPLOYEE.DAT. (Statement 2)
iii) Statement 3 to write the records which are not updated in the file UPDATEEMP.DAT. Write the
condition to check if the record updated (Statement 4).
108
SAMPLE PAPER -4
Section A
1 Write full form of CSV. 1
2 Which is valid keyword? 1
a. Int b. WHILE c.While d.if
3 Which of the following is not a valid identifier name in Python? 1
a) 5Total b) _Radius c) pie d)While
4 Consider the following expression: 1
51+4-3**3//19-3
Which of the following will be the correct output if the expression is evaluated?
a. 50
b. 51
c. 52
d. 53
5 Select the correct output of the code: 1
Str=“Computer”
Str=Str[-4:]
print(Str*2)
a. uter
b. uterretu
c. uteruter
d. None of these
6 Which module is imported for working with CSV files in Python? 1
a. csv
b. python-csv connector
c. CSV
d. python.csvconnector
7 Fill in the blank: 1
command is used to update records in the MySQL table.
(a) ALTER (b) UPDATE (c) MODIFY (d) SELECT
8 Which command used to fetch rows from the table in database? 1
(a) BRING (b) FETCH (c) GET (d) SELECT
109
9 Which of the following statement(s) would give an error after executing the following 1
code?
print(9/2) # Statement-1
print(9//2) # Statement-2
print(9%%2) # Statement-3
print(9%2) # Statement-4
(a) Statement-1 (b) Statement-2 (c) Statement-3 (d) Statement-4
10 Fill in the blanks: 1
is the table constraint used to stop null values to be entered in the field.
(i) Unique
(ii) Not NULL
(iii) Not Empty
(iv) None
11 The correct syntax of read() function from text files is: 1
a. file_object.read()
b. file_object(read)
c. read(file_object)
d. file_object().read
12 Fill in the blank: 1
In SQL, we use command to display the list of databases in the server.
(a) SELECT DATABASES;
(b) SELECT DATABASE;
(c) SHOW DATABASES;
(d) DESC;
13 Fill in the blank: 1
protocol is used to send mail.
(a) SMTP (b) FTP (c) POP (d) HTTPS
14 What will the following expression be evaluated to in Python? 1
10*1*2**4-4//4
15 Which function is used to display the maximum of records from table in a database? 1
(a) MAX (b) MAXIMUM (c) LARGEST (d) GREAT
16 To establish a connection with MySQL from Python which of the following functions is 1
used?
(a) connection() (b) connect() (c) open() (d) cursor()
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): Global variable is declared outside the all the functions. 1
Reasoning (R): It is accessible through out all the functions.
18 Assertion (A): Binary files store all data in text format. 1
Reasoning (R): Binary files data remain in its original type.
Section B
110
19 Rajat has written the following Python code. There are some errors in it. Rewrite the 2
correct code and underline the corrections made.
DEF execmain():
x = input("Enter a number:")
if (abs(x)=x):
print ("You entered a positive number")
else:
x=*-1
print "Number made positive:"xexecmain()
21 a. Find output generated by the following code: 1+1
mystr = “Hello I am a Human.”
print(mystr[::-3])
def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(3)
OR
mylist = [2,14,54,22,17]
tup = tuple(mylist)
for i in tup:
print(i%3, end=",")
OR
Section-C
111
26 a. Consider the following tables Trainer and Course: 1+2
b. Write the Outputs of the MySQL queries (i) to (iv) based on the given above tables:
i. SELECT DISTINCT(CITY) FROM TRAINER WHERE SALARY>80000;
ii. SELECT TID, COUNT(*), MAX(FEES) FROM COURSE GROUP BY TID
HAVING COUNT(*)>1;
iii. SELECT T.TNAME, C.CNAME FROM TRAINER T, COURSE C WHERE
T.TID=C.TID AND T.FEES<10000;
iv. SELECT COUNT(CITY),CITY FROM TRAINER GROUP BY CITY;
27 Write a method/function COUNTLINES_ET() in python to read lines from a text file 3
REPORT.TXT, and COUNT those lines which are starting either with ‘E’ or starting with
‘T’ and display the Total count separately.
For example:
If REPORT.TXT consists of
“ENTRY LEVEL OF PROGRAMMING CAN BE LEARNED FROM PYTHON. ALSO, IT
IS VERY FLEXIBLE LANGUGAE. THIS WILL BE USEFUL FOR VARIETY OF USERS.”
Then, Output will be:
No. of Lines with E: 1
No. of Lines with T: 1
OR
Write a method/ function SHOW_TODO() in python to read contents from a text file
ABC.TXT and display those lines which have occurrence of the word ‘‘TO’’ or
‘‘DO’’.
For example :
If the content of the file is
“THIS IS IMPORTANT TO NOTE THAT
SUCCESS IS THE RESULT OF HARD WORK.
WE ALL ARE EXPECTED TO DO HARD WORK.
AFTER ALL EXPERIENCE COMES FROM HARDWORK.”
112
THIS IS IMPORTANT TO NOTE THAT
WE ALL ARE EXPECTED TO DO HARD WORK.
28 a. Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and 3
Posting given below:
OR
113
Section-D
31 Prithvi Training Institute is planning to set up its centre in Jaipur with four specialized 5
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 (v).
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 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
v. Suggest the type of network implemented here.
32 (a) Write the output of following python code: 2+3
def result(s):
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)
result('Cricket')
114
(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.11.111
User : root
Password: Admin
Database : MYPROJECT
OR
(a) Find the output
Msg1="WeLcOME"
Msg2="GUeSTs"
Msg3=""
for I in range(0,len(Msg2)+1):
if Msg1[I]>="A" and Msg1[I]<="M":
Msg3=Msg3+Msg1[I]
elif Msg1[I]>="N" and Msg1[I]<="Z":
Msg3=Msg3+Msg2[I]
else:
Msg3=Msg3+"*"
print(Msg3)
b) Your friend Jagdish is writing a code to fetch data from a database Shop and table name
Products using Python. He has written incomplete code. You have to help him write
complete code:
import as m # Statement-1
object1 = m.connect(
host="localhost",
user="root",
password="root",
database="Shop"
)
object2 = object1. # Statement-2
query = '''SELECT * FROM Products WHERE NAME LIKE "A%";'''
object2. (query) # Statement-3
object1.close()
33 What is the advantage of using pickle module? 2+3
Write a program to write into a CSV file “one.csv” Rollno, Name and Marks separated by
comma. It should have header row and then take input from the user for all following rows.
The format of the file should be as shown if user enters 2 records.
Roll.No,Name,Marks
20,Ronit,67
56,Nihir,69
OR
What is difference between tell() and seek() methods?
Write a program to read all content of “student.csv” and display records of only those
students who scored more than 80 marks. Records stored in students is in format : [Rollno,
Name, Marks]
115
34 ABC Gym has created a table TRAINER. Observe the table given below and answer the 1+1
following questions accordingly. +2
Section E
35 Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has written the 1+1
following code to read the content of file emp.csv and display the employee record whose +2
name begins from “S‟ also show no. of employee with first letter “S‟ out of total record.
As a programmer, help her to successfully execute the given task.
Consider the following CSV file (emp.csv):
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
import # Line-1
def snames():
with open( ) as csvfile: # Line-2
myreader = csv. (csvfile, delimiter=",") # Line-3
count_rec=0
count_s=0
for row in myreader:
if row[1][0].lower() == "s":
print(row[0],",",row[1],",",row[2])
count_s += 1
count_rec += 1
print(count_rec, count_s)
i. What should be written in Line-1?
ii. In which mode should Priti open the file to print the data?
iii What should be written in Line-2
116
SAMPLE PAPER -5
CLASS – XII COMPUTER SCIENCE (083)
TIME ALLOWED: 03 HOURS M.M.: 70
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 is given in Q35 against part c only.
8. All programming questions are to be answered using Python Language only.
SECTION A
1. Fill in the Blank 1
The explicit conversion of an operand to a specific type is called _____
(a)Type casting (b) coercion (c) translation (d) None of these
2. Which of the following is not a core data type in Python? 1
(a)Lists (b) Dictionaries (c)Tuple (d) Class
3. What will the following code do? 1
dict={"Exam":"AISSCE", "Year":2022}
dict.update({"Year”:2023} )
SECTION B
19. Preety has written a code to add two numbers .Her code is having errors. Rewrite the correct code and 2
underline the corrections made.
def sum(arg1,arg2):
total=arg1+arg2;
print(”Total:”,total)
return total;
sum(10,20)
print(”Total:”,total)
20. Write two points of difference between Hub and Switch. 2
OR
Write two points of difference between Web PageL and Web site.
21. Write the output of following code and explain the difference between a*3 and (a,a,a) 2
a=(1,2,3)
print(a*3)
print(a,a,a)
22 Differentiate between DDL and DML with one Example each. 2
23 (a) Write the full forms of the following: 2
(i) SMTP (ii) PPP
(b) What is the use of TELNET?
24 What do you understand the default argument in function? Which function parameter must be given default 2
argument if it is used? Give example of function header to illustrate default argument
OR
Ravi a python programmer is working on a project, for some requirement, he has to define a function with
name CalculateInterest(), he defined it as:
118
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above function and what is the
solution.
25 Write the output of the queries (a) to (d) based on the table 2
119
28 (Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given below: 3
120
SECTION D
31. MakeInIndia Corporation, an Uttarakhand based IT training company, is planning to set up training centres
in various cities in next 2 years. Their first campus is coming up in Kashipur district. At Kashipur campus,
they are planning to have 3 different blocks for App development, Web designing and Movie editing. Each
block has number of computers, which are required to be connected in a network for communication, data
and resource sharing. As a network consultant of this company, you have to suggest the best network
related solutions for them for issues/problems raised in question nos. (i) to (v), keeping in mind the
distances between various Distance between various blocks/locations:
blocks/locations and other given parameters.
KASHIPUR
APP CAMPUS
DEVELOPM MOVIE
ENT EDITING
MUSSOORIE
CAMPUS
WEB
DESIGNING
Block Distance
App development to Web designing 28 m
App development to Movie editing 55 m
Web designing to Movie editing 32 m
Kashipur Campus to Mussoorie Campus 232 km
Number of computers
Block Number of Computers
App development 75
Web designing 50
Movie editing 80
(i) Suggest the most appropriate block/location to house the SERVER in the Kashipur campus (out of
the 3 blocks) to get the best and effective connectivity. Justify your answer. 1
(ii) Suggest a device/software to be installed in the Kashipur Campus to take care of data security. 1
(iii) Suggest the best wired medium and draw the cable layout (Block to Block) to economically connect 1
various blocks within the Kashipur Campus.
(iv) Suggest the placement of the following devices with appropriate reasons:
aSwitch / Hub 1
b Repeater
(v) Suggest a protocol that shall be needed to provide Video Conferencing solution between Kashipur
Campus and Mussoorie Campus. 1
121
32. (a) What will be the output of following program: 2+
s="welcome2kv" 3
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)
(b)The code given below reads the following record from the table named studentand displays only
those records who have marks greater than 75:
RollNo – integer
Name – string
Clas – integer
Marks – integer
122
33. What is the advantage of using a csv file for permanent storage? Write a Program in Python that defines 5
and calls the following user defined functions:
(i) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a
list with field elements as empid, name and mobile to store employee id, employee name and
employee salary respectively.
(ii) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
OR
Give any one point of difference between a binary file and a csv file. Write a Program in Python that defines
and calls the following user defined functions:
123
35. Anuj Kumar of class 12 is writing a program to create a CSV file “user.csv” which will contain user name and
password for some entries. He has written thefollowing code. As a programmer, help him to successfully
execute the giventask.
import _____________ # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV file 4
f=open(' user.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
124
APPENDIX – 1
Keywords in Python
Precedence of Operators
( ) Parentheses Highest
** Exponentiation
~ x Bitwise nor , +x, -x Positive, Negative (Unary +, -)
*(multiply), / (divide), //(floor division), %(modulus)
+(addition), - (subtraction)
& Bitwise and
^ Bitwise XOR
| Bitwise OR
=, %=, /=, //=, -=, +=, *=, **= (Relational Operators)
125
APPENDIX – 2
Mathematical Functions
fabs() function
returns the absolute math.fabs(1.0) gives
value of num. 1.0.
fabs math.fabs(num)
Negative value is math.fabs(-1.0) gives -
converted to positive 1.0.
value.
126
log10() function
returns the base 10 math.log10(1.0) give
log10 math.log10(num) logarithm for num. base 10 logarithm for
Error occurs if num 1.0.
<=0.
degrees() converts
math.degrees(3.14)
degrees math.degrees(x) angle x from radians
would give 179.91.
to degrees.
radians() converts
math.radians(179.91)
radians math.radians(x) angle x from degrees
would give 3.14.
to radians.
math.factorial(4) gives
factorial math.factorial(arg) Returns factorial
24
Returns greatest
gcd math.gcd(x,y) math.gcd(8,6) gives 2
common divisor
127
APPENDIX – 3
Functions / Methods used with Strings
128
2
>>>a.count(“be”,7)
1
>>>a.count(“be”,7,11)
0
lower() It converts the string into lowercase >>>str=”My Favourite Food”
>>str.lower()
‘my favourite food’
islower() It returns True if all the letters in the >>>str=”my favourite food”
string are in lowercase. >>str.islower()
True
upper() It converts the string into uppercase >>>str=”My Favourite Food”
>>str.upper()
‘MY FAVOURITE FOOD’
isupper() It returns True if all the letters in the >>>str=”My Favourite Food”
string are in uppercase. >>str.isupper()
False
lstrip() It returns the string after removing >>> “ Hello”.lstrip()
the space from the left of the string ‘Hello’
rstrip() It returns the string after removing >>> “Hello ”.rstrip()
the space from the right of the string ‘Hello’
strip() It returns the string after removing >>> “ Hello ”.strip()
the space from the both side of the ‘Hello’
string
isspace() It returns True if the string contains str= “ “
only whitespace characters, str1= “”
otherwise returns False. >>>str.isspace()
True
>>>str1.isspace()
False
swapcase() It converts uppercase letter to >>>"Hello World".swapcase()
lowercase and vice versa of the 'hELLO wORLD'
given string.
>>>"Hello
World".swapcase().swapcase()
'Hello World'
partition() Splits string at the first occurrence >>> Nm= “I Love India”
of argument sep and returns 3- tuple >>>nm.partition(‘Lo’)
containing the part before the ('I ', 'Lo', 've India')
separator , the separator itself and
the part after separator.
ord() It returns the ASCII/Unicode of the >>>ch= ‘A’
character. >>>ord(ch)
65
chr() It returns the character represented >>>ch=65
by the imputed Unicode /ASCII >>>chr(ch)
number ‘A’
startswith() Returns True if the string starts with >>> “abcd”.startswith(“cd”)
the substring ,otherwise returns False
False. >>> “abcd”.startswith(“ab”)
True
129
endswith() Returns True if the string ends with >>> “abcd”.endswith(“cd”)
the substring ,otherwise returns True
False. >>> “abcd”.endswith(“ab”)
False
130
APPENDIX – 4
Functions / Methods used with Lists
132
APPENDIX – 5
Functions / Methods used with Tuples
133
APPENDIX – 6
Functions / Methods used with Strings
dict_items([('a', 'apple'),
('b', 'boy'), ('c', 'cat'),
('d', 'dog')])
keys( ) It returns a list of the key values mydict={'empno':1,'name':'Shivam','dept':'sales',
in a dictionary 'salary':25000}
print(mydict.keys())
key=('Eno','Ename','Sal')
value=[1]
value.append(2)
d1=dict.fromkeys(key,value)
print(d1)
{'Eno': [1, 2], 'Ename': [1, 2], 'Sal': [1, 2]}
clear( ) It removes all the elements from D={'a': 'apple', 'b': 'boy', 'c': ‘cat’}
the Dictionary. D.clear()
print(D)
{}
3
sorted( ) It sorts the elements of a d1={2:100,4:200,3:300,1:400}
dictionary by its key or values. print(sorted(d1))
[1, 2, 3, 4]
d1={1:200,2:300,3:100,4:400}
134
print(sorted(d1.values()))
[100, 200, 300, 400]
pop() It will not only delete the mydict={'empno':1,'name':'Shivam','dept':'sales',
key:value pair but also returns the 'salary':25000}
corresponding value. print(mydict.pop('dept'))
print(mydict)
‘sales’
{'empno': 1, 'name': 'Shivam', 'salary': 25000}
del statement alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
del alpha[‘c’]
print(alpha)
{'a': 'apple', 'b': 'boy', 'd': 'dog'}
popitem( ) It removes the last item from alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
dictionary and also returns the item=alpha.popitem()
deleted item. print(item)
print(alpha)
('d', 'dog')
{'a': 'apple', 'b': 'boy', 'c': 'cat'}
max( ) Returns the key having maximum data={5:100, 2:200,3:300,4:200}
value in the Dictionary. print(max(data))
5
min( ) Returns the key having minimum data={5:100, 2:200,3:300,4:200}
value in the Dictionary. print(min(data))
2
5
sum() It adds the keys in dictionary. data={5:100, 2:200,3:300,4:200}
print(sum(data))
14
update() It merges key:value pairs from the d1={1:100,2:200,3:300,4:400}
new dictionary into the original d2={1:111,2:222,5:555,4:444}
dictionary, adding or replacing as d1.update(d2)
needed. print(d1)
{1: 111, 2: 222, 3: 300, 4: 444, 5: 555}
135
APPENDIX – 7
Answer Key (Revision Tour)
1 Mark Questions
1. Ans. True
2. Ans. (a) continue
3. Ans. b) {'Exam': 'AISSCE', 'Year': 2023, 'Total': 500, 'Pass_Marks': 165}
4. Ans. False
5. Ans.(d) Python .s an .nterpreted language
6. Ans. Statement 4
7. Ans. ( c) 13.0
8. Ans. C) eval
9. Ans. [82, 5, 7]
10. Ans. C) **
11. Ans. b) T[2] = -51
12. Ans. dict={1: ‘Monday’ ,2: ‘Tuesday’ ,3: ‘Wednesday’}
13. Ans. math.fabs()
14. Ans. otPh
15. Ans. a. string
16. Ans. (i) keyword (ii) identifier
17. Ans. (i) math (ii) random
18. Ans. (i)
19. Ans. (a) infinite times
20. Ans. (iii) 100+200
21. Ans. (iii) error
22. Ans. (i) 27
23. Ans. (a) ,(b) , (e)
24. Ans. d) Boolean
25. Ans. (iii) remove( )
26. Ans. (a) n Pr gaug
27. Ans. (ii) True
28. Ans. a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
29. Ans. a) [12, 33, 22, 14]
30. Ans. b) list1.insert(2, 5)
31. Ans. [30, 40, 50, 20, 34, 55]
32. Ans. c) del d[“john”]
33. Ans. c) {1, “A”,2 “B”}
34. Ans. c) Keys can be List
35. Ans. b) 33
36. Ans. c) Error
37. Ans. a) 25
38. Ans. Rahul is playing
39. Ans. a) True
40. Ans. a) oses
41. Ans. a) ab12ef12
42. Ans. [[27, 56, 4]]
43.Ans. roPotP
44. Ans. 7
45. Ans.(1,2,3)
46. Ans. (10, 40, 30)
47. Ans. dict_keys(['empno', 'name', 'dept', 'salary'])
136
dict_values([1, 'Shivam', 'sales', 25000])
48. Ans. {1: 111, 2: 222, 3: 300, 4: 444, 5: 555}
49. Ans. {'Eno': [1, 2], 'Ename': [1, 2], 'Sal': [1, 2]}
50. Ans. {'Exam': 'AISSE', 'Year': 2023}
2 Marks Questions
1. Ans.
a) NIAIAEEB
b) dict_items([('Name', 'Rahul'), ('age', 45), ('address', 'Bhubaneswar')])
2. Ans.
{'ball': 1}
{'ball': 1, 'pen': 1}
{'ball': 2, 'pen': 1}
{'ball': 2, 'pen': 1, 'pencil': 1}
3. Ans.
[10]
[10, 11]
[10, 11, 12]
[10, 11, 12, 13]
4. Ans. GMAILbbCOM
5. Ans. Gnd**M
6. Ans. a) 7 b) True
7. (i) Ans 14 50 (ii) Ans. 12 7 10
8. Ans:
val = int(input("Value:"))
adder = 0
for C in range(1,val,3) :
adder+=C
if C%2==0:
print (C*10)
else:
print (C)
print (adder)
9. Ans.
Val=25
for I in the range(0,Val) :
if I%2==0:
print( I+1)
else:
print (I‐1)
10. Ans.
17
{(1, 2, 4): 5, (4, 2, 1): 4, (1, 2): 8}
1 Mark Questions
1. (a) def
2. (b) def function_name( )
3. (b) 25
4. (d) No Output (Error)
137
5. (a) Function
6. (c) sum( )
7. (a) A function definition begins with “define”
8. (a) Parameter
9. (c) Both the statements are True
10. (b) 18
11. (c) def div(p1=4,p2,p3):
12. (b) Tuple
13. (b) Local Variable
14. (b) random
15. (d) 100
16. (c) 45
17. (a) A python standard library consists of a number of modules
18. (b) from math import sqrt
19. (c) Mumbai#Mumbai#Chennai#Mumbai#
20. (a) 3 5 5
3. Ans.
24
23
64
4. Ans.
50#5
5. Ans:
def display( ): #:
for Name in ["Ramesh","Suraj", "Priya"]: # inverted code and :
if Name [0] = "S": # indentation
print (Name) # small p in print()
6. Ans:
def execmain():
x = int(input("Enter a number:"))
if (abs(x)== x):
print("You entered a positive number")
else:
x*=-1
print("Number made positive : ",x)
execmain()
7. Ans:
The new string is:, pASs@2022
8. Ans:
def Tot(Number) : #Method to find Total #Error 1
138
Sum=0
for C in range (1, Number+1): #Error 2
Sum+=C
return Sum #Error 3
print(Tot(3)) #Function Call #Error 4
9. Ans:
l=[25,24,35,20,32,41]
s=0
for i in l:
if i%2!=0:
s+=i*2
print(s)
10. Ans:
def sepeven_odd(A):
even_sum=0
odd_sum=0
for i in A:
if i%2==0:
even_sum+=i
else:
odd_sum+=i
print("Even sum=",even_sum)
print("Odd sum=", odd_sum)
x=[34,12,67,33,79,6,23]
sepeven_odd(x)
11. Ans:
def OCCURRENCE(s,c):
count=0
for i in s:
if i==c:
count+=1
return count
x=input("Enter any string")
y=input("enter charater to find out frequency")
z=OCCURRENCE(x,y)
print(z)
12. Ans.
def b_search(A,x):
l=0
u=len(A)-1
while l<=u:
m=(l+u)//2
if x==A[m]:
return True
elif x>A[m]:
l=m+1
else:
u=m-1
return False
A=[12,34,45,67,89,95,105]
139
x=int(input("Enter search value"))
if b_search(A,x):
print("Found")
else:
print("Not Found")
13. Ans:
P
YYYY
TTTTT
14. Ans:
S
SC
SCH
SCHO
SCHOO
SCHOOL
SCHOOLbb
SCHOOLbbbb
SCHOOLbbbbC
SCHOOLbbbbCO
SCHOOLbbbbCOM
15. Ans :
6000 * 0
6000 $ 30
600 * 0
6000 $ 600
120000 * 0
120000 $ 600
16. Ans:
def showlarge(s):
l = s.split()
for x in l:
if len(x)>4:
print(x)
s=" My life is for serving my Country "
showlarge(s)
17. Ans :
Non-default argument follows default argument.
140
4. (a) file.read(n)
5. (b) tmpfile.read( )
6. (c) pickle
7. (c) dump
8. (c) load( )
9. (d) The column names of the data
10.(c) csv.reader(my_data, delimiter='\t')
2 / 3 Mark questions
1. Ans:
sr1 =f.readline() # to read first line of file
str2 = f.readline(10) # to read next line of file
str3 = f.read() # to read remaining lines of file
2. Ans:
count =0
f=open ("poem.txt","r")
data=f.readlines() # data will be list of string
print(data)
for line in data:
if line[-2] == 'a':
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count)
f.close()
3. Ans:
def count():
f=open ("notes.txt" ,"r")
count=0
x= f.read()
word =x.split ()
for i in word:
if (len(i) == 4):
count =count + 1
print ("No.of words having 4 characters is" ,count)
f.close()
4. Ans:
def count():
f=open ("Story.txt" ,"r")
count=0
lines= f.readlines()
for line in lines:
count+=1
if line[0] in [‘g’,’G’] :
print(count,line)
f.close()
5. Ans:
F= open(“an.txt”,”r”)
for line in F:
words=line.split( )
for i in words:
for letter in i:
if(letter.isdigit( )):
print(letter)
141
6. Ans:
def remove_lowercase(infile, outfile):
output=file(outfile,”w”)
for line in file(infile):
if not line[0] in “abcdefghijklmnopqrstuvwxyz”:
output.write(line)
output.close()
7. Ans:
d1=pickle.load(f2)
8. Ans:
pickle.dump(dt,f1)
9. Ans:
a. import pickle
def CreateFile():
f=open(“Book.dat”,”ab”)
bookno=int(input(“Enter Book Number:”))
bookname=input(“Enter Book Name:”)
Author=input(“Enter Author Name:”)
Price=int(input(“Enter Book price:”))
Rec=[bookno,bookname,Author,Price]
Pickle.dump(rec,f)
f.close()
CreateFile()
b. def countrec(Author):
f=open(“Book.dat”,”rb”)
num=0
try:
while True:
rec=pickle.load(f)
if Author==rec[2]:
num=num+1
print(rec[0],rec[1],rec[2],rec[3])
except:
f.close()
return num
n=countrec(“ABC”)
print(“total records”,n)
11. Ans:
import pickle
import os
def delrec(e):
num=0
f1=open(“emp.dat”,”rb”)
f2=open(“temp.dat”,”wb”)
try:
while True:
rec=pickle.load(f1)
if rec[0]==e:
print(“record found and deleted”)
else:
pickle.dump(rec,f2)
except:
f1.close()
f2.close()
142
os.remove(“emp.dat”)
os.rename(“temp.dat”,”emp.dat”)
12. Ans:
import csv
f=open(“data.csv”,”r”) // with open (“data.csv”,”r”) as f
d=csv.reader(f)
for row in d:
print(row)
f.close()
14. Ans:
import csv
f=open("data.csv","r")
d=csv.reader(f)
next(f)
print(" recod of student whose score more then 70% marks")
for i in d:
try:
if int(i[3])>70:
print("roll no;",i[0])
print("name: ",i[1])
print("class :",i[2])
print("marks :",i[3])
except:
print()
f.close()
15. Ans:
i) pickle
ii)fout=open("temp.dat",”wb”)
iii) rec=pickle.load(fin)
iv) pickle.dump(rec,fout)
1. Ans:
cobol
7
['java', 'c++', 'python', 'basic', 'vb', 'vc++', 'php', 'c#']
['basic', 'c#', 'c++', 'java', 'php', 'python', 'vb', 'vc++']
4
2. Ans
(i) Index 4 is out of range, because List1 contains 4 items (Index 0 to 3 only)
(ii) String is immutable type so we can’t change any character of string in place.
3. Ans
(i) [10,20,30,40,70]
(ii) [10,20,30,40,70,100]
(iii) [10,20,30,40,70]
(iv) 70
4. Ans:
def sumAlternate(MYLIST):
sum=0
for i in range(0,len(MYLIST),2):
sum+=MYLIST[i]
print("Total = ",sum)
5. Ans
def EvenOdd(MYLIST):
for i in range(len(MYLIST)):
if MYLIST[i]%2==0:
MYLIST[i]//=2
else:
MYLIST[i]*=2
6. Ans:
(i) print(len(MYLIST))
(ii) print(MYLIST.count(30))
(iii) import bisect
bisect.insort(MYLIST,45)
print(MYLIST)
(iv) MYLIST.remove(17)
print(MYLIST)
7. Ans
def Push(Employee):
name=input('Enter Employee name ')
Employee.append(name)
def Pop(Employee):
if len(Employee)==0: # or if Employee==[ ]:
print('Underflow')
else:
name = Employee.pop()
print('Popped Name was ',name)
8. Ans
def SwapMiddle(Codes):
i=0
144
mid = len(Codes)//2
while i<mid:
Codes[i],Codes[mid+i]=Codes[mid+i],Codes[i]
i+=1
9. Ans:
def Push(Package):
Empid=int(input(“Enter Id of Employee: "))
Ename=input(“Enter Name of employee”)
Salary= int(input(“Enter Salary of an employee”))
T=(Empid, Ename ,Salary)
Package.append(T)
def Pop(Package):
if (Package==[]):
print( "Stack empty")
else:
print ("Deleted element:",Package.pop())
10. Ans
def selection_sort(DATA_LIST):
for i in range(0, len (DATA_LIST)):
min = i
for j in range(i + 1, len(DATA_LIST)):
if DATA_LIST[j] < DATA_LIST[min]:
min = j
# swapping
temp= DATA_LIST[min]
DATA_LIST[min] = DATA_LIST[i]
DATA_LIST [i]=temp
print(DATA_LIST)
DATA_LIST = [99 78 25 48 51 11]
print “LIST BEFOR SORTING”,DATA_LIST
selection_sort(DATA_LIST)
**********************************************************************************************
Exam preparation tips
THANK YOU.
145