0% found this document useful (0 votes)
258 views145 pages

Studymaterial Cs Xii 2022 23 Robbsr

Uploaded by

Ayush Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
258 views145 pages

Studymaterial Cs Xii 2022 23 Robbsr

Uploaded by

Ayush Tiwari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

KENDRIYA VIDYALAYA SANGATHAN

BHUBANESWAR REGION

केंद्रीय विद्यालय संगठन


भुवनेश्वर संभाग

STUDENT SUPPORT MATERIAL


XII - COMPUTER SCIENCE (083)
2022 – 2023
1
CHIEF PATRON

DR. SHIHARAN BOSE


DEPUTY COMMISSIONER
KVS RO, BHUBANESWAR

PATRON

SH. A JYOTHI KUMAR


ASST. COMMISSIONER
KVS RO, BHUBANESWAR

COORDINATOR

SH. S. K. DASH
VICE PRINCIPAL, KV NO.3, BHUBANESWAR
AND PRINCIPAL I/C, KV, NAYAGARH

ASSOCIATE COORDINATOR

MS. KABITA HAZRA, PGT, CS


KV. NO.1, BHUBANESWAR, SHIFT-1

CONTENT CONTRIBUTION

MS. DEEPA BEHERA, PGT, CS, KV, ROURKELA


(REVISION TOUR)

MS. RENU SINGH, PGT, CS, KV, BOUDH,


(COMPUTATIONAL THINKING AND PROGRAMMING)

MR. ANIL KUMAR, PGT, CS, KV. NO.6, BHUBANESWAR,


(COMPUTER NETWORKS)

MS. ANKITA AWASTHI, KV. NO.1, BHUBANESWAR, SHIFT-2


(DATABSE MANAGEMENT SYSTEM)

MS. KABITA HAZRA, PGT, CS, KV. NO.1, BHUBANESWAR, SHIFT-1


INTERFACING PYTHON AND MYSQL

2
INDEX
S. NO. NAME OF THE CHAPTER/UNIT PAGE NO

1 REVIEW OF PYTHON 7 - 19

2 FUNCTIONS 20 - 27

3 DATA FILE HANDLING 28 - 34

4 DATA STRUCTURE 35 - 39

5 COMPUTER NETWORKS 40 - 64

6 DATABASE MANAGEMENT SYSTEM 65 - 76

7 INTERFACE PYTHON WITH MYSQL 77 - 81

8 SAMPLE PAPERS 82 - 124

9 APPENDIX 125 - 145


1. Keywords, Operator precedence
2. Mathematical Functions
3. String Functions and methods
4. List functions and methods
5. Tuple functions and methods
6. Dictionary functions and methods
7. Answer key

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

4. Unit wise Syllabus


Unit I: Computational Thinking and Programming – 2
• Revision of Python topics covered in Class XI.
• Functions: types of function (built-in functions, functions defined in module, user defined functions),
creating user defined function, arguments and parameters, default parameters, positional parameters,
function returning value(s), flow of execution, scope of a variable (global scope, local scope)
• Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths
• Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a file
using with clause, writing/appending data to a text file using write() and writelines(), reading from a
text file using read(), readline() and readlines(), seek and tell methods, manipulation of data in a text file
• Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab, ab+),
close a binary file, import pickle module, dump() and load() method, read, write/create, search, append
and update operations in a binary file
• CSV file: import csv module, open / close csv file, write into a csv file using csv.writer() and read from a
csv file using csv.reader( )
• Data Structure: Stack, operations on stack (push & pop), implementation of stack using list.

Unit II: Computer Networks


● Evolution of networking: introduction to computer networks, evolution of networking (ARPANET, NSFNET,
INTERNET)
4
● Data communication terminologies: concept of communication, components of data communication (sender,
receiver, message, communication media, protocols), measuring capacity of communication media (bandwidth,
data transfer rate), IP address, switching techniques (Circuit switching, Packet switching)
● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable),
Wireless media (Radio waves, Micro waves, Infrared waves)
● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card)
● Network topologies and Network types: types of networks (PAN, LAN, MAN, WAN), networking topologies
(Bus, Star, Tree)
● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP
● Introduction to web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup Language
(XML), domain names, URL, website, web browser, web servers, web hosting

Unit III: Database Management


• Database concepts: introduction to database concepts and its need
• Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key,
primary key, alternate key, foreign key)
• Structured Query Language: introduction, Data Definition Language and Data Manipulation Language,
data type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create
database, use database, show databases, drop database, show tables, create table, describe table, alter
table (add and remove an attribute, add and remove primary key), drop table, insert, delete, select,
operators (mathematical, relational and logical), aliasing, distinct clause, where clause, in, between,
order by, meaning of null, is null, is not null, like, update command, delete command, aggregate
functions (max, min, avg, sum, count), group by, having clause, joins: cartesian product on two tables,
equi-join and natural join
• Interface of python with an SQL database: connecting SQL with Python, performing insert, update,
delete queries using cursor, display data by using fetchone(), fetchall(), rowcount, creating database
connectivity applications

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.

7. Suggested Reading Material


NCERT Textbook for COMPUTER SCIENCE (Class XII)
Support Materials on the CBSE website.

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.

Classify the following into valid and invalid identifier.


(i) Total (ii) break (iii) _Sum (iv) My%book (v) Annual_Income
(vi) 10_discount (vii)percent (viii) True (ix) Paid interest (x) class
Ans:
(i) valid (ii) Invalid(keyword) (iii) valid (iv) Invalid(special symbol) (v)valid
(vi) invalid (digit in starting position) (vii) valid (viii) invalid (keyword) (ix)invalid (space)
(x) invalid (keyword)

3. Literals- A fixed numeric or non-numeric value.


1. String literals
2. Numeric literals
3. Boolean literals
4. Special literals

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

Floating Point literals:


These are real numbers having both integer and fractional parts.
a = 45.5
print(a)
OUTPUT:
45.5

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

4. Operators –Symbol used to performs some action on data.


• Arithmetic (+, -, *, /, %, **, //)
• Bitwise operator( & , ^ , | )
• Shift operator( << ,>> )
• Relational /comparison (< , > ,<=, >=, = =, !=)
• Assignment (=)
• Arithmetic assignment operator(compound assignment operator) ( /=, +=, -=, *=, %=, **=, //=)
• Logical (and, or, not)
• Identity (is, is not)
• Membership (in, not in)
Precedence of operators is given in Appendix-1

5. Punctuators: It is a symbol to organize sentence structure. ‘ “ # \ () [] {} @ , : . ` =

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 { }

Mutable and Immutable data Types


If the values can be changed after creating the variable and assigning values, then it is called Mutable.
If the value assigned cannot be changed after creating and initializing it, then it is known as
Immutable. When an attempt is made to update the immutable type, a new memory location is used
with name remaining the same.

Immutable data types Mutable data types


bool, int, float, complex, string, tuple list, dictionary

Implicit and Explicit Type Conversion


Python converts data type into another type automatically called implicit type conversion
a=7 # a to int
b = 3.0 # b to int
c=a+b # Python automatically converts c to float as it is a float addition
d=a*b # Python automatically converts d to float as it is a float multiplication
Explicit type conversion also called type-casting is user-defined conversion that forces an
expression to be specific type. Type casting can be done using the constructor methods of
corresponding data types like -
• int() : int() function take float or string as an argument and return int type object.
• float() : float() function take int or string as an argument and return float type object.
• str() : str() function take float or int as an argument and return string type object.
a=5 # int variable
n = float(a) # typecast to float
a = "5" # string variable
n = int(a) # typecast to int

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

Operation Description Example


Concatenation Str1 + Str2 >>“power” + “full”
‘powerful’
10
Repetition Str * x >>“Hai” * 3
‘HaiHaiHai’
Membership in , not in >>>“a” in “India”
True
>>>“a” not in “India”
False
Comparison == , != , > , < ,<= ,>= >>>"India"<"world"
True
>>>"India"=="world"
False

Slicing String[range] >>>word= “amazing”


>>>word[1:3]
“ma”
>>>word[:3]
“ama”
>>>word[3:]+word[:3]
‘zingama’
String Methods and Built-in functions given in Appendix-3

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]

Operation Description Example


Concatenation L1+ L2 >> [1,2,3] + [4,5]
[1,2,3,4,5]
Repetition L*n >> [1,2] * 3
[1,2,1,2,1,2]
Membership in , not in >>>1 in [1,2,3]
True
>>>2 not in [1,2,3]
False
Slicing String[range] >>>L=[10,20,30,40,50,60]
>>>L[1:4:2]
[20,40]
>>>L[:4]
[10,20,30,40]
>>>L[ : :-1]
[60,50,40,30,20,10]
Methods and functions used with lists are given in Appendix-4
11
Tuples
Tuple is another sequence in python. It consists of multiple values in a single variable separated
by commas. Tuples are enclosed within parentheses ( ). Tuple is an immutable data type.

Examples:
T=( ) #empty tuple
T=10,
T=(10,)
T=(123, “Hello”, 6.8)

Common Tuple Operations:


Operation Description
Concatenation Tuple1 + Tuple2
Repetition Tuple * x
Index Tuple[index]
Membership in and not in
Slicing Tuple[range]

Functions used with Tuples is given in Appendix-5

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}

Functions used with dictionary are given in Appendix-6

1 Mark Questions

1. State True or False


“input() returns the value of string data type.”

2. Which of the following is an invalid identifier in Python?


(a)continue (b) sum_five (c)_percent (d) add_10

3. Given the following dictionaries


dict_exam={"Exam":"AISSCE", "Year":2023}
dict_result={"Total":500, "Pass_Marks":165}
dict_exam.update(dict_result)
print(dict_exam)
Find the output ?
a. {'Exam': 'AISSCE', 'Year': 2023}
12
b. {'Exam': 'AISSCE', 'Year': 2023, 'Total': 500,
'Pass_Marks': 165}
c. {'Total': 500, 'Pass_Marks': 165}
d. None

4. Consider the given expression:


not True or False and not False
Which of the following will be correct output if the given expression is evaluated?
(a) True
(b) False
(c) None
(d) NULL

5. Select the correct output of the code:


x = "Python is an interpreted language"
y = x.split('i')
z = y[0] + "." + y[1] + "." + y[2]
print(y)
(a) Python .i. s an
(b) Python .i. nterpreted language
(c) Python .i. interpreted language
(d) Python .s an .nterpreted language

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

7. What will the following expression be evaluated to in Python?


print(18.0 / 3 * 5.5 - 20)
(a) 13 (b) -5.14 (c) 13.0 (d) 5.14

8. Find the invalid keyword from the following


a) assert b) nonlocal c) eval d) global

9. Given the lists L=[1,3,6,82,5,7,11,92] , write the output of print (L[-5:-2]) .

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])

15. The return type of the input() function is


a. string
b. integer
c. list
d. tuple

16. Write the type of tokens from the following:


(i) in (ii) First_Name

17. Name the Python Library modules which need to be imported to invoke the following functions:
(i) tan() (ii) randrange ()

18. Which is the correct form of declaration of dictionary?


(i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
(ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
(iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
(iv) Day={1’monday’,2’tuesday’,3’wednesday’]

19. Find and write the output of the following python code:
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")

20. What will be the output of the following code ?


print(“100+200”)
(i) 300 (ii) 100200 (iii) 100+200 (iv) 200

21. What is the output of the following ?


x = 123
for i in x:
print(i)
(i) 123 (ii) 1 2 3 (iii) error (iv) infinite

22. What is the value of this expression 3**3**1 ?


(i) 27 (ii) 9 (iii) 3 (iv) 1

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

27. Write the output of the following python expression:


print((9>6) and (2!=2) or (4<8))
(i) False (ii) True (iii) false (iv) true

28. What is the output when we execute list(“hello”)?


a) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’] c) [‘hello’]
b) [‘llo’] d) [‘olleh’]

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]

30. To insert 5 to the third position in list1, we use which command?


a) list1.insert(3, 5)
b) list1.insert(2, 5)
c) list1.add(3, 5)
d) list1.append(3, 5)

31. Find the output of following code?


list2 = [30, 40, 50, 20]
list2.extend([34, 5])
print(list2)

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)

33. Which of the following is not a declaration of the dictionary?


a) {1: ‘A’, 2: ‘B’} b) dict([[1,”A”],[2,”B”]])
c) {1, “A”,2 “B”} d) { }

34. Which of the following isn’t true about dictionary keys?


a) More than one key isn’t allowed
b) Keys must be immutable
c) Keys can be List
d) When duplicate keys encountered, the last assignment wins

35. What will be the output of the following Python code?


a={}
a[2]=10
a[1]=[12,33,44]
15
print(a[1][1])
a) [12,13,44] b) 33 c) 12 d) An exception is thrown

36. What will be the output of the “hello” +1+2+3?


a) hello123 b) hello c) Error d) hello6

37. Find the output :


print(ord(‘z’) – ord(‘a’))?
a) 25 b) 26 c) -25 d) -26

38. What will be the output of the following Python code?


print("RAHUl is Playing".capitalize())

39. What will be the output of the following Python code?


print(‘my_string’.isidentifier())
a) True b) False c) None d) Error

40. What will be the output of the following Python code?


print(‘ringaringaroses.lstrip(‘ringa’))
a) oses b) roses
c) ringaroses d) None

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])

43 Find the output of the following code:


s1="Python"
s2="Programming"
s3=s1+s2
print(s3[10: :-2])

44. dc1={}
dc1[2]=6
dc1['10']=2
dc1[2.0]=5
s=0
for i in dc1:
s+=dc1[i]
print(s)

45. tup = tuple({1:"Rahul",2:"Sourav",3:"Sachin"})


print(tup)

46. Find the output of the following code:


val = (10,20,30)
a,b,c = val
16
b=40
val=(a,b,c)
print(val)

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)

50. Find the output of following code:


dict_exam={"Exam":"AISSCE", "Year":2023,"Exam":"AISSE"}
print(dict_exam)

2 Mark Questions

1. (a) Given is a Python string declaration:


My_dict="CBSE EXAMINATION 2023”
Write the output of: print(My_dict[15::-2])
(b) Write the output of the code given below:
my_dict = {"Name": "Rahul", "age": 40}
my_dict['age'] = 45
my_dict['address'] = "Bhubaneswar"
print(my_dict.items())

2. Predict the output of the Python code given below:


item={ }
M=['ball', 'pen' ,'ball' , 'pencil']
for index in M:
if index in item:
item[index]+=1
else:
item[index]=1
print(item)

3. Predict the output of the Python code given below:


val=[ ]
for i in range (10,14):
val.append(i)
print(val)

4. Predict the output of the code given below:


17
Text="gmail@com"
L=len(Text)
N=""
for i in range(0,L):
if Text[i].isupper():
N=N+Text[i].lower()
elif Text[i].isalpha():
N=N+Text[i].upper()
else:
N=N+'bb'
print(N)

5. Predict the output of the code given below:


Msg1="Good*Morning"
Msg2="India"
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)

6. Evaluate the following expressions:


a) (5 * 3 + 3**2 // 10 - 8)
b) (20 > 15 or 7 > 10 and not 14 > 4)

7. i) Find out the output of the Following –


x=20
x=x+5
x=x-10
x,y=x-1,50
print(x,y)

ii) Find out the output of the Following –


x,y,z=5,10,15
x,y,x,z=y-5,x+2,z-3,x+5
print(x,y,z)

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)

10. Predict the output of the code given below:


my_dict={}
my_dict[(1,2,4)]=5
my_dict[(4,2,1)]=4
my_dict[(1,2)]=8
sum=0
for k in my_dict:
sum+=my_dict[k]
print(sum)
print(my_dict)

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

6. which of the following statement is a function call?


a. call sum() b. def sum() c. sum() d. function sum()

7. Which of the following statement is not true regarding functions?


a. A function definition begins with “define”
b. A function may or may not have parameters.
c. A function may or may not return value.
d. Function header always ends with a colon(:)

8. def cal(n1): what is n1?


a. Parameter b. Argument c. Keyword d. None of the above

9. Choose the correct answer


def s(n1):
print(n1)
n2=4
s(n2)
22
Statement A: n1 and n2 have same memory Address
Statement B : both n1 and n2 are referring to the same value, so they have same identity
a. Statement A is True and Statement B is False
b. Statement A is False and Statement B is True
c. Both the statements are True
d. Both the statement are False

10. Write the output of the following :


def cal(m,n):
if m==n:
return m*3
else:
return m*2
s=cal(9,8)
print(s)

a. 16 b. 18 c. 27 d. 24

11. Which of the following function definition header is wrong?


a. def sum(n1,n2,n=3):
b. def sum(p1,p2=4,p3=5):
c. def div(p1=4,p2,p3):
d. def mul(p1,n1,m1):

12. A function may return multiple values using _____________.


a. List b. Tuple c. String d. Dictionary

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

14. Which module is to be imported for using randint() function?


a. rand b. random c. randrange d. randomrange

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

16. Write the output of :


print(abs(-45))
a. 45.0 b. -45 c. 45 d. None of the above

17. Which of the following statement is correct?


a. A python standard library consists of a number of modules
b. A module consists of a number of Python standard libraries
c. Library and modules are alias of each other.
d. None of the above.

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#

20. What will be the output of the following code?


x=3
def myfunc():
global x
x+=2
print(x,end=’ ‘)
print(x,end=’ ‘)
myfunc()
print(x,end=’ ‘)
a. 3 5 5 b. 5 5 5 c. 5 3 5 d. 3 3 5

Short answer questions: (2 ,3 marks)

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#

2. Find and write the output of the following python code:


def Change(P ,Q=30):
P=P+Q
Q=P-Q
print( P,"#",Q)
return (P)
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
24
3. Write output :
def CALLME(n1=1,n2=2):
n1=n1*n2
n2+=2
print(n1,n2)
CALLME()
CALLME(2,1)
CALLME(3)

4. What will be the output of following code?


v=50
def display(n):
global v
v=25
if n%7==0:
v=v+n
else:
v=v-n
print(v,end="#")
display(20)
print(v)

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()

7. Write the output of the following Python program code:


def show(mystr):
newstr = " "
for x in mystr:
if x.isupper():
newstr += x.lower()
elif x.islower():
newstr += x.upper()
else: newstr += x
print("The new string is:", newstr)
25
show("PasS@2022")

8. Rewrite the following code after removing all errors


def Tot(Number) #Method to find Total
Sum=0
for C in Range (1, Number+1):
Sum+=C
RETURN Sum
print Tot[3] #Function Call

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.

13. Show output of following:


def Show(STR, KEY):
x=0
L=len(STR)
while x < (L//2):
if x%2 is not 1:
print( STR[x] * KEY )
else:
print( STR[x] * (KEY+1) )
x+=1
KEY+=2
Show("PYTHON",1) #calling function show()

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')

15. Write output of following code


def Alter(x,y=20):
x=x*y
y=x%y
print (x,'*',y)
return (x)
a=200
b=30
a=Alter(a,b)
print (a,'$',b)
b=Alter(b)
print (a,'$', b)
a=Alter(a)
print (a,'$',b)

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

17. Find error in following code:-


def DEFA_ARG(n1=1, n2=2,n3):
n1=n1+n2
n2+=n3
print (nl ,n2,n3)
Check()
Check(2, 1)
Check(3,4,5)

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.

Steps in Data File Handling


1. OPENING FILE  We should first open the file for read or write by specifying the name of file
and mode.
2. PERFORMING READ/WRITE  Once the file is opened, we can either read or write for which
file is opened using various functions available
3. CLOSING FILE  After performing operation we must close the file and release the file for other
application to use it,

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”

File Access Modes


Text File Binary File Description Notes
Mode Mode
r Rb Read only File must exists, otherwise
Python raises I/O errors

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()

Reading from File


o To read from file python provide many functions like :
▪ Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire
file.
▪ Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n
bytes. Read bytes in the form of string ending with line character or blank string if no
more bytes are left for reading.
▪ Filehandle.readlines(): reads all lines and returns them in a list
Writing onto files
o After read operation, let us take an example of how to write data in disk files. Python
provides functions:
▪ write ()
▪ writelines()
o The above functions are called by the file handle to write desired content.
Name Syntax Description
write() Filehandle.write(str1) Writes string str1 to file referenced by filehandle

Writelines() Filehandle.writelines(L) Writes all string in List L as lines to file


referenced by filehandle.
File Pointer
o Every file maintains a file pointer which tells the current position in the file where reading
and writing operation will take.
o When we perform any read/write operation two things happens:
▪ The operation at the current position of file pointer
▪ File pointer advances by the specified number of bytes.
Binary file operations

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)

COMMA SEPARATED VALUE (CSV FILE)


o CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
o Files in the CSV format can be imported to and exported from programs that store data in
tables, such as Microsoft Excel or OpenOffice Calc.
o CSV stands for "comma-separated values“.
o A comma-separated values file is a delimited text file that uses a comma to separate values.
o Each line of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file
format

CSV file handling in Python:


To perform read and write operation with CSV file, we must import csv module.
open() function is used to open file, and return file object.
o Reading from CSV file
 import csv module
 Use open() to open csv file, it will return file object.
 Pass this file object to reader object.
 Perform operation you want
o How to create CSV file
Method 1 (From MS-Excel):
1. Open Excel, delete all the sheet except sheet
2. Type all the data, in separate cells
3. Save it as csv file in your desired location.
4. If any warning comes, click on „YES‟
5. When you close the excel, choose „NO‟
6. Now file is created at your desired location, go and double click or open with
notepad to check the content
Method 2 (From Notepad):
1. Open Notepad
2. Type record by separating each column value by comma(,)
3. Every record in separate line
4. Save it by giving extension .csv (PUT THE NAME IN DOUBLE QUOTES
TO ENSURE .TXT WILL NOT BE APPENDED WITH FILE NAME FOR
E.G. if you want it to save with name emp then give name as “emp.csv” in
double quotes
5. File is created close it and double click to open and check

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

Multiple Choice Questions: (1 Mark)

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()

6. Which module is required to use built in function dump()


a. Math b. flush c. pickle d. unpickle

7. Which of the following function is use to write data in binary mode?


a. write b. output c. dump d. send

8. Unpickling is done by______________.


a. open() b. close() c. load() d. dump()
9. In separated value files such as .csv , what does the first row in the file typically contain?
a. The author of the table data
31
b. The source of the data
c. Notes about the table data
d. The column names of the data
10. Assume you have a file object my_data which has properly opened a separated value file that
uses the tab character (\t) as the delimiter. What is the proper way to open the file using the
Python csv module and assign it to the variable csv_reader? Assume that csv has already been imported.
a. csv.tab_reader(my_data)
b. csv.reader(my_data)
c. csv.reader(my_data, delimiter='\t')
d. csv.reader(my_data, tab_delimited=True)

Short Answer type Questions (2 , 3 Marks):

1. Considering the content stored in file “EXAM.TXT”


See, you hear this word and shiver
While some of us get problems of the liver
yup! Exams are what I'm talking about
The reason pupils start howling about
Oh exams! What do we do with you
As it approaches, students be like
A reaction no one ever seen like
In our dreams like a monster sneaks up
Within our soul like Death creaps up
Oh exams! What do we do with you
Write the output of following statements –
f = open("EXAM.TXT")
sr1 = ____________ # to read first line of file
str2 = ___________ # to read next line 10 character of file
str3 = ___________ # to read remaining lines of file

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.

7. Consider the following code and complete the missing statement.


import pickle
f2=open('sdata.dat','rb')
d1=____________
print(d1)

8. Consider the following code and complete the missing statement.


32
import pickle
f1=open('sdata.dat','wb')
roll=int(input('Enter your roll number'))
name=input('Enter your name')
dt={'Roll':roll,'Name':name}
________________#statement to write dictionary into file
f1.close()

9. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


a. Write a user defined function CreateFile() to input data for a record and add to book.dat.
b. Write a function CountRec(Author) in python which accepts the Author Name as parameter
and count and return number of books by the given Author are stored in the binary file “
Book.dat”
10. A binary file “Student.dat” has structure [admission_No, name, percentage]. Write a function
countrec() in python that would read contents of the file “ Student.dat” and display the details of
those students whose percentage is above 75. Also display number of students scoring above 75%.

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.

12. Write a function to read entire data from the data.csv

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:

import _______ #Statement 1


def update_data():
rec={}
fin=open("record.dat","rb")
fout=open("_____________") #Statement 2
found=False
eid=int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=______________ #Statement 3
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary:: "))
pickle.____________ #Statement 4
else:
pickle.dump(rec,fout)

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.

TYPES OF DATA STRUCTURE

Data structure can be classified into following two types:


o Simple Data structure : these are built from primitive data types like integer, float, string or
Boolean. Example: Linear List or Array
o Complex Data structure : simple data structure can be combined in various way to form
more complex data structure. It is of two types:
▪ Linear : are single level data structure i.e. in linear fashion to form a sequence.
Example : STACK, QUEUE, LINKED LIST
▪ Non-Linear: are multilevel data structure. Example: TREE and GRAPH.
STACK
o Allow to insert and delete items from one end only called TOP.
o Stack works on LIFO principle. It means items added in list will be removed first.
o Real life Example: Stack of Plates, Books, Bangles
o Computer based examples: Undo Operation, Function Call etc.
QUEUE
o Allows insertion and deletion from different end i.e. insertion from REAR and deletion from
FRONT
o Queue works on FIFO principle i.e. item added first will be removed first.
o Real life example: Queue of People for ticket
o Computer based example: Keyboard typing, Printer etc.

OPERATIONS ON DATA STRUCTURE

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.

Multiple Choice Question (1mark)

1. Stack is a data structure that follows _________ order


a. FIFO b. LIFO c. LILO d. FILO

2. Process of inserting an element in stack is called ____________


a) Create b) Push c) Evaluation d) Pop

3. In a stack, if a user tries to remove an element from empty stack it is called


a) Underflow b) Empty collection c) Overflow d) Garbage Collection

4. Entries in a stack are “ordered”. What is the meaning of this statement?


a) A collection of stacks is sortable
b) Stack entries may be compared with the ‘<‘ operation
c) The entries are stored in a linked list
d) There is a Sequential entry that is one by one

5. The type of expression in which operator succeeds its operands is?


a) Infix Expression
b) pre fix Expression
c) postfix Expression
d) None

6. Consider the following operation performed on a stack of size 5.


Push(1);
Pop();
Push(2);
Push(3);
Pop();
Push(4);
36
Pop();
Pop();
Push(5);
After the completion of all operation, the number of elements present in stack are
a) 1 b) 2 c) 3 d) 4

7. Which data structure is needed to convert infix notation to postfix notation?


a) Branch b) Tree c) Queue d) Stack

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

11. Insertion in a linear list, which statement is true


i)if the array is unordered, the new element is inserted at the end of the array.
ii)if the array is sorted then new element is added at appropriate position without altering the
order and to achieve this, rest of the elements are shifted.
a) i
b) ii
c) i and ii
d) None

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

2 , 3 and 4 marks Questions

1. What will be the output of the following Python code :


mylist =[‘java’,’c++’,’python’,’vb’,’vc++’,’php’,’cobol’]
print(mylist.pop())
mylist.append(‘c#’)
print(len(mylist))
mylist.insert(3,’basic’)
print(mylist)
mylist.sort()
print(mylist)
print(mylist.index(‘php’))

2. Identify the error in following code:


(i) List1 = [10,20,30,40]
List1[4]=100
(ii) Name=”Michael Jackson”
Name[2]=”k”

3. Write down the status of Stack after each operation:


Stack =[10,20,30,40] where TOP item is 40
(i) Push 70
(ii) Push 100
(iii) Pop an item from Stack
(iv) Peek the Stack

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]

6. Given the list: MYLIST = [5,11,17,19,25,29,30,30,32,46,90]


Write down the Python statements for the following requirement:
38
(i) To find the number of items in MYLIST
(ii) To find the frequency of item 30 in MYLIST i.e. how many times 30 is in MYLIST
(iii) Write the code to insert 45 in the above sorted list to its correct position (do not disturb the
sorting)
iv) Write the code to delete 17 from the above sorted list

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

10. Consider the following unsorted list:


99 78 25 48 51 11
Sort the list using selection sort algorithm. Show the status of the list after every iteration.

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.

Peer-to-Peer Network (P2P)


As the name suggests, Each computer controls its own information and plays role of either aclient or a
server(due to which efficiency is lesser). There is no in-charge of the network.
Peer-to-peer computers are often termed as non-dedicated servers.
Such Networks are popular in home networks, small companies as they are easy to install andcheaper.
Although the scope is limited.
Blockchain is the best example.
The Client Server Network
Bigger networks prefer to have centralized control. Dedicated servers and clients are there. Task
specified servers also exists, e.g. file server, printer server, modem server. The key point of this model is
that client is dependent on server to provide and manage information. They are also known as
Master-Slave networks. e.g. Websites are stored on web servers, web browser is the client which
makes a request to the server.

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)

Data Transfer Rates


It represents the amount of data transferred per second by a communication channel or acomputing or
storage device.
It's measured in units of bits per second(bps), bytes per second(Bps), or baud.
When "Kilo", "Mega", "Giga" prefixes are applied they denote power of 1000. Whereas in units of
storage they stand for powers of 1024. e.g. 1Kbps = 1000bps | 1KB = 1024bytes

1 Bps = 8 bps 1 KB = 1024 bytes


1 Kbps = 1000 bps 1 MB = 1024 KB
1 Mbps = 1000 Kbps 1 GB = 1024 MB
1 Gbps = 1000 Mbps 1 TB = 1024 GB or 2^40 bytes

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.

Bus or Linear Topology


It consists of a single transmission medium(generally coaxial cable) onto which variousnodes
are attached. Transmission from any node travels in both directions to the whole bus, and can
be received by all other stations. At both ends there are terminators which removes the
travelling data token from the network.
• It's easy to connect a computer to a linear bus.
Requires less cable length than a start topology.
• Entire network shuts down, if main
cable fails.
• Terminators are required at both ends.
• Diagnosis is difficult if entire network shuts down.
• Can't use it as a stand-alone topology in a large building.

Ring or Circular Topology


Each node is connected to exactly two neighboring nodes. Data is accepted from one of the
neighboring nodes and is transmitted onwards to another. Generally, data tokens travels in one
direction(unidirectional ring) from node to node around the ring. After passing through each node, it
returns to the sending node, which removes it or it stops until it has reached destination.
• All packets flow in one direction, reducing chances of packet collisions.A server is not
needed to control connectivity.
• Transfer speed is good.
• New nodes can be added without impacting performance of the network.
Disadvantages
• Data transferred must pass through each node which makes it slower than star topology.
• Entire network will be impacted if one workstation shuts down.
• Hardware needed to connect each workstation to the network is more expensive than
• hubs/switches and ethernet cards.

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.

RJ45(Registered Jack 45) Connector


This 8-pin plug or jack is commonly used to connect computers
onto Ethernet-based localarea networks.

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.

FTP(File Transfer Protocol)


It's a standard for the exchange of files across internet. Files of any type can be transferred, although type of
file needs to be specified. It's useful in transferring files from one network to other. Different groups can
45
co-operate on a same project even from long distances.

HTTP(Hypertext Transfer Protocol)


It's the set of rules for transferring hypertext that is text, graphic, image, sound, video, etc. on
WWW(World Wide Web). It has the required lightness and speed for distributive, collaborative,
hypermedia information systems. HTTP is also used as a generic protocol for communication
between user agents and gateways to other internet protocols such as SMTP,FTP, etc.

TCP/IP(Transmission Control Protocol/Internet Protocol)


It's the base communication protocol of the internet. IP uses numeric IP addresses to join network
segments and TCP provides reliable delivery of messages between computers on the network. It makes
sure all the data packets are sent and received correctly. TCP/IP is a layeredset of protocols.

PPP(Point to Point Protocols)


It's the Internet Standard for transmission of IP packets over serial lines. As the name suggests it's a
protocol used to establish direct connection between two computers(points) using telephone lines.

SMTP(Simple Mail Transfer Protocol)


It's the internet standard for electronic mail(e-mail) transmission across IP(Internet Protocols) networks. E-
mail server uses SMTP to send and receive mail messages, although user-level applications use SMTP
only for sending messages. For receiving messages, they usually useeither POP(Post Office Protocol) or
iMAP(internet Message Access Protocol).

POP(Post Office Protocol)


It's the standard protocol used by local e-mails clients to retrieve emails from a remote server over a
TCP/IP connection. POP(Post Office Protocol) or iMAP(internet Message Access Protocol) are the most
prevalent Internet standard protocols for email retrieval. POP3 is the current latest version which is
used by most webmail services like Gmail, Hotmail and Yahoo mail.

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.

ARPANET(Advanced Research Projects Agency Network)


The U.S. Department of Defense sponsored a project named a ARPANET(Advanced Research Projects
Agency NETwork) to connect computers at different universities and U.S. defense, messages and data
were exchanged. It was the first wide-area packet-switching network withdistributed control, it was the
first network to implement the TCP/IP protocol.

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.

GSM(Global System for Mobile communication)

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.

GPRS(General Packet Radio System)


GPRS is a third-generation technology for radio transmission of small packets of data especially
between mobile devices and internet. It's also known as GSM-IP(Global SystemMobile
Communications Internet Protocol) as it keeps user online and allows them to makevoice calls and
access internet.

WLL(Wireless in Local Loop)


WLL/WiLL is the system which connects subscribers to the Public Switched Telephone Network(PSTN)
through a radio link instead of copper wires. It's analogous to telephone service but wireless and more
capable. It's more reliable and enhanced technology which offers high quality data transmission. It has
much better bandwidth than traditional telephone system.

CDMA(Code Division Multiple Access)


This digital wireless telephony transmission technique uses spread-spectrum allows multiple
frequencies to be used simultaneously. Unlike GSM, that uses TDMA, CDMA doesn't assign a specific
frequency to each user. Instead, every channel uses the full available spectrum.

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.

Voice over Internet Protocol(VoIP)


It's communication protocols and transmission technologies for delivery of voice communicationsand
multimedia sessions over Internet Protocol(IP) networks, such as the internet. VoIP is also known as IP
telephony, Internet telephony and broadband telephony.

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.

WWW(World Wide Web)


WWW is a set of protocols that allows you to access any document on the internet through anaming
system based on URLs. It also specifies a way(HTTP) to request and send a document over the
internet. Before WWW, Internet was mainly used for obtaining textual information. After WWW
internet popularity grew tremendously.

HTML(Hyper Text Markup Language)


HTML is the coding language used to create Hypertext documents for use on the World WideWeb. It's the
standard markup language for web pages.

XML(Extensible Markup Language)


It's a markup language that defines a set of rules for encoding documents in a format that is both
human-readable and machine-readable. It was designed to store and transport data. It doesn't do anything,
it's just information wrapped in tags.

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.

Networking MCQ Questions -1 Mark


1 A computer network:
(a) Is a collection of hardware components and computers
(b) Is interconnected by communication channels
(c) Allows sharing of resources and information
(d) All of the above

2 MAN Stands for _____.


(a) Metropolitan Area Network
(b) Main Area Network
(c) Metropolitan Access Network
(d) Metro Access Network

3 Which of these is not an example of unguided media?


(a) Optical Fibre Cable
(b) Radio wave
(c) Bluetooth
(d) Satellite
49
4 In which topology are all the nodes connected through a single Coaxial cable?
(a) Star
(b) Tree
(c) Bus
(d) Ring

5 What is a standalone computer?


(a) A computer that is not connected to a network
(b) A computer that is being used as a server
(c) A computer that does not have any peripherals attached to it
(d) A computer that is used by only one person

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

8 Which transmission media is capable of having a much higher bandwidth (data


capacity)?
(a) Coaxial
(b) Twisted pair cable
(c) Untwisted cable
(d) Fiber optic

9 Which type of transmission media is the least expensive?


(a) Coaxial
(b) Twisted pair cable
(c) CAT cable
(d) Fiber optic

10 Find the odd one transmission media from the following?


(a) Coaxial cable
(b) Twisted pair cable
(c) CAT cable
(d) LAN cable

11 Which of these components is internal to a computer and is required to connect the


computer to a network ?
(a) Wireless Access Point
(b) Network Interface card
(c) Switch
(d) Hub
50
12 A device that forwards data packet from one network to another is called a
(a) Bridge
(b) Router
(c) Hub
(d) Gateway

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

15 Which of the following is not a type of cloud?


(a) Private
(b) Public
(c) Protected
(d) Hybrid

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

17 In computers, converting a digital signal into an analogue signal is called


(a) modulation
(b) demodulation
(c) conversion
(d) transformation

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.

19 What is the address size of IPv4?


(a) 32 bit
(b) 64 bit
(c) 128 bit
(d) 256 bit

20 What is the address size of IPv6?


(a) 32 bit
51
(b) 64 bit
(c) 128 bit
(d) 256 bit

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

23 Bionic Connector is used for ___________.


(a) CAT6 Cable
(b) Coaxial Cable
(c) Twisted pair cable.
(d) Fiber Cable

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

27 Network device which connects networks of similar types (same protocols).


(a) Hub
(b) Router
(c) Bridge
(d) Gateway

28 Network device which connects dissimilar networks (different protocols).


(a) Hub
(b) Router
(c) Bridge
52
(d) Gateway

29 Networks devices that sends the data over optimizing paths through connected hops is
(a) Hub
(b) Router
(c) Bridge
(d) Gateway

30 Which of these is not a part of URL?


(a) IP address
(b) Port Number
(c) Domain Name
(d) None of these

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

32 In URL, http://www.pacein.com/pr/main.htm, which component identifies the protocol?


(a) http
(b) www.pacein.com
(c) /pr/main.htm
(d) none

33 URLs are of two types:


(a) Absolute & Relative
(b) Static & Dynamic
(c) Absolute & Dynamic
(d) None of the above

34 In an email address, the characters following '@' character represent


(a) User name
(b) E-mail Recipient
(c) Domain name
(d) None of these

35 Which one of the following is not a network topology?


a) Star
b)Ring
c)Bus
d)Peer to Peer

36 Mbps stand for


(a) Megabyte per second
(b) Megabit per second
(c) Multibyte per second
(d) Multibit per second

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

39 MAC address is of ___________


a) 24 bits
b) 36 bits
c) 42 bits
d) 48 bits

40 DNS is the abbreviation of


a) Dynamic Name System
b) Dynamic Network System
c) Domain Name System
d) Domain Network Service

41 What is the meaning of Bandwidth in Network?


a) Transmission capacity of a communication channels
b) Connected Computers in the Network
c) Class of IP used in Network
d) None of Above

42 Which of the following protocol is used for remote terminal connection service?
a) RARP
b) UDP
c) FTP
d) TELNET

43 Which of the following is considered as the unsolicited commercial email?M


a) Virus
b)Malware
c)Spam
d)All of the above

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

46 Which of the following switch methods creates a point-to-point physical connection


between two or more computers?
a) Message switching
b) Packet switching
c) Circuit switching
d) None of these

47 MAC address is also called ______.


a) Physical address
b)Logical address
c)Source address
d)Destination address

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

49 A collection of hyperlinked documents on the internet forms the ?


a) World Wide Web (WWW)
b)E-mail system
c)Mailing list
d)Hypertext

50 TELNET used _________ protocol for data connection


a) TCP
b) UDP
c) IP
d) DHCP

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

Short Answer Type Questions 2 marks


1. Write two features of LAN
• Can spread in a room or small area.
• Established with twisted pair cable or wi-fi.

2. Write the two features of PAN.


• Established with USB cable, Bluetooth or infrared.
• Very small area upto few feet.
• Ad-hoc network. Devices can join and leave anytime.
• Less secure.

3. Write any two advantages of co-axial cable.


• High bandwidth.
• Can be used for upto 500 mtr distance.

4.What is RJ 45 connector?
• Used with twisted pair cable
• Full form is Registered Jack
• Plugin to network devices
• Primarily for LANs

5. Write features of Tree topology.


• No cycle
• Connection to all PCs
• Either direct or through other PCs
• Can say, it is a group of stars
• A fault breakdowns the network

6. Write features of Mesh topology.


• Connected in many to many concept.
• Fastest connection topology
• Very costly
• Lots of cable required
• Robust network
• High speed

7. What is peer to peer network?


• Only two devices
• Can have separate wires
• Easiest
57
• More secure than others

8. What is Ethernet Card?


• A hardware for connecting nodes
• Transmit data to network from computer
• Receive data from network to computer
• Can connect one cable or more

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.

10. Explain networking Hub.


• A Hub is a networking device that allows you to connect multiple PCs to a single network.
• It is used to connect segments of a LAN.
• A hub stores various ports, so when a packet arrives at one port, it is copied to various other ports.
• Hub works as a common connection point for devices in a network.

11. What is cloud computing?


Answer:
The sharing of compute resources (dedicated, time-shared, or dynamically shared servers) and related
infrastructure components (load balancers, firewalls, network storage, developer tools, monitors and
management tools) to facilitate the deployment and operation of web and network based applications.
Cloud computing relies on sharing of resources to achieve coherence and economies of scale, similar to a
utility (like the electricity grid) over a net-work.

12. What is MODEM?

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.

13. What is RJ45?

RJ45 stands for Registered Jack 45. It is an 8 wire connector used to connect computers on a. LAN or
Ethernet Card.

14. What is switching and its types?

Switching is the technique of transmitting information from one device/network to another.

There are three types of switching.


i. Circuit Switching: In packet switching, a physical communication link is established between source
and destination computer/device before transmitting information.
ii. Message Switching: In message switching, information is transferred from source computer to first
switching office, then a communication path is established with another switching office. From there it is
transferred to destination computer.
iii. Packet Switching: In packet switching, information is transferred from source computer to destination
computer in the form of fixed sized blocks known as packets.

15. What is a Hub?


58
Hub is a device having multiple ports used for interconnecting multiple computers together.
Hub provides shared bandwidth to all connected computers.
Hubs are of two types.
i. Active hub : It amplify the signal when it moves from one computer to another.
ii. Passive hub: It allows the signal to pass from one computer to another without any change.

16. What is a Switch

A switch is a device used to interconnect computers on a network but it provides dedicated bandwidth to
all connected computers.

17. What is a Bridge?

A bridge is a network device used to interconnect two networks that follow same protocols.

18. What is a Router?

A router is a network device used to interconnect networks having different protocols. Router forwards
data from one computer to another by shortest path.

19. What is a Gateway?

A gateway is a network device used to interconnect dissimilar networks. It establishes an intelligent


connection between local networks with completely different structures.

20. What is WiFi Card?

A WiFi card is an internal or external Local area network adapter with a builtin wireless radio and antenna.

21. Differentiate between Bus and Star topology of network.

Bus topology Star topology


Bus topology is linear Star topology is non linear
Less cable required More cable required
No switch or hub is uses to connect computer switch or hub is used to connect computer

22. In networking, what is WAN? How is it different from LAN?


Answer:
WAN (Wide Area Network):
A communication network that uses such devices as telephone lines, satellite, dishes, or radiowaves to
span a larger geographic area which cannot be covered by a LAN.

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.

25. Explain any two switching techniques used in networking.


Answer:
Message Switching: It is similar to Post-office mailing system. A temporary link is established for one
message transfer.
Packet Switching: It is a form of store and forward switching system which stores the message as small
packets at the switch nodes and then transmits it to the destination.

Case Study Based Type Questions (5 marks)

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.

No of Computers in each Block Distance between various blocks


Block A 25 Block A to Block B 60 Mtrs
Block B 50 Block B to Block C 140 Mtrs
Block C 125 Block C to Block A 130 Mtrs
Block D 10 Block D to Block C 90 Mtrs

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:

Place From Place TO Distance


Head Office Sales Office 10 km
Head Office Tech Office 70 mtr
Tech Office Sales Office 50 mtr
Head Office Kolkata Office 1291 Km
Head Office Ahmedabad Office 790 Km
61
Head Office Coimbatore Office 1952 Km
In continuation of the above, the company expert has planned to install the following number of computer
in each of their offices:
Head Office 100
Sales Office 20
Tech Office 50
Kolkata Office 50
Ahmedabad Office 50
Coimbatore Office 50

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.

Advantages of a database system:-


• It reduces data redundancy (duplication)
• It controls data inconsistency.
• It facilitates sharing of data.
• It ensures data security.
• Databases enforces standards.

Types of database models:


• 1. Relational data model
• 2. Network data model
• 3. Hierarchical data model
• 4. Object oriented data model

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

Types of keys in RDBMS (RELATIONAL DATABASE MANAGEMENT SYSTEM)


• There are four different types of keys in dbms and each key has it’s different functionality:
• Primary key – is a column or group of columns in a table that uniquely identify every row in that
table.
• Candidate key – is a set of attributes which are eligible to become primary key
• Alternate key – is a candidate key which does not become primary key.
• Foreign key – is a column that creates a relationship between two tables. The foreign key of a
relation is a primary key of another relation.

Integrity constraints in relational model:-


• Domain constraints: these are attribute level constraints. An attribute can only take values which lie
inside the domain range. E.g,; if a constrains age>0 is applied on student relation, inserting negative
value of age will result in failure.
• Key integrity: every relation in the database should have atleast one set of attributes which defines a
tuple uniquely. Those set of attributes is called key. E.g.; roll_no in student is a key. No two students
can have same roll number and no null value is allowed in the key field.
• Referential integrity: when one attribute of a relation can only take values from other attribute of
same relation or any other relation, it is called referential integrity.

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:-

i. DATA DEFINITION LANGUAGE (DDL)


DDL commands deal with defining and redefining the database objects like table, database, index,
views etc. Various commands under DDL are as follow:-
CREATE ,ALTER, DROP ,RENAME
ii. DATA MANIPULATION LANGUAGE (DML)
Data Manipulation Language deals with data manipulation and is used to store, modify, retrieve,
delete and update data in a database.
SELECT , INSERT , UPDATE ,DELETE
iii. DATA CONTROL LANGUAGE (DCL)
DCL is short name of data control language concerned with rights, permissions and other controls of
the database system.
GRANT ,REVOKE

iv. TRANSACTION CONTROL LANGUAGE (TCL)


TCL is short name of transaction control language which deals with a transaction within a
database.
Commit ,ROLLBACK ,SAVEPOINT ,SET TRANSACTION

SQL commands with syntax and example:-


1. CREATE DATABASE statement is used to create a database in mysql.
CREATE DATABASE <db_name>;
EXAMPLE:
CREATE DATABASE student;

2. USE is used to open a database.


USE <db_name>;
67
3. SHOW TABLES is used to list all the tables in a database.
SHOW TABLES;

4. CREATE TABLE statement is used to create a table in mysql database.


CREATE TABLE <table_name>
(
attribute1 data_type constraint(s),
attribute2 data_type constraint(s),
.
.
attribute_n data_type constraint(s)
);
Example:
Create table student
(
admn int PRIMARY KEY,
name varchar(20) NOT NULL,
dob date );
Note: -You must open the database before creating tables in the database.

5. The UPDATE statement is used to modify the existing records in a table.

UPDATE <table_name>
SET <column1>= <value1>, <column2> = <value2>
WHERE <condition>;
Eg:- UPDATE student
SET dob=“2001-12-27”
WHERE admn=1234;

6. The DELETE statement is used to delete existing records in a table.


DELETE FROM <table_name> WHERE <condition>;
Eg:
DELETE FROM student WHERE admn=1235;

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;

8. The DROP DATABASE statement is used to drop an existing SQL database.


DROP DATABASE <databasename>;
EG:
DROP DATABASE mydatabase;
68
9. The DROP TABLE statement is used to drop an existing table in a database.
DROP TABLE <table_name>;
Eg:
DROP TABLE student;

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.

SELECT column1, column2, ...


FROM table_name;
OR
If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;

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 &amp; 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

2 Printer 15000 3 21/5/97 4 2


3 Scanner 18000 1 29/8/98 3 1
4 Camera 21000 2 13/6/96 1 2
5 Hub 8000 1 31/10/99 2 1
6 UPS 5000 5 21/5/96 1 4

i. To select the ItemName purchased after 31/10/97.


ii. To list the ItemName, which are within the warranty period till present date.
iii. To list the itemname in ascending order of the date of purchase when quantity > 3.
iv. To display ItemName, CostPerItem and Quantity whose warranty is over.
v. To count the number of items whose cost > 10000.
vi. To display all the ItemName purchased on 21/5/96.

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.

Date and Time Functions


Curdate() Returns the current date
/current_date()
/current_date
Date() Extracts the date part of the date/ date-time expression
Month() Returns the month from the date passed
Year() Returns the year
Dayname() Returns the name of the weekday
Dayofmonth() Returns the day of month(1-31)
Dayofweek() Returns the weekday index of the argument
Dayofyear() Returns the day of the year(1-366)
Now() Returns the time at which function executes
Sysdate() Returns the current date n time

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

• Identify the correct keyword 1


INSERT INTO employee ________(1002, ‘KAUSAR’, 2000);
i. Table
ii. Values
iii. Relation
iv. Field

• 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”;

• Which two select queries will give the same output


i. SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS
NULL AND STUDENTS.ADMNO =SPORTS.ADMNO ;
ii. SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS
NOT NULL AND STUDENTS.ADMNO =SPORTS.ADMNO ;
iii. SELECT NAME, GRADE FROM STUDENTS,SPORTS WHERE ADDRESS IS
NULL OR STUDENTS.ADMNO=SPORTS.ADMNO ;
iv. SELECT ST.NAME, SP.GRADE FROM STUDENTS ST,SPORTS SP WHERE
ADDRESS IS NULL AND ST.ADMNO=SP.ADMNO ;
a. i AND ii
b. ii AND iii
c. i AND iv
d. iii AND iv

• In SQL, what is the use of IS NULL operator? 1

• Write any one aggregate function used in SQL. 1

• Which of the following is a DDL command? 1


SELECT b) ALTER c) INSERT d) UPDATE

• 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

(a)Identify the attribute best suitable to be declared as a primary key. 1


(b) Write the degree and cardinality of the table STORE. 1
(c) Insert the following data into the attributes ItemNo, ItemName and SCode
respectively in the given table STORE. ItemNo = 2010, ItemName = “Note Book”
and Scode = 25 1
(d) Abhay want to remove the table STORE from the database MyStore. Which
command will he use from the following: 1
a) DELETE FROM store;
b) DROP TABLE store;
c) DROP DATABASE mystore;
d) DELETE store FROM mystore;
(e) Now Abhay wants to display the structure of the table STORE, i.e, name of the
attributes and their respective data types that he has used in the table. Write the query
to display the same. 1

• 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

1 Jugal 34 Computer Sc 10/01/2017 12000 M


2 Sharmila 31 History 24/03/2008 20000 F
3 Sandeep 32 Mathematics 12/12/2016 30000 M
4 Sangeeta 35 History 01/07/2015 40000 F
5 Rakesh 42 Mathematics 05/09/2007 25000 M
6 Shyam 50 History 27/06/2008 30000 M
7 Shiv Om 44 Computer Sc 25/02/2017 21000 M
8 Shalakha 33 Mathematics 31/07/2018 20000 F
Table : Posting
P_ID Department Place
1 History Agra
2 Mathematics Raipur
3 Computer Science Delhi

i. SELECT Department, count(*) FROM Teacher


GROUP BY Department; 1
ii. SELECT Max(Date_of_Join),Min(Date_of_Join)
FROM Teacher;
75
ii. SELECT Teacher.name,Teacher.Department,
Posting.Place FROM Teachr, Posting WHERE
Teacher.Department = Posting.Department AND
Posting.Place=”Delhi”;

• Which function is used to display the total number of records from table in a database?
(a) sum(*)
(b) total(*)
(c) count(*)
(d) return(*)

• Categorize the following commands as DDL or DML:


INSERT, UPDATE, ALTER, DROP
• Write the outputs of the SQL queries (i) to (iv) based on the relations Teacher and Placement given
below: 4
T_ID Name Age Department Date_of_join Salary Gender
1 Arunan 34 Computer Sc 2019-01-10 12000 M
2 Saman 31 History 2017-03-24 20000 F
3 Randeep 32 Mathematics 2020-12-12 30000 M
4 Samira 35 History 2018-07-01 40000 F
5 Raman 42 Mathematics 2021-09-05 25000 M
6 Shyam 50 History 2019-06-27 30000 M
7 Shiv 44 Computer Sc 2019-02-25 21000 M
8 Shalakha 33 Mathematics 2018-07-31 20000 F

Table : Placement
P_ID Department Place
1 History Ahmedabad
2 Mathematics Jaipur
3 Computer Sc Nagpur

i. SELECT Department, avg(salary) FROM Teacher


GROUP BY Department;
ii. SELECT MAX(Date_of_Join),MIN(Date_of_Join) FROM Teacher;
iii. SELECT Name, Salary, T.Department, Place FROM Teacher T, Placement P WHERE
T.Department = P.Department AND Salary>20000;
iv. SELECT Name, Place FROM Teacher T, Placement P
WHERE Gender =’F’ AND T.Department=P.Department
v. Write the command to view all tables in a database.

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.

Steps for establishing database connectivity between Python and MySQL

1.Import mysql.connector package


import mysql.connector or
import mysql.connector as Con # Con is the alias for mysql.connector

2.Establishing a connection with Mysql DATABASE.


We can establish a connection to a mysql database using connect () function of mysql.connector
It creates a connection to the mysql server and returns a MySQL connection object.
<Connection object> = mysql.connector.connect (host=<hostname>,
user=<username>, passwd:<password>, database=<dbname>)
Example
import mysql.connector
con=mysql.connector.connect(host=”localhost”,user=”root”, passwd= “ ” )
Note: the database parameter is optional and can be skipped when we create a DB

3. Creating a cursor Object


Cursor is a useful control structure of database connectivity which allows us to execute the queries. It
stores the result of the query returned called the resultset (a logical set of records that are fetched from
the database by executing an sql query and made available in the program) as a temporary container of
returned data and allows traversal of data one row at a time.
Cursors are created by the connection.cursor() method as
<cursor object>=<connectionobject>.cursor()
Example
cursor=con.cursor()

4. Execute SQL query:


We can execute SQL query using execute() method of the cursor object by passing the query as a string
<cursor object>.execute(“SQL QUERY”)
Example
cursor.execute(“select * from data”)
Note: Whenever there is some change in data in the database through DML commands INSERT,
UPDATE, DELETE, the changes can be made / written to the DB using commit() method of the
connection object as
con.commit( )

5. Access data from resultset:

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.

6. Closing the connection


Once the data management work is over connection can be closed using close() method as
<connectionobject>.close()
Example: con.close()

Example-1 TO CREATE DATABASE


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system")
if con.is_connected()==False:
print("Error connecting to MYSQL DATABASE")
cursor=con.cursor()
cursor.execute("CREATE DATABASE STUD_DB")
con.close()

Example-2 SHOW DATABASE


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system")
cursor1=con.cursor()
cursor1.execute("SHOW DATABASES")
for x in cursor1:
print (x)
con.close()

Example-3 CREATE A TABLE


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system", database=" STUD_DB")
cursor1=con.cursor()
cursor1.execute("CREATE TABLE STUDENT (ADMNO INT, NAME VARCHAR(20),MARKS
INT);")
con.close()

Example-4 TO DESCRIBE TABLE STRUCTURE


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system", database="STUD_DB")
cursor1=con.cursor()
cursor1.execute("DESC STUDENT")
for x in cursor1:
print(x)
con.close()
78
Example-5 TO EXECUTE SELECT QUERY TO VIEW A RECORD
import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system",database="STUD_DB")
cursor1=con.cursor()
cursor1.execute("select * from student")
r=c.fetchone()
print(r)
con.close()

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)

Example-8 TO INSERT A RECORD


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system",database="STUD_DB")
cur=con.cursor()
an=int(input("enter the admission number "))
nm=input("enter name")
m=int(input("enter marks"))
cur.execute("INSERT INTO student(admno,name,marks) VALUES({},'{}',{})".format(an,nm,m))
con.commit()
print(cur.rowcount,"RECORD INSERTED")
con.close()

Example-9 TO UPDATE DATA IN A TABLE


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system",database=" STUD_DB")
cur=con.cursor()
cur.execute("UPDATE STUDENT SET MARKS=100 WHERE MARKS=40")
con.commit()
print(mycursor.rowcount,"RECORD UPDATED")

Example-10 TO DELETE A RECORD


import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",passwd="system",database=" STUD_DB")
cur=con.cursor()
cur.execute("DELETE FROM STUDENT WHERE MARKS<50")
print(cur.rowcount,"RECORD DELETED")
con.commit()

79
Questions based of DB connectivity (2/3 marks)

1. Complete the missing statements:


#Assume basic setup import, connection and cursor is created
query="select * from emp where empno=________".format(eno)
mycursor.execute(query)
results = mycursor._________
print(results)

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.

import mysql.connector as mysql


def sql_data():
con1=mysql.connect(host="localhost", user="root", passwd="root",
database="school")
mycursor=_______________ #Statement 1
query="Select * from student where marks>75; "
________________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()
4. 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:
80
CustNo – integer
CustName – string
CustCity – string
Mobile – char(10)

Note the following to establish connectivity between Python and MYSQL:


• host is localhost
• Username is root1
• Password is WELCOME
• The table exists in a MYSQL database named InventoryMaster.
• Function below reads a city from user and displays the details of customers of that city.

5. Write the following missing statements to complete the code:


Statement 1 – parameters to form the connection object
Statement 2 – to form the query which searches the details of customers of CustCity
Statement 3 – to access each record from the resultset
import mysql.connector as mysql
def SEARCH():
con=mysql.connect(_________________________________) #Statement 1
mycur=con.cursor()
City=input("Enter Customer City to search :: "))
querry = _____________________________ #Statement 2
R=mycur.execute(querry)
for ________________: #Statement 3
print(row)

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

1001 RAVI SHANKAR 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 3
1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE HOD
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE HOD

i) SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;


ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE
DESIGNATION = ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
37. Write a program to perform push operations on a Stack containing Student details as
given in the following definition of student node:
RNo integer
Name String
3
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
86
else:
return False
def stk_push(stk, item):
# Write the code to push student details using stack.
OR
Write a program to perform pop operations on a Stack containing Student details as
given in the following definition of student node:
RNo integer
Name String
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_pop(stk):
# Write the code to pop a student using stack.

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

Distance between the buildings


Building-5 Building-4
Building No of computers
Building 1 and 2 20 Meters 1 40
Building 2 and 3 50 Meters 2 45
Building 3 and 4 120 Meters 3 110
Building 3 and 5 70 Meters 4 70 5
Building 1 and 5 65 Meters 5 60
Building 2 and 5 50 Meters
Computers in each building are networked but
buildings are not networked so far. The Company has now decided to connect
building also.
(i) Suggest a cable layout for connecting the buildings
(ii) Do you think anywhere Repeaters required in the campus? Why
(iii) The company wants to link this office to their head office at Delhi
(a) Which type of transmission medium is appropriate for such a link?
(b) What type of network would this connection result into?
(iv) Where server is to be installed? Why?
(v) Suggest the wired Transmission Media used to connect all buildings
efficiently.
39. Write SQL queries for (i) to (v), which are based on the table: SCHOOL and ADMIN
TABLE: SCHOOL 5
CODE TEACHERNAME SUBJECT DOJ PERIODS EXPERIENCE

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

i) To decrease period by 10% of the teachers of English subject.


ii) To display TEACHERNAME, CODE and DESIGNATION from tables
SCHOOL and ADMIN whose gender is male.
iii) To Display number of teachers in each subject.
iv) To display details of all teachers who have joined the school after 01/01/1999 in
descending order of experience.
v) Delete all the entries of those teachers whose experience is less than 10 years in
SCHOOL table.
40. Write a function SCOUNT( ) to read the content of binary file “NAMES.DAT‟ and
display number of records (each name occupies 20 bytes in file ) where name begins
from “S‟ in it.
For. e.g. if the content of
file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK
HARI SHANKER
Function should 5
display
Total Names beginning from “S” are 2
OR
Consider the following CSV file (emp.csv):
Sl, name, salary
1,Peter,3500 2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and display
only those records where salary is 4000 or above

88
SAMPLE PAPER -2

Class : XII Time Allowed : 03:00 Hours


Subject : (083) Computer Science Maximum Marks : 70

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.”

Q02. Which of the following is not a keyword? (1)


(A) eval (B) assert
(C) nonlocal (D) pass

Q03. Given the following dictionaries (1)


dict_student = {"rno" : "53", "name" : ‘Rajveer Singh’}
dict_marks = {"Accts" : 87, "English" : 65}
Which statement will merge the contents of both dictionaries?
(A) dict_student + dict_marks (B) dict_student.add(dict_marks)
(C) dict_student.merge(dict_marks) (D) dict_student.update(dict_marks)
Q04. Consider the given expression: (1)
not ((True and False) or True)
Which of the following will be correct output if the given expression is evaluated?
(A) True (B) False
(C) NONE (D) NULL
Q05. Select the correct output of the code: (1)
>>> s='[email protected]'
>>> s=s.split('kv')
>>> op = s[0] + "@kv" + s[2]
>>> print(op)
(A) mail2@kvsangathan (B) mail2@sangathan.
(C) mail2@kvsangathan. (D) mail2kvsangathan.
Q06. Which functions is used to close a file in python? (1)
(A) close (B) cloose()
(C) Close() (D) close()
Q07. Fill in the blank: (1)
________ command is used to change table structure in SQL.
(A) update (B) change
(C) alter (D) modify
89
Q08. Which of the following commands will remove the entire database from MYSQL? (1)
(A) DELETE DATABASE (B) DROP DATABASE
(C) REMOVE DATABASE (D) ALTER DATABASE
Q09. Which of the following statement(s) would give an error after executing the following (1)
code?
D={'rno':32,'name':'Ms Archana','subject':['hindi','english','cs'],'marks':(85,75,89)} #S1
print(D) #S2
D['subject'][2]='IP' #S3
D['marks'][2]=80 #S4
print(D) #S5
(A) S1 (B) S3
(C) S4 (D) S3 and S4
Q10. Fill in the blank: (1)
_____ is a non-key attribute, whose values are derived from the primary key of some other
table.
(A) Primary Key (B) Candidate Key
(C) Foreign Key (D) Alternate Key
Q11. The correct syntax of seek() is: (1)
(A) seek(offset [, reference_point]) (B) seek(offset, file_object)
(C) seek.file_object(offset) (D) file_object.seek(offset [,
reference_point])
Q12. Fill in the blank: (1)
The SELECT statement when combined with ________ clause, returns records without
repetition.
(A) DISTINCT (B) DESCRIBE
(C) UNIQUE (D) NULL
Q13. Fill in the blank: (1)
______ is a communication methodology designed to deliver both voice and multimedia
communications over Internet protocol.
(A) SMTP (B) VoIP
(C) PPP (D) HTTP
Q14. What will the following expression be evaluated to in Python? (1)
print ( round (100.0 / 4 + (3 + 2.55) , 1 ) )
(A) 30.0 (B) 30.55
(C) 30.6 (D) 31
Q15. Which function is used to display the total number of records from a table in a database? (1)
(A) total() (B) total(*)
(C) return(*) (D) count(*)
Q16. In order to open a connection with MySQL database from within Python using (1)
mysql.connector package, __________ function is used.
(A) open (B) connect
(C) database() (D) connectdb()
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
Q17. str1= “Class” + ”Work” (1)
ASSERTION: Value of str1 will be “ClassWork”.
REASONING: Operator ‘+’ adds the operands, if both are numbers & concatenates the
string if both operands are strings.
90
Q18. Assertion: CSV (Comma Separated Values) is a file format for data storage which looks (1)
like a text file.
Reason (R): The information is organized with one record on each line and each field is
separated by semi-colon.
Section – B
Q19. Vivek has written a code to input a number and check whether it is even or odd number. (2)
His code is having errors. Rewrite the correct code and underline the corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int( input(“ Enter a number to check :))
k=checkNumber(num)
if k = 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)

Q20. Write two points of difference between Bus topology and star topology. (2)
OR
Write two points of difference between XML and HTML.

Q21. (A) Given is a Python string declaration: (2)


message='FirstPreBoardExam@2022-23'
Write the output of: print(message[ : : -3].upper())

(B) Write the output of the code given below:


d1={'rno':25, 'name':'dipanshu'}
d2={'name':'himanshu', 'age':30,'dept':'mechanical'}
d2.update(d1)
print(d2.keys())

Q22. Explain the use of ‘Foreign Key’ in a Relational Database Management System. Give (2)
example to support your answer.

Q23. (A) Write the full forms of the following: (2)


(i) HTTP (ii) FTP
(B) What is the use of TELNET?

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

Predict the output of the Python code given below:


L=[1,2,3,4,5]
Lst=[]
for i in range(len(L)):
if i%2==1:
t=(L[i],L[i]**2)
Lst.append(t)
print(Lst)

Q25. Differentiate between order by and group by clause in SQL with appropriate example. (2)

OR

Categorize the following commands as DDL or DML:


INSERT, UPDATE, ALTER, DROP
Section – C
Q26. Write the output of the queries (i) to (vi) based on the table given below: (3)
TABLE: CHIPS

BRAND_NAME FLAVOUR PRICE QUNATITY

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:

INDIA is my country. I live in India. India has many states.

The countIndia() function should display the output as:


Frequency of India is 3

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:

INDIA is my country. I live in India. India has many states.

The countVowel() function should display the output as:


Total number of vowels are : 20
Q28. (A) Consider the following tables BOOKS and ISSUED in a database named “LIBRARY”. (3)
Write SQL commands for the statements (i) to (iv).
Table: BOOKS
BID BNAME AUNAME PRICE TYPE QTY
COMP11 LET US C YASHWANT 350 COMPUTER 15
GEOG33 INDIA MAP RANJEET P 150 GEOGRAPHY 20
HIST66 HISTORY R BALA 210 HISTORY 25
COMP12 MY FIRST C VINOD DUA 330 COMPUTER 18
MY
LITR88 ARVIND AD 470 NOBEL 24
DREAMS

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.

(B) Write the command to view all tables in a database.


Q29. Write a function lenFOURword(L), where L is the list of elements (list of words) passed as (3)
argument to the function. The function returns another list named ‘indexList’ that stores
the indices of all four lettered word of L.
For example:
If L contains [“DINESH”, “RAMESH”, “AMAN”, “SURESH”, “KARN”]
The indexList will have [2, 4]
Q30. A list contains following record of a student: (3)
[StudentName, Class, Section, MobileNumber]
Write the following user defined functions to perform given operations on the stack named
‘xiia’:
(i) pushElement() - To Push an object containing name and mobile number of students
who belong to class xii and section ‘a’ to the stack
(ii) popElement() - To Pop the objects from the stack and display them. Also, display
“Stack Empty” when there are no elements in the stack.
For example:
If the lists of students details are:
[“Rajveer”, “99999999999”,”XI”, “B”]
[“Swatantra”, “8888888888”,”XII”, “A”]
[“Sajal”,”77777777777”,”VIII”,”A”]
93
[“Yash”, “1010101010”,”XII”,”A”]

The stack “xiia” should contain


[“Swatantra”, “8888888888”]
[“Yash”, “1010101010”]

The output should be:


[“Yash”, “1010101010”]
[“Swatantra”, “8888888888”]
Stack Empty

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

Distance between various buildings.


Jupiter Building to Orbit Building 50 Mtrs
Orbit Building to Oracle Building 85 Mtrs.
Oracle Building to Sunrise Building 25 Mtrs.

94
Sunrise Building to Jupiter Building 170 Mtrs.
Jupiter Building to Oracle Building 125 Mtrs.
Orbit Building to Sunrise Building 45 Mtrs.

Number of Computers in each of the buildings is follows:


Jupiter Building 30
Orbit Building 150
Oracle Building 15
Sunrise Building 35

i) Suggest a cable layout of connections between the buildings.


ii) Suggest the most suitable place (i.e. building) to house the server of this organisation
with a suitable reason
iii) Suggest the placement of the following devices with justification:
a. Internet Connecting Device/Modem
b. Switch
iv) The organisation is planning to link its sale counter situated in various parts of the same
city, which type of network out of LAN, MAN or WAN will be formed? Justify your
answer.
v) What do your mean by PAN? Explain giving example.
Q32. (A) Write the output of the code given below: (2+3)
def printMe(q,r=2):
p=r+q**3
print(p)

#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

Note the following to establish connectivity between Python and MySQL:


* Username is root
* Password is toor@123
* The table exists in a “stud” database.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose marks are
greater than 90.
Statement 3- to read the complete result of the query (records whose marks are greater than
90) into the object named data, from the table student in the database.
import mysql.connector as mysql
def sql_data():
con1=mysql.connect(host="localhost",user="root",password="toor@123",
database="stud")
mycursor=_______________ #Statement 1
print("Students with marks greater than 90 are : ")
______________________ #Statement 2
data=__________________ #Statement 3
for i in data:
print(i)
print()

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

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) If three columns are added and 5 rows are deleted from the table stock, what
will be the new degree and cardinality of the above table?
(iii) Write the statements to:
(a) Insert the following record into the table
Stockid - 201, dateofpurchase – 18-OCT-2022, name – neckphone
Make – BoAT, price - 500
(b) Decrease the price of stock by 5% whose were purchased in year 2020
OR (Option for part iii only)
(iii) Write the statements to:
(a) Delete the record of stock which were purchased before year 2015.
(b) Add a column STATUS in the table with datatype as char with 1 characters

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()

(i) Which module should be imported in the program? (Statement 1)


(ii) Write the correct statement required to open a temporary file named temp.dat.
(Statement 2)
(iii) Which statement should Aryan fill in Statement 3 to read the data from the binary file,
record.dat and in Statement 4 to write the updated data in the file, temp.dat?

98
SAMPLE PAPER -3
CLASS-XII
SUBJECT – COMPUTER SCIENCE (083)

Time Allowed: 3 hours Maximum Marks: 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 State True or False: 1
“Python is a dynamically typed language”.

2 Which among the following is not a keyword in Python. 1


a) in b) for c) pass d) none

3 What will be the output for the following Python statements? 1

D= {"Amit":90, "Reshma":96, "Suhail":92, "John":95}


print("John" in D, 90 in D, sep= "#")

a) True#False b)True#True c) False#True d) False#False

4 Consider the given expression: 1


False or not False and True

Which of the following will be correct output if the given expression is evaluated?
a) True b) False c) NONE d) NULL

5 D={1:"One", 2:"Two", 3: "Three"} 1


L=[]
for K,V in D.items():
if V[0]=="T":
L.append(K)
print(L)

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

8 Choose the correct command to delete an attribute A from a relation R. 1


a) ALTER TABLE R DELETE A
b) ALTER TABLE R DROP A
c) ALTER TABLE DROP A FROM R
d) DELETE A FROM R

9 What will be the output of the following Python code? 1


L = [10, 20]
L1=[30, 40]
L2=[50, 60]
L.append(L1)
L.extend(L2)
print(L)

(a) [60, 50, 40, 30, 20, 10]


(b) [10, 20, 30, 40, 50, 60]
(c) [10, 20, 30, 40, [50, 60]]
(d) [10, 20, [30, 40], 50, 60]

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)

12 Which of the following aggregate functions ignore NULL values? 1


a) COUNT b) MAX c) AVERAGE d) All of these

13 _______ is a device that forwards data packets along networks. 1


a) Gateway b) Modem c) Router d) Switch

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]

15 Which of the following are DML commands? 1


a) SELECT, CREATE b) ALTER, UPDATE c) INSERT, UPDATE d) DROP, DELETE

16 Mandatory arguments required to connect any database from Python are: 1


a) Username, Password, Hostname, Database name, Port
b) Username, Password, Hostname
c) Username, Password, Hostname, Database Name
d) Username, Password, Hostname, Port

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.

18 Assertion (A): Text file stores information in ASCII or Unicode characters. 1


Reason (R): In text file, there is no delimiter for a line.

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

20 What will be the output of the following Python code? 2

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

What will be the output of the following Python code?

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?

22 a) Find the output of the following Python statements: 1+1


S = "GOOD MORNING"
print(S.capitalize(), S.title(), end="!")

b) Find the output of the following Python statements


L = []
for i in range (4):
L.append(2*i + 1)
print(L[::-1])

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.

24 a) Expand the terms: TCP/IP, CDMA 2


b) Name the protocol:
i) Used to transfer voice using packet switched network
ii) Used for chatting between two groups or between two individuals

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

What will be the output of the following commands:


Select * from employee natural join department

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

i) SELECT SUM(DISCOUNT) FROM CROCKERY WHERE COST>1500;


ii) SELECT MAX(DATEOFPURCHASE) FROM CROCKERY;
iii) SELECT * FROM CROCKERY WHERE DISCOUNT>5 AND FID LIKE "T%";
iv) SELECT DATEOFPURCHASE FROM CROCKERY WHERE NAME IN ("GLASS", "PLATE");
27 Write a method LONGWORDS() in Python that reads the content of a text file Sports.txt and returns a 3
list of all the long words (words having more than 8 characters).

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.

b) Write SQL command for the following:


i) To display the structure of a table Transaction
ii) To display the list of databases

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.

For example: If the sample content of the dictionary is as follows:


marks={'Riya': 90, 'Aman':75, 'Rabi': 85, 'Mani': 95, 'Sapna': 80, 'Rohit': 88, 'Prabha': 92, 'Adi': 94,
'Om':89, 'Raima': 94}

Sample Output of the code should be:


Riya Mani Prabha Adi Raima

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.

32 a) Find and write the output of the following Python code: 5


data=["P", 20, "R", 10, "S", 30] (2+3)
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)
b) The code given below inserts the following record in the table Customer:
CustNo – integer
CustName – string
CustCity – string
Mobile – char(10)

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is welcome
• The table exists in a MYSQL database named Inventory.
• The details of customer 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 Customer
Statement 3 – to add the record permanently in the table

import mysql.connector as mysql


def INSERT():
CON=mysql.connect(host="localhost", user="root", password="welcome", database="Inventory")
mycursor=_________________ #Statement 1
CustNo=int(input("Customer Number :: "))
CustName=input("Customer Name :: ")
CustCity=input("Customer City :: "))
Mobile=input("Customer Mobile :: "))
querry="insert into Customer values({}, '{}', '{}', '{}')".format(CustNo, CustName, CustCity, Mobile)
______________________ #Statement 2
______________________ # Statement 3
print("Data Added successfully")

OR

a) Find and write the output of the following python code:

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)

Note the following to establish connectivity between Python and MYSQL:


• host is localhost
• Username is root1
• Password is WELCOME
• The table exists in a MYSQL database named InventoryMaster.
• Function below reads a city from user and displays the details of customers of that city.

Write the following missing statements to complete the code:


Statement 1 – parameters to form the connection object
Statement 2 – to form the query which searches the details of customers of CustCity
Statement 3 – to access each record from the resultset

import mysql.connector as mysql


def SEARCH():
con=mysql.connect(_________________________________) #Statement 1
mycur=con.cursor()
City=input("Enter Customer City to search :: "))
querry = _____________________________ #Statement 2
R=mycur.execute(querry)
for ________________: #Statement 3
print(row)

33 (i) Differentiate between the writerow and writerows function. 5


(ii) Write a Program in Python that defines and calls the following user defined functions: (1+4)
(a) ADD() – To accept and add data of Trains to a CSV file ‘TRAINS.CSV’. Each record consists of a
list with field elements as [TrainNo, FromCity, ToCity] to store Train Number, City from where train
is leaving and city to where train is reaching, respectively.
(b) SEARCH()- To display the details of all those trains which are starting from Bhubaneswar and
reaching to Delhi form the file ‘TRAINS.CSV’
OR
(i) State the difference between seek() and tell() functions of Python.
(ii) Write a Program in Python that defines and calls the following user defined functions:
(a) ADD() – To accept and add data of an patient to a CSV file ‘PATIENT_RECORD.CSV’. Each record
consists of a list with field elements as [PatientNo, PatientName, Age, Doctor] to store the patient
number, name of patient and the name of doctor who visited the patient, respectively.

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

Based on the data given above answer the following questions:


i) Identify the most appropriate column, which can be considered as Primary key.
ii) If two columns are added and 2 rows are deleted from the table ITEMS, what will be the new
degree and cardinality of the above table?
iii) Write the statements to:
a) To insert the first record into the table ITEMS from the sample table above.
b) To update the quantity to 50 for the first record of the table above.

OR (Option for part iii only)

iii) Write the statements to:


a) Delete the record of ITEMS whose supplier code is 21.
b) Add a column REMARKS in the table with datatype as varchar with 50 characters.

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

CLASS-XII SUBJECT: COMPUTER SCIENCE


TIME: 3 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 has 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 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])

b. Write the output of the code given below:


p=10
q=20
p*=q//3
p=q**2
q+=p
print(p,q)
22 Differentiate between DDL and DML with one Example each. 2
23 a. Give the full form of the following: 2
i. URL
ii. FTP

b. What is the use of HTTP?


24 Predict the output of the following code: 2

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=",")

25 Answer the following : 2


i) Name the package imported for connecting Python with MySQL database.
ii) What is the purpose of cursor object?

OR

What is primary key in MySQL database? Give an example.

Section-C

111
26 a. Consider the following tables Trainer and Course: 1+2

What will be the output of the following statement?


SELECT * FROM TRAINER NATURAL JOIN COURSE;

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.”

The method/function should display:

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:

i. SELECT Department, count(*) FROM Teacher GROUP BY Department;


ii. SELECT Max(Date_of_Join),Min(Date_of_Join) FROM Teacher;
iii. SELECT Teacher.name,Teacher.Department, Posting.Place
FROM Teacher, Posting
WHERE Teacher.Department = Posting.Department AND Posting.Place=”Delhi”;
iv. SELECT Gender, COUNT(Gender) FROM Teacher GROUP BY Gender;

b. Write the command to view the schema of the table Teacher.


29 Python funtion oddeve(L) to print positive numbers in a list L. 3
Example:
Input: [4, -1, 5, 9, -6, 2, -9, 8]
Output: [4, 5, 9, 2, 8]
30 Write a function AddCustomer(Customer) in Python to add a new Customer information 3
into the stack (list) CStack and display the information.

OR

Write a function DeleteCustomer() to delete a Customer information from a list of


CStack. The function delete the name of customer from the stack.
Example: If the stack contains [“Abhinav”,”Vimank”],
the output should be:
Vimank
Abhinav

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

a. What is Degree and Cardinality of the above table?


b. Which field should be made as the primary key? Justify your answer.
c. Write the query to:
i. Insert a record: (107,Bhoomi,Delhi,2001-12-15,90000)
ii. Increase the salary by 1% for the trainers whose salary is more than 80000
OR
i. Delete the record of Richa
ii. Add a new column remarks of VARCHAR type with 50 characters.

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} )

a. It will create new dictionary dict={” Year”:2023}and old dictionary


will be deleted
b. It will throw an error and dictionary cannot updated
c. It will make the content of dictionary as dict={"Exam":"AISSCE",
"Year":2023}
d. It will throw an error and dictionary and do nothing
4. What will be the value of the expression :14+13%15 1
5 Select the correct output of the code: 1
a= "Year 2022 at All the best" a = a.split('2')
a = a[0] + ". " + a[1] + ". " + a[3] print (b)
(a) Year . 0. at All the best (b) Year 0. at All the best
(c) Year . 022. at All the best (d) Year . 0. at all the best
6. Which of the following mode will refer to binary data? 1
(a)r (b) w (c) + (d) b
7. Fill in the blank: 1
______ command is used to remove a column from a table in SQL.
(a) update (b)remove (c) alter (d)drop
8. Which of the following commands will delete the rows of table? 1
(a) DELETE command (b) DROP Command
(c) REMOVE Command (d) ALTER Command
9. Which of the following statement(s) would give an error after executing the following code? 1
S="Welcome to class XII" # Statement 1print(S) #
Statement 2 S="Thank you" # Statement 3
S[0]= '@' # Statement 4
S=S+"Thank you" # Statement 5

(a) Statement 3 (b) Statement 4


(b) Statement 5 (d) Statement 4 and 5
10. Logical Operators used in SQL are? 1
(a) AND,OR,NOT (b) &&,||,!
(c) $,|,! (d) None of these
11 The correct syntax of seek() is:
(a) file_object.seek(offset [, reference_point]) (b) seek(offset [, reference_point])
(c) seek(offset, file_object) (d) seek.file_object(offset)
12. Fill in the blank: 1
All tuples in the relation are assigned NULL as the value for the new Attribute,with the ________ Command
(a) MODIFY (b) TAILOR (c)ELIMINATE (d) ALTER
13. What is the size of IPv4 address? 1
(a)32 bits (b) 64 bits (c) 64 bytes (d) 32 bytes
14. What will be the output of the following expression? 1
24//6%3 , 24//4//2 , 48//3//4
a)(1,3,4) b)(0,3,4) c)(1,12,Error) d)(1,3,#error)
15. Which of the following ignores the NULL values inSQL? 1
a) Count(*) b) count() c)total(*) d)None of these
16. Which of the following is not a legal method for fetching records from a database from within a Python 1
program?
(a) fetchone() b)fetchtwo() (c) fetchall() (d) fetchmany()
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False (d) A is false but R is True
17. Assertion (A):- If the arguments in a function call statement match the number and order of arguments as 1
defined in the function definition, such arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains default argument(s) followed by
positional argument(s).
18. Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text file. 1
Reason (R): The information is organized with one record on each line and each field is separated by
comma.

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

(a) SELECT min(Population) FROM country;


(b) SELECT max(SurfaceArea) FROM country Where Lifeexpectancy <50;
(c) SELECT avg(LifeExpectancy) FROM country Where CName Like "%G%";
(d) SELECT Count(Distinct Continent) FROM country;
OR
(a) Identify the candidate key(s) from the table Country.
(b) Consider the table CAPITAL given below:

Which field will be considered as the foreign key if the tables


COUNTRY and CAPITAL are related in a database?
SECTION-C
26 Write the outputs of the SQL queries (i) to (iii) based on the relations Teacher and Posting given below: 3
Table: Stationary
S_ID StationaryName Company Price
DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer
C_ID ConsumerName Address S_ID
1 Good Learner Delhi PL01
6 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
1. SELECT count(DISTINCT Address) FROM Consumer;
2. 2. SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Stationary
GROUP BY Company;
SELECT Consumer.ConsumerName, Stationary.StationaryName, Stationary.Price FROM Stationary,
Consumer WHERE Consumer.S_ID = Stationary.S_ID;
27. Write a function COUNT_AND( ) in Python to read the text file “STORY.TXT” and count the number of times 3
“AND” occurs in the file. (include AND/and/And in the counting)
OR
Write a function DISPLAYWORDS( ) in python to display the count of words starting with “t” or “T” in a text
file ‘STORY.TXT’.

119
28 (Write a output for SQL queries (i) to (iii), which are based on the table: SCHOOL and ADMIN given below: 3

SELECT SUM (PERIODS), SUBJECT FROM SCHOOL GROUP BY SUBJECT;


ii) SELECT TEACHERNAME, GENDER FROM SCHOOL, ADMIN WHERE
DESIGNATION = ‘COORDINATOR’ AND SCHOOL.CODE=ADMIN.CODE;
iii) SELECT COUNT (DISTINCT SUBJECT) FROM SCHOOL;
29. Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the function. The 3
function returns another list named ‘indexList’ that stores the indices of all Non-Zero Elements of L.
For example:
If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
30. Write a program to perform push operations on a Stack containing Student details as given in the following 3
definition of student node:
RNo integer
Name String
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_push(stk, item):
# Write the code to push student details using stack.
OR
Write a program to perform pop operations on a Stack containing Student details as given in the following
definition of student node:
RNo integer
Name String
Age integer
def isEmpty(stk):
if stk == [ ]:
return True
else:
return False
def stk_pop(stk):
# Write the code to pop a student using stack

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

Note the following to establish connectivity between Python and MYSQL:


• Username is root
• Password is tiger
• The table exists in a MYSQL database named school.
Write the following missing statements to complete the code:
Statement 1 – to form the cursor object
Statement 2 – to execute the query that extracts records of those students whose marks are greater than
75.
Statement 3- to read the complete result of the query (records whose
marks are greater than 75) into the object named data, from the table student in the database.
import mysql.connector as mysql def sql_data():
con1=mysql.connect(host="localhost",user="root", password="tiger",
database="school")
mycursor=_______________ #Statement 1 print("Students
with marks greater than 75 are :
")
_________________________ #Statement 2
data=__________________ #Statement 3 for i in data:
print(i)
print()

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:

(i) add() – To accept and add data of an employee to a CSV


file ‘furdata.csv’. Each record consists of a list with field elements as fid, fname and fprice to store
furniture id, furniture name and furniture price respectively.
(ii) search()- To display the records of the furniture whose price is more than 10000.
SECTION E
34 Write SQL commands for the following queries (i) to (v) based on the relation 4

Trainer and Course given below:


(i) Display the Trainer Name, City & Salary in descending order of
their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute
in the month of December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from
tables TRAINER and COURSE of all those courses whose FEES
is less than or equal to 10000.
(iv) To display number of Trainers from each city.
OR
(iv) To display the Trainer ID and Name of the trainer who are not
belongs to ‘Mumbai’ and ‘DELHI’

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”)

(a) Name the module he should import in Line 1.


(b) In which mode, Anuj should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.

124
APPENDIX – 1
Keywords in Python

False Class Finally Is return


None Continue Lambda For try
True Def From nonlocal while
And Del Global Not with
As Elif If Or yield
assert else Import Pass
break except In Raise

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)

=, %=, /=, //=, -=, +=, *=, **= (Assignment Operators)


is, is not (Identity operator)
in, not in (Membership operator)
Logical NOT
Logical AND Lowest
Logical OR

125
APPENDIX – 2

Mathematical Functions

Function Syntax Description Example

This function returns


base raised to power
exp. Error occurs if
pow math.pow(base,exp) math.pow(2,3) gives 8
(base=0 and exp<=0)
or (base<0 and exp is
not integer).

math.ceil(1.3) gives 2.0


This function returns
ceil math.ceil(num) math.ceil(-1.3) gives
next integer value.
-1.0

This function returns math.floor(1.3) gives


floor math.floor(num) previous integer 1.0
value. math.ceil(-1.3) gives -2

This function returns


the square root of a math.sqrt(16.0) gives
sqrt math.sqrt(num) number. If number is 4.0.
less than 0, error will
be shown.

exp() function returns


math.exp(2.0) gives the
exp math.exp(num) e raised to the power
value of e 2 .
exp.

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.

math.log(1.0) gives the


log() function returns natural logarithm for
the natural logarithm 1.0.
log math.log(num,[base]) for num.
Error occurs if math.log(1024, 2) will
num<=0 give logarithm of 1024
to the base 2.

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.

sin() function returns


the sine of arg. The math.sin(val)
sin math.sin(arg)
value of arg must be (val is a number)
in radians

cos() function returns


the cosine of arg. The math.cos(val)
cos math.cos(arg)
value of arg must be (val is a number)
in radians

tan() function returns


the tangent of arg. math.tan(val)
tan math.tan(arg)
The value of arg must (val is a number)
be in radians

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

math.pi gives the value of mathematical constant pi=3.141592.


math.e gives the mathematical constant e=2.718281.

127
APPENDIX – 3
Functions / Methods used with Strings

Function Description Examples

len() Returns the length of the string. >>>a="hai"


>>>len(a)
3
capitalize() Converts the first letter of the string name = "hello!"
in uppercase print(name.capitalize())
output:
Hello!
split() Breaks up a string at the specified >>>” I Love Python”.split()
separator and returns a list of [ ‘I’, ‘Love’ , ‘Python’]
substrings. >>>” I Love Python”.split(“ “)
[ ‘I’, ‘Love’ , ‘Python’]
>>>” I Love Python”.split(“o”)
[ ‘I L’, ‘ve Pyth’ , ‘n’]
replace() It replaces all the occurrences of the >>> “I love my pet”.replace(‘love’,
old string with the new string. ‘care’)
‘I care my pet’
find() It is used to search the first >>> str= ‘it goes as – ringa ringa
occurrence of the substring in the roses’
given string. >>> sub= ‘ringa’
>>>str.find(sub,15,22)
-1
>>>str.find(sub,15,25)
19
index() It also searches the first occurrence >>>’abcdabcd’.index(‘ab’)
and returns the lowest index of the 0
substring. >>>’abcdabcd’.index(‘ab’,3)
4
isalpha() It checks for alphabets in an >>>str= “abc”
inputted string and returns True in >>>str.isalpha()
string contains only letters. True
isalnum() It returns True if all the characters >>>str= “abc123”
are alphanumeric. >>>str.isalnum()
True
isdigit() It returns True if the string contains >>>str= “123”
only digits. >>>str.isdigit()
True
istitle() It returns the string with first letter >>>str=”My Favourite Food”
of every word in the string in >>str.istitle()
uppercase and rest in lowercase. True
title() It returns the title case of text. >>>str=”my favourite food”
>>str.title()
‘My Favourite Food’
count() It returns number of times substring >>>a="To be or not to be"
str occurs in the given string. >>>a.count(“be”)

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

join() Joins string after each member of >>> “*”.join(“Hello”)


the string iterator. The sequence ‘H*e*l*l*o’
must contain all strings else it will >>> “$$”.join([“Hello”, “Sister”])
raise error. ‘Hello$$Sister’
>>> “&&&”.join((“Hello”,
“Good”, “Morning”))
‘Hello&&&Good&&&Morning’
>>> “$$”.join([123, “Sister”])
TypeError

130
APPENDIX – 4
Functions / Methods used with Lists

Function Description Examples

append() It adds a single item to the end >>>col=[‘red’,’green’]


of the list. >>>col.append(‘yellow’)
>>>col
[‘red’,’green’,’yellow’]
>>>T1=[1,3,6]
>>>T1.append(7)
>>>T1
[1,3,6,7]
>>> T1.append(8,10)
Error
>>> T1.append([8,10])
>>>T1
[1,3,6,7,[8,10]]
extend() It adds one list at the end of >>>T1=[1,3,6]
another list >>>T2=[7,9]
>>> T1.extend(T2)
>>> T1
[1,3,6,7,9]
insert() It adds an element at a >>> T1=[‘a’,’e’,’u’]
specified index. >>> T1.insert(2,’i’)
>>>T1
[‘a’,’e’,’i’,’u’]
reverse() It reverses the order of the >>> T1=[‘a’,’e’,’u’]
elements in a list. >>> T1.reverse()
>>> T1
[‘u’,’e’,’a’]
>>>T2= T1.reverse()
>>>T2
No output
index() It returns the index of first >>> L=[10,20,30,40,50]
matched item from the list. >>>L.index(30)
2
len() Returns the length of the list >>> L=[10,20,[30,40],50]
i.e. number of elements in a >>>len(L)
list 4
sort() This function sorts the items >>> L=[‘u’,’b’,’i’,’d’]
of the list. >>>L.sort()
[‘b’,’d’,’i’,’u’]
>>>L.sort(reverse=True)
[‘u’,’i’,’d’,’b’]
sorted() Returns a new sorted list. >>> L=[‘u’,’b’,’i’,’d’]
>>>L1=sorted(L)
>>>L1
[‘b’,’d’,’i’,’u’]
>>>L2=sorted(L,reverse=True)
131
>>>L2
[‘u’,’i’,’d’,’b’]
clear() It removes all the elements >>> L=[‘u’,’b’,’i’,’d’]
from the list. >>>L.clear()
>>>L
[]
count() It counts how many times an >>> L=[‘u’,’b’,’i’,’d’,’b’]
element has occurred in a list >>>L.count(‘b’)
and returns it. 2
pop() It removes the element from >>>L=[‘u’,’b’,’i’,’d’]
the end of the list or from the >>>ele=L.pop()
specified index and also >>>ele
returns it. ‘d’
>>>L
[‘u’,’b’,’i’]
>>>ele=L.pop(2)
>>>ele
‘i’
del Statement It removes the specified L=[10,20,30,40,50]
element from the list or entire del L[3]
list print(L)
[10, 20, 30, 50]
del L # removes entire list
remove() It is used when we know the >>> L=[‘u’,’b’,’i’,’d’]
element to be deleted, not the >>>L.remove(‘b’)
index of the element. >>>L
[‘u’,’i’,’d’]
max() Returns the element with the >>> L=[10,20,30,40,50]
maximum value from the list. >>>max(L)
50
min() Returns the element with the >>> L=[10,20,30,40,50]
minimum value from the list. >>>min(L)
10
sum() Returns sum of elements in >>> L=[10,20,30,40,50]
the list. >>>sum(L)
150

132
APPENDIX – 5
Functions / Methods used with Tuples

Function Description Examples


del statement It is used to delete the whole tuple. ItT=(10,20,30,40,50)
doesn’t support item deletion. del T
index( ) It returns the index of first matched >>> T=(10,20,30,40,50)
item from the tuple. >>>T.index(30)
2
len( ) Returns the length of the tuple i.e. >>> T=(10,20,(30,40),50)
number of elements in a tuple >>>len(T)
4
count( ) It counts how many times an element >>> T=[‘u’,’b’,’i’,’d’,’b’]
has occurred in a tuple and returns it. >>>T.count(‘b’)
2
sorted( ) It is used to sort the elements of a >>> T=(‘u’,’b’,’i’,’d’)
tuple. It returns a list after sorting. >>>T1=sorted(T)
>>>T1
[‘b’,’d’,’i’,’u’]
>>>T2=sorted(T,reverse=True)
>>>T2
[‘u’,’i’,’d’,’b’]
sum( ) It returns sum of the elements of the >>> T=(10,20,30,40,50)
tuple. >>>sum(T)
150
max( ) Returns the element with the >>> T=(10,20,30,40,50)
maximum value from the tuple. >>>max(T)
50
min( ) Returns the element with the >>> T=(10,20,30,40,50)
minimum value from the tuple. >>>min(T)
10

133
APPENDIX – 6
Functions / Methods used with Strings

Function EExa Description Examples


items( ) It returns the content of dictionary alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
as a list of tuples having key- mytuple = alpha.items()
value pairs. print(mytuple)

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())

dict_keys(['empno', 'name', 'dept', 'salary'])


print(mydict.keys())
values( ) It returns a list of values from mydict={'empno':1,'name':'Shivam','dept':'sales',
key-value pairs in a dictionary 'salary':25000}
print(mydict.values())
dict_values([1, 'Shivam', 'sales', 25000])
get( ) It returns the value for the given alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
key ,if key is not available then it alpha.get('b')
returns None 'boy'
copy( ) It creates the copy of the alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
dictionary. d1=alpha.copy()
print(d1)
{'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
len( ) Returns the length of the D={'a': 'apple', 'b': 'boy', 'c': ‘cat’}
Dictionary i.e. number of print(len(D))
key:value pairs in a Dictionary 3
fromkeys( ) It is used to create dictionary from key=('Eno','Ename','Sal')
a collection of keys(tuple/list) d1=dict.fromkeys(key)
print(d1)
{'Eno': None, 'Ename': None, 'Sal': None}

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}

Answer Key (Functions)

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

2/3 Marks Questions

1. Ans: (ii) 30#40#50#


Max value of FROM is 3 Min Value of FROM is 1
Max value of TO is 4 and Min value of TO is 2
2. Ans.
250 # 150
250 # 100
130 # 100

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.

Answer Key - Data File Handling


1 mark questions
1. (a) tells the current position within the file.
2. (d) move the current file position to a different location at a defined offset.
3. (d) outfile = open(“c:\\temp.txt”, “a”)

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)

Answer key - Data Structure


1 mark questions
1. b. LIFO
2. b) Push
3. a) Underflow
4. d) There is a Sequential entry that is one by one
5. c) postfix Expression
6. a) 1
7. d) Stack
8. a) LIL[0], LIL[1], LIL[2]………LIL[9]
9. a) Involves searching for the specified data element in a data structure.
10. b) Binary search
11. c) i and ii
12. c) remove
13. c)[[2,3,4],[22,32,43]]
14. c) overflow
15. b) underflow
143
2/3/4 Marks Questions

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

• Give yourself enough time to study


• Keep your study space clean
• Use flow charts and diagrams
• Practice on old exam papers
• Explain your answers to others
• Organize study groups with friends
• Take regular breaks
• Drink plenty of water
• Do Meditation to keep yourself calm and composed
• Read / Write and Practice

THANK YOU.

145

You might also like