[go: up one dir, main page]

0% found this document useful (0 votes)
27 views163 pages

CS-Part_A

This document outlines the syllabus and practical guidelines for Class XII Computer Science based on the CBSE Exam Pattern for 2025-2026. It includes topics such as Python programming, functions, exception handling, data structures, computer networks, and database management, along with practical exercises and project suggestions. The document emphasizes learning outcomes, distribution of marks, and the integration of Python with SQL for database connectivity.

Uploaded by

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

CS-Part_A

This document outlines the syllabus and practical guidelines for Class XII Computer Science based on the CBSE Exam Pattern for 2025-2026. It includes topics such as Python programming, functions, exception handling, data structures, computer networks, and database management, along with practical exercises and project suggestions. The document emphasizes learning outcomes, distribution of marks, and the integration of Python with SQL for database connectivity.

Uploaded by

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

XII
COMPUTER
SHORT NOTES-2025-2026

CLASS (083
XII )
Based on the latest CBSE Exam Pattern for the Session
Sr.No. Topic Page No.

1 REVIEW OF PYTHON 1 to 15

2 FUNCTIONS 16 to 29

3 EXCEPTION HANDLING 30 to 33

4 DATA FILE HANDLING 34 to 36

5 DATA STRUCTURE 37 to 65

6 COMPUTER NETWORKS 66 to 87

7 DATABASE MANAGEMENT SYSTEM 88 to 120

8 SAMPLE PAPER - 1 121 to 139

9 SAMPLE PAPER - 2 140 to 147


Computer Science
CLASS-XII
Code No. 083
2023-24
1. Prerequisites
Computer Science- Class XI
2. Learning Outcomes
Student should be able to
a) apply the concept of function.
b) explain and use the concept of file handling.
c) use basic data structure: Stacks
d) explain basics of computer networks.
e) use Database concepts, SQL along with connectivity between Python and SQL.

3. Distribution of Marks:

Unit No. Unit Name Marks Periods

Theory Practical

I Computational Thinking and 40 70 50


Programming – 2
II Computer Networks 10 15 …

III Database Management 20 25 20

Total 70 110 70

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)
● Exception Handling: Introduction, handling exceptions using try-except-finally blocks
● 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
writer(),writerow(),writerows() and read from a csv file using 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)
● 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 connect(), cursor(),
execute(), commit(), fetchone(), fetchall(), rowcount, creating database connectivity
applications, use of %s format specifier or format() to perform queries 5. Practical

S.No Unit Name Marks


(Total=30)

1 Lab Test: 8
1. Python program (60% logic + 20%
documentation + 20% code quality)
2. SQL queries (4 queries based on one or 4
two tables)
2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using
one table / two tables.
● Minimum 4 programs based on Python -
SQL connectivity
3 Project (using concepts learnt in Classes 11 8
and 12)

4 Viva voce 3

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 userid.
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 sensitized to avoid plagiarism and violations of copyright issues
while working on projects. Teachers should take necessary measures for this.
REVIEW OF PYTHON

Characteristics of Python: Object-Oriented, Open-Source, Portable, Platform-independent,


interpreted Language developed by Guido Van Rossum in 1991.
Character Set of Python: Set of all characters recognised by python. It includes:
• Letters: A- Z and a -z
• Digits: 0-9
• Special Symbols: + , - , /, % , ** , * , [ ], { }, #, $ etc.
• White spaces: Blank space, tabs, carriage return, newline, form feed
• Other Characters: All ASCII and UNICODE characters.
Tokens: Tokens are smallest identifiable units in a python program. Different tokens are:
● Keywords: reserved words which are having special meaning. Examples: int, print,
input, for, while
● Identifiers: name given by programmer to identify variables, functions, constants, etc.
● Literals: literals are constant values.
● Operators: Operators trigger an operation. Parameters provided to the operators are
called operands. Examples: + - * % ** / //
● Delimiters: Symbols used as separators. Examples: {} , [ ] ; :

Rules for identifier names:


● Keywords cannot be used
● Can contain A-Z,a-z,0-9 and underscore(_) ● Cannot start with a number.
Example: engmark, _abc , mark1, mark2

Variables and data types: Variables are used to store data. Data types of variables:
● Numeric Types: int, float, complex ● Boolean – True or False values.
● None – a special type with an unidentified value or absence of value.
● Sequence: an ordered collection of elements. String, List and Tuples are sequences.
● Mappings – Dictionaries are mappings. Elements of dictionaries are key-value pairs.

Mutable and Immutable types:


Mutable -Values can be changed in place. E.g. List, Dictionary
Immutable: Values cannot be changed in place in memory. E.g., int, float, str, tuple.

Assigning Values to Variables:


The assignment operator (=) is used to assign values to variables. E.g. a = 100

Multiple Assignments:
• Assigning same value to multiple variables - a = b = c = 1
• Different values to different variables- a, b, c = 5,10,20
print statement: used to display output. If variables are specified i.e., without quotes then
value contained in variable is displayed.
E.g., x = "kve " Output:
print(x) kve

To combine both text and a str variable, Python uses the “+” character:
Example
x = "awesome" Output:
print("Python is " + x) Python is awesome

Expressions: An expression is combination of values, variables and operators. E.g. – x=


3*3//5 Operators: Operators trigger an operation. Some operators need one operand, some
need more than one operand to perform the operation. Types of operators:
• Arithmetic Operators: + - * / (division) // (Floor division) % (remainder) ** (power)
• Relational Operators > < >= <= = = (equality) != (inequality)
• Logical Operators: not and or

Precedence of Operators: The operator having high priority is evaluated first compared to
an operator in lower order of precedence when used in an expression.

Examples:
1. x = 7 + 3 * 2 2. >>> 3+4*2
13 11
* has higher precedence than +, so it first Multiplication gets evaluated before the
multiplies 3*2 and then adds into 7 addition operation

Comments: Comments are ignored by the Python interpreter. Comments gives some
message to the Programmer. It can be used to document the code. Comments can be:
• Single-line comments: It begins with a hash(#) symbol and the whole line is considered
as a comment until the end of line.
• Multi line comment is useful when we need to comment on many lines. In python, triple
double quote (" " ") and single quote (' ' ') are used for multi-line commenting.
Example:
# This is a single line comment
' ' 'I am a multi
line comment ' '
'

input() function:An input() function is used to receive the input from the user through the
keyboard. Example: x=input('Enter your name') age = int( input ('Enter your age'))

Selection Statements: It helps us to execute some statements based on whether the condition
is evaluated to True or False.
if statement: A decision is made based on the result of the comparison/condition. If condition
is True then statement(s) is executed otherwise not.
Syntax:
if <expression>:
statement(s) Example:
a = 3 if a > 2: Output:
print(a, "is greater") 3 is greater
print("done")
done

If-else statement:
If condition is True then if-block is executed otherwise else-block is executed.
Syntax: if test
expression:
Body of if stmts else:
Body of else
Example:
a=int(input('enter the number')) Output: enter the
if a>5: number 2
print("a is greater") a is smaller than the input given
else:
print("a is smaller than the input given")

If-elif-else statement: The elif statement allows us to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates to TRUE.
Syntax:
If <test expression>:
Body of if stmts elif
< test expression>:
Body of elif stmts else:
Body of else stmts
Example:
var = 100 if var == 200: print("1 - Got Output:
a true expression value") print(var) elif 3 - Got a true expression value
var == 150: print("2 - Got a true
100
expression value") print(var) elif var
== 100: print("3 - Got a true expression
value") print(var) else: print("4 -
Got a false expression value")
print(var)

Iteration/Repetition: Repeated execution of a set of statements is called iteration. The


for-statement and while- statements can be used

While loop: while loop keeps iterating a block of code defined inside it until the desired
condition is met.

Syntax: Example: Output:


while(expression): i=1 while i<=3: KV School
Statement(s) print("KV School") KV School
i=i+1
KV School

For loop: for loop iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects.
Syntax:
for <loopvariable> in <sequence>:
Statement(s)
Example 1: Output is:
L = [ 1, 2, 3, 4, 5] 12345
for var in L:
print( var, end=’ ‘)
Example 2: output: 0,1,2,3,4,5,6,7,8,9
for k in range(10):
print(k, end =’ , ‘)

‘break’ statement: Terminates the loop upon execution


‘continue’ Statement: Skips the current iteration / rest of the and continues on with the next
iteration in the loop.

Strings: A string is a sequence of characters. E.g. 'banana', "apple", '''orange'''

String slices: A segment or a part of a string is called a slice.


Syntax: string_object[Start: stop: steps]
● Slicing will start from index and will go up to stop(excluding stop) in step of steps.
● steps default is 1. If negative step then sequence will be decreasing order
● Default value of start is 0 if step is positive and the last item if step is negative
Example:
str = 'Hello World!' Output:
print (str[2:5] ) llo llo
print (str[2:]) World!

String concatenation: ‘+’ is string concatenation operator.


String repetition operators: ‘*’ is called repetition operator
print ( 'hello' * 2 ) Output: hellohello
print('hello' + 'world') helloworld

String functions and methods:


Sno Method name Description
1. isalnum() Returns true if string has at least 1 character and all characters are
alphanumeric and false otherwise.
2. isalpha() Returns true if string has at least 1 character and all characters are
alphabetic and false otherwise.
3. isdigit() Returns true if string contains only digits and false otherwise.
4. islower() Returns true if string has at least 1 cased character and all cased
characters are in lowercase and false otherwise.
5. isnumeric() Returns true if a string contains only numeric characters and false
otherwise.
6. isspace() Returns true if string contains only whitespace characters and false
otherwise.
7. istitle() Returns true if string is properly “titlecased” and false otherwise.
8. isupper() Returns true if string has at least one cased character and all cased
characters are in uppercase and false otherwise.
9. replace(old,new[ Replaces all occurrences of old in string with new or at most max
, max]) occurrences if max given.
10. split() Splits string according to delimiter str (space if not provided) and
returns list of substrings;
11. count() Occurrence of a string in another string
12. find() Finding the index of the first occurrence of a string in another string
13. swapcase() Converts lowercase letters in a string to uppercase and viceversa
14. startswith(str, Determines if string or a substring of string (if starting index beg
beg=0, end= and ending index end are given) starts with substring str; returns
len(string)) true if so and false otherwise.

List:Lists are ordered mutable data types enclosed in square brackets. E.g., [ 'A', 87, 23.5 ]
Python has a set of built-in methods that you can use on lists
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Basic List Operations:


Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 123 Iteration
Note: indexing and slicing are similar to that of strings. For example:
L= ['kvsch', 'school', 'KVSCH!']

Python Expression Results Description

L[2] KVSCH Offsets start at zero

L[-2] school Negative: count from the right

L[1:] ['school', 'KVSCH!'] Slicing fetches sections

Tuples: A tuple is a collection which is ordered and unchangeable. In Python tuples are
created by enclosing items within round brackets. Tuple is immutable. We can create tuple in
different ways.
X=( ) # an empty tuple
X=(1,2,3) # a tuple with three elements
X=tuple(list1)
X=1,2,3,4
Accessing elements of a tuple:
We can use index to access the elements of a tuple. From left to right, index varies from 0 to
n1, where n is total number of elements in the tuple. From right to left, the index starts with -1
and the index of the leftmost element will be –n, where n is the number of elements.
T = ( 1, 2,4,6) Output:
print(T[0]) print(T[- 1
1]) 6

Some important functions which can be used with tuple: count ():
Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 4
>>> x.count(2)
index (): Searches the tuple for a specified value and returns its position in the tuple.
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) Output: 1
>>> x.index(2)
len(): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2) output: 12
>>> y=len(x)
>>> print(y)

Dictionaries: A dictionary is a collection which is unordered, changeable and indexed. In


Python dictionaries are created with curly brackets, and they have keys and values. Values can
be of any type. Keys should be distinct and immutable data type.
Example: X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(A=1, B=2)
Functions available for handling dictionary:
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
Return a new dictionary with keys from seq and value equal to v
fromkeys(seq[, v]) (defaults to None).
Return the value of key. If key does not exit, return d (defaults
get(key[,d]) to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
Remove the item with key and return its value or d if key is not
pop(key[,d])
found. If d is not provided and key is not found, raises KeyError.
Remove and return an arbitary item (key, value). Raises KeyError
popitem() if the dictionary is empty.

setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key
with a value of d and return d (defaults to None).

update([other]) Update the dictionary with the key/value pairs from other,
overwriting existing keys.
values() Return a new view of the dictionary's values
remove() It removes or pop the specific item of dictionary
del( ) Deletes a particular item
len( ) we use len() method to get the length of dictionary

Multiple Choice Questions


1. Which of the following is not a keyword?
a) Eval b) assert c) nonlocal d) pass
2. What is the order of precedence in python?
(i) Parentheses ii) Exponential iii) Multiplication iv) Division v) Addition vi)
Subtraction
a) i,ii,iii,iv,v,vi
b) ii,i,iii,iv,v,vi
c) ii,i,iv,iii,v,vi
d) i,ii,iii,iv,vi,v
3. What will be the value of X in the following Python expression?
X = 2+9*((3*12)-8)/10
a) 30.0 b) 30.8 c) 28.4 d) 27.2

7. Which of the following can be used as valid variable identifier(s) in Python?


a) total b) 7Salute c) Que$tion d) global

8. Which of the following statement is correct for an AND operator?


a) Python only evaluates the second argument if the first one is False
b) Python only evaluates the second argument if the first one is True
c) Python only evaluates True if any one argument is True
d) Python only evaluates False if any one argument is False

10. Which point can be considered as difference between string and list?
a. Length c. Indexing and Slicing
b. Mutability d. Accessing individual elements

11.Which of the following statement is true for extend () list method?


a) adds element at last c) adds multiple elements at last
b) adds element at specified index d) adds elements at random index
12.The statement del l[1:3] do which of the following task?
a) delete elements 2 to 4 elements from the list
b) delete 2nd and 3rd element from the list
c)deletes 1st and 3rd element from the list
d)deletes 1st, 2nd and 3rd element from the list
13.If l=[11,22,33,44], then output of print(len(l)) will be
a)4 b)3 c) 8 d) 6
15.The step argument in range() function .
a. indicates the beginning of the sequence
b. indicates the end of the sequence
c. indicates the difference between every two consecutive numbers in the sequence
d. generates numbers up to a specified value

16. If D=1,2,3
What will be the data type of D?
a)List b)tuple c)set d)invalid type

17.Consider the following code


L=[‘a’,’b’,’c’,’d’]
L.pop(-1)
print(L)
What would be the output?
a)’d’ b)[‘a’,’b’,’c’,’d’] c)[‘a’,’b’,’c’] d)error

18 What is the output when the following code is executed?


>>>name=[‘Aadi’,’Beena’,’Charlie’,’David’]
>>>print(name[-1][-1])
a)’d’ b)’D’ c)’i’ d)Charlie
19.T=(“See You”)
What is the data type of T?
a)tuple b)string c)List d)set

20.Assertion(A):After adding element in a list, its memory location remains same


Reason(R):List is a mutable data type
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

21. Assertion(A):An identifier may be combination of letters and numbers.


Reason(R):No special symbols are permitted in an identifier name
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

Answers of MCQ:
1)a 2)a 3)b 4)a 5)d 6)c 7)a 8)b 9) d 10)b 11)b 12)b 13)a 14)c
15)c 16)b 17)c 18)a 19)b 20)a 21)c

Very Short Answer Type Questions


1. Give the output of the following Sum = 0 for k in
range(5): Sum = Sum+k print(Sum)

2. Give the output of the following Sum = 0


for k in range(10 , 1, -2):
Sum = Sum+k
print(Sum)

3. Give the output of the following for k in range(4): for j


in range(k):
print(‘*’, end = ‘ ‘)
print()

4. Give the output of the following for k in range(5,0, -1):


for j in range(k):
print(‘*’, end=’ ‘)
print()

5. How many times the following loop will execute? Justify


your answer
A=0

11 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
while True:
print(A)
A =A+1
6. Give the output of the following. Also find how many
times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1

7. Give the output of the following. Also find how many


times the loop will execute.
A=0
while A<10:
print(A, ‘ , ‘)
A =A+1
print(‘\n’, A)

8. Give the output of the following


T = (5) T
= T*2
print(T)

9. Give the output of the following


T = (5, )
T = T*2
print(T)
10. What kind of error message will be generated if the
following code is executed A = 5
B = ‘hi’
d = A+B
print(D)
11. Give the output of the following L = [1,2,3,4,5,6,7,8,9]
print(L[:])

12. Give the output of the following L = [1,2,3,4,5,6,7,8,9]


print(L[: -1])

13. Find the output of the following


S = ‘abcdefgh’
L = list(S)
print(L[1:4])

12 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
14. Give the output of the following L = [1,2,3,4,5,6,7,8,9]
print(L.count(2)) print(L.index(2)
15. Write python code to sort the list, L, in descending order.

16. Give the output of the following x=[4,5,66,9]


y=tuple(x) print( y)
17.Guess the output?
if 8:
print(“Hello”) if(-
5):
print(“Hai”)

18.Find output.
vowels=['a','e','i']
vowels.append('o')
vowels.append(['u'])
vowels.extend(['A','E'])
print("New List:",vowels)
19.Given the following declaration, what will be the output of the
following: Lst=(1,2,3,4,5) del Lst[2] print(Lst)
20.Identify the statement(s) from the following options which will raise TypeError exception.

a)print(‘5’*’3’)

b)print(5*3)

c)print(‘5’+3)

d)print(‘5’+’3’)

e)print(‘5’*3)
Answers for VSA Questions

1)10
2)30
3)
*
* *
* * *

4) * * * * *
* ***

13 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
* * *
* * *
5)infinite loop. Condition / test expression is always Ture.

6) 0,1,2,3,4,5,6,7,8,9

7) 0,1,2,3,4,5,6,7,8,9
10

8) 10 Note: here T is an integer

9) (5, 5), Note: here T is tuple

10)TypeError

11) [1,2,3,4,5,6,7,8,9]

12) [1,2,3,4,5,6,7,8]

13) ['b', 'c', 'd']


14) 1
1
15) L.sort(reverse= True)
16) (4, 5, 66, 9)
17)Hello
Hai
18) New List: ['a', 'e', 'i', 'o', ['u'], 'A', 'E']
19)Error
20) a)print(‘5’*’3’)

c)print(‘5’+3)

Short Answer Type Questions


1.Consider the following dictionary ‘D’. Display all the items of the dictionary as individual
tuple
D = {‘A’: 20, ‘B’: 30, ‘C’:40. ‘D’: 50}

2.Write Python code to remove an element as entered by the user form the list, L

3.Create a list k, by selecting all the odd numbers within the given range, m and n. User will
input the values of m , n at run time
4.Write Python code to create and add items to a dictionary. Ask the user to input key value
pairs. Continue as long as the user wishes.

5.Write Python code to find whether the given item is present in the given list using for loop.
14 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6.Create a list, L, with the squares of numbers from 0 to 10
7.Write a program to accept a list of numbers and to create a dictionary with two keys ODD
and EVEN whose values are all the odd numbers from the list and all the even numbers from
the list respectively.

8.Mr. Rahul wants created a dictionary to store the details of his students and to manipulate the
data. He wrote a code in Python, help him to complete the code:
studentDict = ______ # stmt 1 n = int(input("How
Many Students you Want To Input?"))
for i in range(___): # stmt 2 - to enter n number of students
data rollno = input("Enter Roll No:") name = input("Enter
Name:")
physicsMarks = int(input("Enter Physics Marks:"))
chemistryMarks = int(input("Enter Chemistry Marks:")) mathMarks
= int(input("Enter Maths Marks:")) studentDict[rollno]=__________ # stmt 3
Answers /Hints: Short answer Type Questions.
1) for k in D.items(): print(k)
2) a =int(‘input the item to be
deleted’) l.remove(a)
3) m = int(input(‘lower
limit’)) n =
int(input(‘upper limit’))
n = n+1
L = [x for x in range(m, n) if x%2!=0]
4) D = { } while True:
K = input(‘type a key’)
V = int(input(‘type the value’)
D[K] = V
C = input(‘type ‘y’ to add more’)
if C!=’y’:
break
5) flag = 0
L = eval(input(‘input a list on numbers’))
E = int(input(‘item to be searched’)
K =len(L) for p in range(K): if
E ==L(p):
flag = 1
print(‘found and index is ‘,p) if
flag==0:
print(‘not found’)

15 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6) list1=[] for x in
range(10):
list1.append(x**2)
list1
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
OR
list1=list(map(lambda x:x**2, range(10)))
7) L=eval(input("Enter a
list")) D={"ODD":
[],"EVEN":[]} for i in
L: if i%2!=0:
D["ODD"].append(i)
else:
D["EVEN"].append(i)
print(D)
8) Statement 1 :
StudentDict = dict( )
Statement 2 = for i in
range( n ):
Statement 3: studentDict[rollno]=[name, physicsMarks, chemistryMarks, mathMarks]

FUNCTIONS
Functions: A function is a named sequence of statement(s) that performs a computation. They
can be categorized as: Built-in function, Functions defined in module and User defined
functions
a) Built-in functions: Built in functions are the function(s) that are built into Python and can
be accessed by a programmer. We don’t have to import any module to use these functions.
Name of the Description Example
function

abs (x) It returns the positive value of x. >>>abs(-45) 45


>>>abs(119) 119
range(start, stop[, It is used to generate a sequence of >>> range(10)
step]) numbers. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1,2, 3, 4, 5,6, 7, 8, 9, 10]
>>>range(0, 30, 5)
[0, 5, 10,15,20, 25]
round( x [, n] ) It returns float x rounded to n digits >>>round(80.23456, 2)
from the decimal point, where x and 80.23
n are numeric expressions. If n is not >>>round(-100.000056, 3)

16 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
provided then x is rounded to 0 -100.0
decimal digits. >>> round (80.23456)
80

b) Functions defined in module: A module is a file containing Python definitions (i.e.,


functions) and statements. To use these modules in the program, a programmer needs to
import the module by using either the import statement or the from statement.

import statement: It is simplest and most common way to use modules in our code. syntax is:
import modulename1 [, modulename2, ]
Example: import math
To use/ access/invoke a function, you will specify the module name and name of the function-
separated by dot (.). This format is also known as dot notation.

Example: >>> value= math.sqrt (25) # dot notation


From Statement: It is used to get a specific function in the code instead of the complete
module file. For modules having large no. of functions, it is recommended to use from instead
of import. Its syntax is:
>>> from modulename import functionname [, functionname…..]
>>>from modulename import * ( Import everything from the file)
Example: >>> from math import sqrt
value = sqrt (25)

Some functions from math module are:


Name of Description Example
function
ceil( x ) It returns the smallest integer not less math.ceil(-45.17) -45.0
than x, where x is a numeric expression. math.ceil(100.12) 101.0
math.ceil(100.72) 101.0
floor( x ) It returns the largest integer not greater math.floor(-45.17) -46.0
than x, where x is a numeric expression. math.floor(100.12) 100.0
math.floor(100.72) 100.0
fabs( x ) It returns the absolute value of x, where math.fabs(-45.17) 45.17
x is a numeric value. math.fabs(100.12) 100.12
math.fabs(100.72)
100.72
exp( x ) It returns exponential of x: e x, where x math.exp(-45.17) 2.41500621326e-
is a numeric expression. 20 math.exp(100.12)
3.03084361407e+43
math.exp(100.72)
5.52255713025e+43

17 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
pow( x, y ) It returns the value of xy, where x and y math.pow(100, 2) 10000.0
are numeric expressions. math.pow(100, -2) 0.0001
math.pow(2, 4) 16.0
math.pow(3, 0) 1.0
sqrt (x ) It returns the square root of x for x > 0, math.sqrt(100)
where x is a numeric expression. 10.0
math.sqrt(7)-
2.6457513110645907

Some functions from random module are:


Name of the Description Example
function
random ( ) It returns a random float x, such >>random.random( )
that 0 ≤ x 0.281954791393
>>>random.random( )
0.309090465205
randint (a, b) It returns a int x between a & b >>> random.randint (1,10)
such that a ≤ x ≤ b 5
>>> random.randint (2,20) -1

uniform (a,b) It returns a floating point >>>random.uniform (5, 10)


number x, such that a <= x < b 5.52615217015

randrange([start,] It returns a random item from >>>random.randrange(100,1000,3)


stop[,step]) the given range 150

Some functions from statistics module are:


Name of the Description Example
function
mean(x) It returns arithmetic mean >>>statistics.mean([11,24,32,45,51]) 32.6

median(x) It returns median (middle >>>statistics.median([11,24,32,45,51]) 32


value) of x
mode(x) It returns mode (the most >>>statistics.mode([11,24,11,45,11])
repeated value) 11
>>>statistics.mode(("red","blue","red")) red

c) User defined functions


a. The keyword def is used to define a function.

18 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
b. After the keyword comes an identifier i.e. name of the function, followed by
parenthesized list of parameters and the colon which ends up the line.
c. Next follows the block of statement(s) that are the part of function. Syntax:
def function_name([parameter1, parameter2,....]) :
statement1
statement2

...
[return <value1, value2, ...> ]
Formal Parameters or Parameters: These are the values provided in Parenthesis when we
write a function Header.
Actual Parameters or Arguments: These are the values passed to the function when it is
called/invoked.
Example:
def area_of_circle( radius ): # radius Formal Parameter OUTPUT
parameter print(“Area of circle = “,3.1416*radius*radius) Enter radius of circle 10
r=int(input(“Enter radius of circle”)) ar=area_of_circle(r)
Area of circle = 314.16
# r - Actual Parameter or Argument
(i) Default Parameters: The parameters which are assigned with a value in function header
while defining the function are known as default parameters. Default parameters will be
written in the end of the function header, which means positional parameter cannot
appear to the right side of default parameter. If no value is provided in function call, then
the default value will be taken by the parameter.
Example:
def SICal(amount, rate, time=10): #time has default parameter
(ii) Positional Parameters/ Required Arguments: The function call statement must match
the number and positional order of arguments as defined in the function definition, then it is
called the positional parameters.
Example:
def Test(x,y,z): # x,y,z are positional parameters
Then we can call function using following statements p,q,r=3,4,6
Test(p,q,r) #3 variables are passed
Test(4,q,r) # 1 literal and 2 variables are passed

Function returning value(s)


A function can return multiple values. The return values should be a comma separated list of
values. The multiple return values are returned as a tuple. We can unpack the received value by
specifying the same number of variables on the left side of the function call.

19 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Example 1: def add10(x,y,z): Output
return x+10,y+10,z+10 (20, 30, 40)
x=10
y=20
z=30
result=add10(x,y,z)
print(result)
Example 2: def add10(x,y,z): Output:
return x+10,y+10,z+10 20 30 40
x=10
y=20
z=30
a,b,c=add10(x,y,z) #unpack

SCOPE OF VARIABLES: Scope of a variable is the portion of a program where the variable
is recognized and can be accessed therein. There are two types of scope for variables:
1.Local Scope: A variable declared in a function-body is said to have local scope. It cannot be
accessed outside the function.
2. Global Scope: A variable declared in top level segment (main) of a program is said to have
a global scope.

Example 1:
def Sum(x , y) : #x,y,z local
z=x+y return z a
=5 #a,b global
b=7s=
Sum(a , b)
print(s)
Practice Questions (1 MARK)
1 Which of the following is a valid function name?
a) Start_game() b) start game() c) start-game() d) All of the above
2 If the return statement is not used in the function then which type of value will be
returned by the function?
a)int b) str c) float d) None
3 What is the minimum and maximum value of c in the following code snippet?
import random
a=random.randint(3,5)
b = random.randint(2,3)
c=a+b
print(c)
a) 3 , 5 b) 5, 8 c) 2, 3 d) 3, 3
4 pow( ) function belongs to which library ?

20 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a) math b) string c) random d) maths
5 What data type is the object below?
L = (1, 23, ‘hello’,1)
a) list b) dictionary c) array d) tuple
6 What is returned by int(math.pow(3, 2))?
a) 6 b) 9 c) error, third argument required d) error, too many arguments

7 Which of the following is not a type conversion functions? a)


int() b) str() c) input() d) float()
8 Identify the module to which the following function load () belong to?
a) math b) random c) pickle d) sys
9 How many argument(s) a function can receive
a) Only one b) 0 or many c) Only more than one d) At least one
10 Give the output def
fun():
global a
a=10
print(a)
a=5 fun()
print(a)
a) 10 b) 5 c) 5 d) 10
10 10 5 5

11 Value returning functions should be generally called from inside of an expression a)


True b) False
12 The variable declared inside the function is called a variable
a) global b) local c) external d) none of the above
13 These are predefined functions that are always available for use. For using them we
don’t need to import any module
a) built in function b) pre-defined function
c) user defined function d) none of the above
14 The of a variable is the area of the program where it may be
referenced a) external b) global c) scope d) local

15 If you want to communicate between functions i.e. calling and called statement, then
you should use
a) values b) return c) arguments d) none of the above
16 Which of the following function header is correct?
a) def mul(a=2, b=5,c) b) def mul(a=2, b, c=5)
c) def mul(a, b=2, c=5) d) def mul(a=2, b, c=5)

21 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
17 Find the flow of execution of the following code:
1. def calculate (a, b):
2. res=a**b
3. return res
4.
5. def study(a):
6. ans=calculate(a,b)
7. return ans
8.
9. n=2
10. a=study(n)
11. print(a)
a) 1 > 5 > 9 > 10 >6 > 2 > 3 > 7 > 11 b) 5 > 9 > 10 > 6 > 2 > 3 > 7 > 11
c) 9 > 10 > 5 > 1 > 6 > 2 > 3 > 7 > 11 d) None of the above
18 A can be skipped in the function call statements a)
named parameter b) default parameter
c) keyword parameters d) all of the above

ANSWERS
1 a)Start_game()
2 d) None
3 b) 5, 8
4 a) math
5 d) tuple
6 b) 9
7 c) input()
8 c)pickle
9 b) 0 or many
a) 10
10
10
11 a) True
12 b) local
13 a) built in function
14 c) scope
15 c) arguments
16 c) def mul(a, b=2, c=5)
17 a) 1 > 5 > 9 > 10 >6 > 2 > 3 > 7 > 11
18 b) default parameter

22 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Practice Questions (2 MARKS)
1. What is the output of the following
code? def cube(x): return x * x * x x
= cube(3) print( x)
a) 9 b)3 c)27 d) 30

2 Which of the following items are present in the function


header? a) function name
b) parameter list
c) return value
d) Both A and B
3 Choose correct
answer def
fun1(num): return
num+5 print(fun1(5))
print(num)
a) Print value 10 b) Print value 5 c) Name Error d) 25
4. Predict the output of the following
code def func1(list1): for x in list1:
print(x.lower(),end="#")
func1(["New","Dehli"])
A. [New,Dehli]
B. new#dehli#
C. newdehli#
D. New#Dehli#

5. What will be the output of the following python


code? def mul (num1, num2): x = num1 * num2
x = mul(20,30)
A. 600 B. None C. No Output D. 0

6 Which of the following function header is Correct:


A. def fun(x=1,y)
B. def fun(x=1,y,z=2)
C. def fun(x=1,y=1,z=2)
D. def fun(x=1,y=1,z=2,w)

23 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 What is the output of the program given
below? x = 50 def func (x) :
x=2
func (x)
print ('x is now', x)
A) x is now 50 B) x is now 2 C) x is now 100
D) Error
9 Predict the output of the following code
fragment def update(x=10): x+=15

print("x=",x)
x=20 update()
print("x=",x)
a) x=20 b) x=25 x=25
x=25
c) x=20 d) x=25
x=25 x=20

10 Predict the output of the following code fragment


def display(x=2,y=3):
x=x+y
y+=2
print(x,y)
display( )
display(5,1)
display(9)
a) 5 5 b)12 5
63 63
12 5 55
c) 5 6 d) 5 5
12 5 7 7
63 6 6

Give the output of the following program


12
def check(a):
for i in range(len(a)):
a[i]=a[i]+5
return a
b=[1,2,3,4]
c=check(b)
print(c)
a) [6, 8, 8, 9] b) [6,7,8,9] c) [7, 7, 8, 9] d) [6,7,9,9]

24 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
14 Predict the output of the following code
snippet: def Execute(M): if M%3==0:
return M*3 else:
return M+10; def
Output(B=2): for T in range
(0,B):
print(Execute(T),"*",end="")
print() Output(4)
Output()
Output(3)

15 Find the output of the following program:


.
def ChangeIt(Text,C): T="" for K in
range(len(Text)): if Text[K]>='F'
and Text[K]<='L':
T=T+Text[K].lower(); elif
Text[K]=='E' or Text[K]=='e':
T=T+C; elif K%2==0:
T=T+Text[K].upper()
else:
T=T+T[K-1]
print(T)
OldText="pOwERALone"
ChangeIt(OldText,"%")
(a) PPW%RRLLN% (b) PPWCRRllNC
(c) PPW%RRllN% (d) PpW%RrllN%

16 What possible outputs are expected to be displayed on screen at the time of execution of
the program from the following code? Also specify the maximum value that can be
assigned to each of the variables L and U.
import random
Arr=[10,30,40,50,70,90,100]

L=random.randrange(1,3)
U=random.randrange(3,6) for
i in range(L,U+1):
print(Arr[i],"@",end="")

i) 40 @50 @ ii) 10 @50 @70 @90 @ iii)


40 @50 @70 @90 @ iv) 40 @100 @

25 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
18 What will be the output of the following
code total=0 def add(a,b): global total
total=a+b print(total)
add(6,6) print(total)
a) 12 b) 12 c) 0 d) None of these

19 Find and write the output of the following Python code:


def makenew(mystr):
newstr = " " count = 0 for
i in mystr: if count%2 ==0:
newstr = newstr+i.lower()
else: if i.islower():
newstr = newstr+i.upper()
else:
newstr = newstr+i
count +=1
newstr = newstr+mystr[:3]
print ("The new string is :", newstr)
makenew("cbseEXAMs@2022")

20 What possible output(s) are expected to be displayed on screen at the time of


execution of the following code? Also specify the maximum and minimum value that
can be assigned to variable X.

import random
L=[10,7,21]
X=random.randint(1,2) for
i in range(X):
Y=random.randint(1,X)
print(L[Y],"$",end=" ")

(i)10 $ 7 $ (ii) 21 $ 7 $ (iii) 21 $ 10 $ (iv) 7 $

26 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
21 Choose the correct option:
Statement1: Local Variables are accessible only within a function or block in which it
is declared.
Statement2: Global variables are accessible in the whole program.
a. Statement1 is correct but Statement2 is incorrect
b. Statement2 is correct but Statement1 is incorrect
c. Both Statements are Correct
d. Both Statements are incorrect
22 Consider the following code and choose correct
answer: def nameage(name, age): return
[age,name]
t=nameage('kishan',20)
print(type(t))
a) tuple b) list c) (kishan,20) d) None of all
Write the output of the following: a=(10,
23
12, 13, 12, 13, 14, 15) print(max(a)
+ min(a) + a.count(2))
a) 13 b) 25 c) 26 d) Error
24 Consider the code given below and Identify how many times the message “Hello
All” will be printed. def prog(name): for x in name: if x.isalpha():
print('Alphabet')
elif x.isdigit():
print('Digit') elif
x.isupper():
print('Capital Letter')
else: print('Hello
All')
prog('vishal123@gmail.com')
a) 0 b) 2 c) 1 d) 3

25 Find and write the output of the following Python code:


def changer(p,q=10):
p=p/q q=p
%q
print(p,"#",q)
return p
a=200

27 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
b=20
a=changer(a,b)
print(a,"$",b)
a=changer(a)
print(a,"$",b)

ANSWERS
1. Ans. C) 27
2 Ans.d
Both A and B
3 Ans c)Name Error
4. Ans. B)new#dehli#
5. Ans. C)No Output
6 Ans.c) def fun(x=1,y=1,z=2)
7 Ans. A)
A) x is now 50
9 Ans. d)
x=25
x=20
10 Ans. a)
55
63
12 5
12 Ans. b) [6, 7, 8, 9]
14 Ans.
0 *11 *12 *9 *
0 *11 *
0 *11 *12 *
15. Ans: c) PPW%RRllN%
16 Ans. Options i and iii
i)40 @50 @ iii) 40 @50
@70 @90 @
Maximum value of L and U : L=2 ,U=5
18 Ans : a)12
12
19 Ans. The new string is :
cBsEeXaMs@2022cbs
20 Ans. iv) 7 $
Maximum value of x is 2
Minimum value of x is 1
21 Ans.c) Both Statements are correct
22 Ans : b)
23 Ans : b) 25

|KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
27
24 Ans: b) 2
25 Ans.
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20

ASSERTION AND REASONING QUESTIONS(1 mark)


(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
2 Assertion(A): If the arguments in a function call match the number and order of
argumets as defined in the function definition,such arguments are called the positional
arguments.
Reasoning(R): During a function call,the argument list first contains default arguments
followed by positional arguments.
3 Assertion(A): The random module is a built-in module to generate the pseudo-random
variables.
Reason(R): The randrange() function is used to generate a random number between the
specified range in its parameter.
4 Assertion (A): Global variable is declared outside the all the functions.
Reasoning (R): It is accessible through out all the functions.
5 Assertion (A): The math.pow(2,4)gives the output: 16.0
Reason (R): The math.pow() method receives two float arguments, raise the first to the
second and return the result.
7 Assertion (A): Built-in function are predefined in the language that are used directly.
Reason (R): print() and input() are built-in functions
8 Assertion (A):- In Python, statement return [expression] exits a function.
Reasoning (R):- Return statement passes back an expression to the caller.
A return statement with no arguments is the same as return None.
9 Assertion (A): When passing a mutable sequence as an argument, function modifies
the original copy of the sequence.
Reasoning (R): Function can alter mutable sequences passes to it.

ANSWERS
2 (c) A is True but R is False
3 (b)Both A and R are true and R is not the correct explanation for A
4 (a) Both A and R are true and R is the correct explanation for A
5 (b)Both A and R are true and R is not the correct explanation for A
7 (a) Both A and R are true and R is the correct explanation for A
29 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8 (a) Both A and R are true and R is the correct explanation for A
9 (b)Both A and R are true and R is not the correct explanation for A

Additional Practice Questions (2/3 MARKS)


1 Python function oddeven(L) to print positive numbers in a list L.
Example:
Input: [4, -1, 5, 9, -6, 2, -9, 8]
Output: [4, 5, 9, 2, 8]
2 Write a function listchange(Arr,n)in Python, which accepts a list Arr of numbers and n is
an numeric value depicting length of the list. Modify the list so that all even numbers
doubled and odd number multiply by 3
Sample Input Data of the list: Arr= [ 10,20,30,40,12,11], n=6
Output: Arr = [20,40,60,80,24,33]
3 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
4 Write a function in Shift(Lst), Which accept a List ‘Lst’ as argument and swaps
the elements of every even location with its odd location and store in different list
eg. if the array initially contains
2, 4, 1, 6, 5, 7, 9, 2, 3, 10 then
it should contain
4, 2, 6, 1, 7, 5, 2, 9, 10, 3
5 Define a function ZeroEnding(SCORES) to add all those values in the list of SCORES,
which are ending with zero (0) and display the sum.
For example :
If the SCORES contain [200, 456, 300, 100, 234, 678]
The sum should be displayed as 600
6 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an
argument and displays the names (in uppercase)of the places whose names are longer
than 4 characters.
For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
The output should be: LONDON NEW YORK
10 Write a function LISTELE(L), where L is the list of elements passed as argument to the
function. The function returns another list named ‘indexList’ that stores the indices of all
Non-Zero Elements of L.
For example: If L contains [12,4,0,11,0,56]
30 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
The indexList will have - [0,1,3,5]

Exception Handling
An exception is a python object that represents an error. The exception needs to be handled by
the programmer so that the program does not terminate abruptly.
Eg:

Try and Except Block: An exception is caught in the try block and handled in except block.
An exception is said to be caught when a code designed to handle a particular exception is
executed.

While executing the program if an exception is encountered further execution of the code inside
the try block is stopped and the control is transferred to the except block.

try...except…else clause:
We can put an optional else clause along with the try...except clause. An except block will be
executed only if some exception is raised in the try block. But if there is no error then none of
the except blocks will be executed. In this case, the statements inside the else clause will be
executed.

31 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Eg:
try:
numerator=50
denom=int(input("Enter the denominator: "))
quotient=(numerator/denom)
print ("Division performed successfully")
except ZeroDivisionError:
print ("Denominator as ZERO is not allowed") except
ValueError:
print ("Only INTEGERS should be entered") else:
print ("The result of division operation is ", quotient) Finally
clause:
The try statement in Python can also have an optional finally clause. The statements inside the
finally block are always executed regardless of whether an exception has occurred in the try
block or not.

32 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Some of the commonly occurring built-in exceptions are :
S. No Name of the Builtin Explanation
Exception
1 SyntaxError It is raised when there is an error in the syntax of the Python
code.
2 ValueError It is raised when a built-in method or operation receives an
argument that has the right data type but mismatched or
inappropriate values.
3 IOError It is raised when the file specified in a program statement
cannot be opened.

4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key
while executing a program due to which the normal flow of the
program is interrupted.
5 ImportError It is raised when the requested module definition is not found.

33 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6 EOFError It is raised when the end of file condition is reached without
reading any data by input().
7 ZeroDivisionError It is raised when the denominator in a division operation is zero.
8 IndexError It is raised when the index or subscript in a sequence is out of
range.
9 NameError It is raised when a local or global variable name is not defined.
10 IndentationError It is raised due to incorrect indentation in the program code.
11 TypeError It is raised when an operator is supplied with a value of incorrect
data type.
12 OverFlowError It is raised when the result of a calculation exceeds the maximum
limit for numeric data type.
13 Key-Error Python raises a KeyError whenever a dict() object is requested
(using the format a= adict[key]) and the key is not in the
dictionary.

MCQ Question based on Exception Handlihng

1. Which block lets you test a block of code for errors?


A. try
B. except
C. finally
D. None of the above
Ans : A
Explanation: The try block lets you test a block of code for errors.

2. What will be output for the folllowing code? try:


print(x)
except:
print(""An exception occurred"")
A. x
B. An exception occurred
C. Error
D. None of the above Ans : B
Explanation: An exception occurred be the output for the followinng code because the try block
will generate an error, because x is not defined.

4. How many except statements can a try-except block have?


A. 0
B. 1
C. more than one
D. more than zero
Ans : D
Explanation: There has to be at least one except statement.

34 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5. Can one block of except statements handle multiple exception? A. yes, like
except TypeError, SyntaxError [,…]
B. yes, like except [TypeError, SyntaxError]
C. No
D. None of the above
Ans : A
Explanation: Each type of exception can be specified directly. There is no need to put it in a
list.
7. What will be the output of the following Python code?
lst = [1, 2, 3]
lst[3]
a) NameError
b) ValueError
c) IndexError
d) TypeError Answer: c
Explanation: The snippet of code shown above throws an index error. This is because the index
of the list given in the code, that is, 3 is out of range. The maximum index of this list is 2.

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


int('65.43')
a) ImportError
b) ValueError
c) TypeError
d) NameError
Answer: b
Explanation: The snippet of code shown above results in a value error. This is because there is
an invalid literal for int() with base 10: ’65.43’.

DATA FILE HANDLING


File- A file is a sequence of bytes on the disk/permanent storage.

Types of File in Python:


• Text file: A text file is simply a sequence of ASCII or Unicode characters. Text file can
be created using any text editor. Ex. Myfile.txt.
• Binary file: A binary file stores the data in the same way as stored in the memory.
The .exe files, mp3 file, image files, word documents are some of the examples of
binary files.
• CSV file: CSV (Comma Separated Values) is a simple text file format in which data is
organized with one record on each line and each field is separated by comma.

Absolute Path – It is a full path of the file from the root directory. Ex
: - C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt
f=open(“C:\\Users\\Tanmay\\Desktop\\Delete\\file_handling.txt”,r)

35 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Relative Path – Relative Path is the hierarchical path that locates a file or folder on a file
system starting from the current working directory.
f=open(“file_handling.txt”, r)

Operation On Text Files In python


Opening a file - file_object = open(“read_sample.txt”, ’r’) # Relative Path
1. Read/Write file -Read Functions – read() , readline(), readlines()
Write Functions – write() , writelines()
2. Close the File – close() Function
3. Remove the file – os.remove() #Function of OS Module
4. Rename the file–os.rename(“oldname”,”newname”) #Function of OS Module

open() function
syntax: open(filename, mode). If mode not specified, default mode is 'r' i.e., read text file

Modes Description
1. r,rb Read only
2. r+, rb+ Read and write
3. w,wb Write only
4. w+, wb+ Write and Read.
5. a,ab Append.
6. a+, ab+ Append and read.

b stands for binary file, otherwise opens in text mode r In all r modes file must exist prior to
open otherwise error is thrown. File pointer is placed at beginning.
w In all w modes, if file exists then it is removed and it always creates a blank file. File pointer
placed at beginning a In all a modes, if file exists then newly added data is added at the end. If
file does not exist then a new file is created.

Reading from a file


There are three ways to read data from a text file. read() : Returns the read bytes in form of a
string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])

readline() : Reads a line of the file and returns in form of a string. For specified n, reads at most
n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])

readlines() : Reads all the lines and return them list in which each line as a string element
File_object.readlines()

Writing onto text files:


write() function
The write() function will write the content in the file without adding any extra characters.
file_name.write(content)

36 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
writelines() function98
This function writes the content of a list to a file.
file_name.writelines(list_of_lines)

Setting Offsets in a File


If we want to access data in a random fashion, then Python gives us seek() and tell() functions
to do so
The tell() method: This function returns an integer that specifies the current position of the file
object in the file. E.g,. A=file_object.tell()

The seek() method: This method is used to position the file object at a particular position in a
file. The syntax of seek() is: file_object.seek(offset ,[ reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved.
reference_point indicates the starting position of the file object. That is, with reference to which
position, the offset has to be counted. It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file

By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the
file. For example, the statement fileObject.seek(5,0) will position the file object at 5th byte
position from the beginning of the file.

SAMPLE PROGRAMS
1. Write a program to write roll no and name to xiib.txt

2.Write read contents from story.txt and count no: of independent words “to” in the file

3.______ is the return type of readline()


Ans: string

PRACTICE QUESTIONS (TEXT FILES)


1. Write a program to read contents from the text file story.txt and count no:of vowels in it
37 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
2. Write a program to read contents from the text file myfile.txt and find average word
count
3. Write a program to read contents from the text file library.txt and count “is” as
independent word
4. Write a program to read contents from the text file diary.txt and count number of lines
with Starting letter “T” or “M”
5. Write a program to read contents from the text file mydiary.txt and count number of
lines with ending letter “r”

MULTIPLE CHOICE QUESTIONS


1 If a text file is opened in w+ mode, then what is the initial position of file
pointer/cursor?
a. Beginning of file
b. End of the file
c. Beginning of the last line of text file Undetermined
2 Which of the following statements are true?
a. When you open a file for reading, if the file does not exist, an error
occurs
b. When you open a file for writing, if the file does not exist, a new file is
created
c. When you open a file for writing, if the file exists, the existing file is
overwritten with the new file
d. All of the mentioned

3 To read the entire remaining contents of the file as a string from a file object myfile,
we use
a. myfile.read(2)
b. myfile.read()
c. myfile.readline()
d. myfile.readlines()

4 A text file is opened using the statement f = open(‘story.txt’). The file has a total of
10 lines.
Which of the following options will be true if statement 1 and statement 2 are
executed in order.
Statement 1: L1 = f.readline( )
Statement 2: L2 = f.readlines( )

a. L1 will be a list with one element and L2 will be list with 9 elements.
b. L1 will be a string and L2 will be a list with 10 elements.

c. L1 will be a string and L2 will be a list with 9 elements.


d. L1 will be a list with 10 elements and L2 will be an empty list.

38 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Which function of a file object can be used to fetch the current cursor position in
terms of number of bytes from beginning of file?
a. seek( )
b. bytes( )
c. tell( )
d. fetch( )

6. The contents of a text file named ‘quote.txt’ is as shown below


All the kings horses and all the kings men cannot fix what
isn’t broken.
What will be the output of the following code?
fin = open('fracture.txt’) data =
fin.read(10) print(data[0:3], end=
‘’) data = fin.readline(5)
print(data[0:3] , end= ‘’)
fin.seek(0) data = fin.read(4)
print(data[0:3] , end= ‘’)

a. AllngsAll
b. AllcanAll
c. Allcancan
d. Allngscan

7 What will be the most correct option for possible output of the following code, given
that the code executes without any error.
f = open(‘cricket.txt’) data
= f.read(150)
print(len(data))

a. It will always be 150


b. 151
c. More than or equal to 150
d. Less than or equal to 150

8. For the following python code, what will be the datatype of variables x, y, z given
that the code runs without any error?
f = open(‘story.txt’)
x = f.read(1) y =
f.readline() z =
f.readlines()
a. string, list, list
b. None, list, list
c. string, string, list
d. string, string, string
ANSWERS:
39 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1. a. Beginning of file
2. d. All of the mentioned
3. b. myfile.read()
4. c. L1 will be a string and L2 will be a list with 9 elements.
5. c. tell( )
6. a. AllngsAll
7. d. Less than or equal to 150
8. c. string, string, list

VERY SHORT ANSWER TYPE QUESTIONS


1. Differentiate between file modes r+ and w+ with respect to python?
Ans: r+ opens a text file for reading and writing. w+ opens a text file for reading and
writing. It overwrites the file if it exists, create a file if it doesn’t.

2. Write a statement in Python to open a text file “ABC.TXT” in reading mode.


Ans: F=open("ABC.TXT","r")

3. In ___________ files each line terminates with EOL or ‘\n’ or carriage return, or
‘\r\n’.
Ans: Text File

4. Observe the following code and answer the questions that follow.
File=open(“MyData”,”a”)
_____________ #Blank1
File.close()
a) What type (text/binary) of file is MyData ?
b) Fill the Blank1 with statement to write “ABC” in the file “Mydata”
Ans: a) Text File
c) File.write(“ABC”)

5. What are files?


Ans: A named entity, usually stored on a hard drive that contains a stream of characters are
called files.

2 SHORT ANSWER TYPE QUESTIONS 1.


Explain seek() method in python.
In Python, seek() function is used to change the position of the File Handle to a given specific
position.
Syntax: fi.seek(offset, from_where), where fi is the file pointer
Offset: This is used for defining the number of positions to move forward.

40 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
from_where: This is used for defining the point of reference. It can take
0: beginning of the file. 1: current position of the file. 2: end of the file.

2. Write a function in Python that counts the number of “the” or “this” words
present in a text file “myfile.txt”. Example: If the “myfile.txt” contents are as
follows:
This is my first class on Computer Science. File handling is the easiest topic for me
and Computer Networking is the most interesting one. The output of the function should be:
Count of the/this in file: 3 Answer:
def displayTheThis():
num=0
f=open("myfile.txt","r")
N=f.read() M=N.split()
for x in M: if x=="the"
or x== "this":
print(x)
num=num+1
f.close()
print("Count of the/this in file:",num)

3. Write a function countVowels() in Python, which should read each character of a


text file “myfile.txt”, count the number of vowels and display the count.
Example: If the “myfile.txt” contents are as follows: This is my first class on
Computer Science.
The output of the function should be: Count of vowels in file: 10
Answer: def countVowels():
fobj = open(“myfile.txt”) data =
fobj.read() count = 0
vowels=[‘a’,’e’,’I’,’o’,’u’] for ch in
data: if ch in vowels: count +=1
print(“Count of vowels in file:”, count)

4. Write a Python program to count all the line having 'a' as last character.
Answer: count =0
f=open('fracture.txt',"r")
data=f.readlines() 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()

Binary file: A binary file is a file whose content is in a binary format consisting of a series
of sequential bytes, each of which is eight bits in length.

41 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Opening a Binary file in Python
Syntax: file_object= open (file_name, access_mode)
Example: myObject=open(“myfile.txt”, “ab+”)

Pickling: The process of converting the structure (lists and dictionary etc.) into a byte stream
just before writing to the file. This is also called as object serialization. It converts a Python
object (list, dictionary, etc.) into a character stream.

Unpickling: A reverse of pickling process where information from byte stream gets converted
into object structure.

Pickle module: Python pickle module is used for serializing and de-serializing a Python object
structure. Any object in Python can be pickled so that it can be saved on disk. First, we need to
import the module.
import pickle
It provides two main methods for the purpose- dump and load.
1. pickle.dump(): This function is used to pickle the data object into byte stream and
stores it in the binary file.
2. Pickle.load() : This function reads pickled objects from a file, whereas loads()
deserializes them from a bytes-like object.

Example1: #writing a binary file


import pickle
f=open('datafile.dat','wb')
x=[1,2,3,4,5]
pickle.dump(x,f) f.close()

Example2: #reading a binary file import


pickle
f=open('datafile.dat','rb'
) L=pickle.load(f)
f.close() print(L)

Output:
[1,2,3,4,5]

Example3: Write/Append data in Binary File using


dictionary def bf_append():
f = open("sports.dat","ab")
print("Append Data") pcode =
int(input("Enter the Player code:")) pname
= input("Enter Player Name:") score =
int(input("Enter individual score:")) rank =
int(input("Enter Player Rank:"))
42 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
rec={'Pcode':pcode,'Pname':pname,'Score':score,'Rank':rank}
pickle.dump(rec,f) f.close()
bf_append()

Example4: Search for record in binary file using dictionary def


bf_search():
f = open("Sports.dat","rb") pc =
int(input("Player to code to search:"))
flag=False while True: try:
rec= pickle.load(f) if
rec['Pcode']==pc: print("Player
Name:",rec['Pname'])
print("Individual Score:",rec['Score'])
print("Rank:",rec['Rank'])
flag =
True except
Exception:
f.close() if
flag==False:
print("Record not found...")
f.close()
bf_search()

Example5: Update a record in binary file using dictionary


def bf_update():
f = open('student.dat','rb')
reclst = []
while True:
try:
rec = pickle.load(f)
reclst.append(rec)
except EOFError:
break f.close()
pc=int(input("Enter player code to update:"))
pn=input("Enter new name:")
ps=int(input("Enter Player
Score:")) pr=int(input("Enter Player
Rank:")) for i in range (len(reclst)):
if reclst[i]['Pcode']==pc:
reclst[i]['Pname'] = pn reclst[i]
['Score'] = ps reclst[i]['Rank'] =
pr f = open('sports.dat','wb') for i in
reclst: pickle.dump(i,f) f.close()
bf_update()

43 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Question and Answers (Binary Files)
1. Which functions is used to close a file in python?
(A) close (B) cloose() (C) Close() (D) close()
Ans: (D) close()

3. Which of the following python statement will bring the read pointer to 10th character from
the end of a file containing 100 characters, opened for reading in binary mode.
a) File.seek(10,0) b) File.seek(-10,2) c) File.seek(-10,1) d) File.seek(10,2)
Ans: File.seek(-10,2)

4. Which of the file opening mode will open the file for reading and writing in binary mode. a)
rb b) rb+ c) wb d) a+
Ans: b) rb+

5. 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
Assertion (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reasoning (A): A binary files are just like normal text files and can be read using a text editor
like notepad.
Ans: A is True and R is False
6. A binary file data.dat needs to be created with following data written it in the form of
Dictionaries.
Rollno Name Age
1001 TOM 17
1002 BOB 16
1003 KAY 16
Write the following functions in python accommodate the data and manipulate it.
a) A function insert() that creates the data.dat file in your system and writes the three
dictionaries.
b) b) A function read() that reads the data from the binary file and displays the dictionaries
whose age is 16.
Ans: a)import pickle
def insert():
d1 = {'Rollno':1001, 'Name':'TOM', 'Age':17}
d2 = {'Rollno':1002, 'Name':'BOB', 'Age':16}
d3 = {'Rollno':1003, 'Name':'KAY', 'Age':16}
f = open("data.dat","wb")
pickle.dump(d1,f) pickle.dump(d2,f)
pickle.dump(d3,f)
f.close()
44 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
b) def
read():
f = open("data.dat", "rb")
while True:
try:
d = pickle.load(f)
if d['Age']==16:
print(d)
except EOFError:
break
f.close()

7. Which of the following mode will refer to binary data?


(a)r (b) w (c) + (d) b
Ans: (d) b

8. Which file mode can be used to open a binary file in both append and read mode?
a) w+ b) wb+ c) ab+ d) a+
Ans: (c) ab+

9. Sheela is a Python programmer. She has written a code and created a binary file “book.dat”
that has structure [BookNo, Book_Name,Author, Price]. The following user defined function
CreateFile() is created to take input data for a record and add to book.dat and another user
defined function CountRec(Author) which accepts the Author name as parameter and count
and return number of books by the given Author.As a Python expert, help her to complete the
following code based on the requirement given above:
import ___________ #statement1
def createFile():
fobj = open("book.dat","________") #statement2
BookNo = int(input("Book number:"))
Book_Name = input("Book Name:")
Author = input("Author:")
Price = int(input("Price:"))
rec = [BookNo, Book_Name, Author, Price]
pickle.__________________
#statement3 fobj.close() def
Count_Rec(Author):
fobj = open("book.dat","rb")
num = 0
try:
while True:
rec = pickle._______________ #statement4
if Author == rec[2]:
num=num+1
except:
45 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
fobj.close()
return num
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a file named book.dat.(Statement 2)
(iii) Which statement should be filled in Statement 3 to write the data into the binary file,
book.dat?
(iv) Statement 4 to read the data from the file, book.dat?
Ans:
(i) pickle
(ii) ab
(iii) dump(rec, fobj)
(iv)load(fobj)

10. Mr. Deepak is a Python programmer. He has written a code and created a binary file
“MyFile.dat” with empid, ename and salary. The file contains 15 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_rec():
rec={}
fin=open("MyFile.dat","rb")
fout=open("_____________") #Statement 2
found=False eid=int(input("Enter employee id to
update salary : ")) while True: try:
rec=______________ #Statement 3
if rec["empid"]==eid:
found=True
rec["salary"]=int(input("Enter new salary : "))
pickle.____________ #Statement
4 else: pickle.dump(rec,fout)
except:
break
if found==True: print("The salary of employee id ",eid," has been
updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()
(i) Which module should be imported in the program? (Statement 1)
(ii) Write the correct statement required to open a temporary file named temp.dat.(Statement
2) (iii) Which statement should Deepak 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?
46 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Ans: (i) Ans: pickle
(ii) fout=open(‘temp.dat’, ‘wb’) (iii)
Statement 3: pickle.load(fin)
iv)Statement 4:
pickle.dump(rec,fout)

CSV FILE: A Comma Separated Values (CSV) file is a plain text file that contains the
comma-separated data. These files are often used for exchanging data between different
applications.

CSV File Structure sample


Name, DOB, City
Ram, 12-Jul-2001, Delhi
Mohan, 23-Jan-2005, Delhi

Python CSV Module: To work with CSV Files, programmer has to import CSV Module.
import csv

Methods of CSV Module :


● writer( ) – returns writer object used for writing rows of data to csv file
● reader( ) – returns reader object used for reading rows of data from csv file

writer( ) Object Methods : The writer object has two functions that can be used:
● w_obj . writerow( <Sequence> ) : Write a Single Line/row
● w_obj . writerows ( <Nested Sequence> ) : Write Multiple Lines/rows

Example:- ## writerow()
import csv
row=['Nikhil', 'CEO', '2', '9.0']
f=open("myfile.csv", 'w')
w_obj = csv.writer(f)
w_obj.writerow(row)
f.close()
## writerows() import csv
rows = [['Nikhil','CEO','2','9.0'],
['Sanchit','CEO','2','9.1']]
f=open("myfile.csv",'w') w_obj = csv.writer(f)
w_obj.writerows(rows)
f.close()

reader( ) Methods: This function returns a reader object which is used to iterate over lines
of a given CSV file. Each iteration over the reader object returns a list of strings
r_obj = csv.reader(csvfile_obj)

47 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Example: reading a csv file:
import csv
f=open("myfile.csv",'r')
r_obj = csv.reader(f) for
data in r_obj:
print(data)
f.close()

SAMPLE QUESTIONS (CSV Files)

1. Write a program to read entire data from file data.csv


import csv f=open("data.csv", OUTPUT:
'r') d=csv.reader(f) for row in d: ['Admno', 'Name', 'Class', 'Sec', 'Marks']
print(row) ['1231', 'Amit', 'XII', 'A', '45']
['1224', 'Anil', 'XII', 'B', '49']
['1765', 'Suman', 'XI', 'A', '42']
['2132', 'Naman', 'XII', 'C', '38']

2.Write a program to add/insert records in file “data.csv”. Structure of a record is roll number,
name and class. import csv
field = ["Roll no" , "Name" , "Class"]
f = open("data.csv" , 'w')
d=csv.writer(f)
d.writerow(field)
rn=int(input("Enter Roll number:
")) nm = input("Enter name: ") cls
= input("Enter Class: ")
rec=[rn,nm,cls]
d.writerow(rec)
f.close()

Multiple Choice Questions:


1. CSV stands for :
a. Comma Separated Values
b. Comma Separated Variables
c. Comma Stored Values
d. Comma Stored Variables

2. The separator character of CSV Files is called a

48 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a. EOL b. Delimiter c. EOF d. Default

3. The default delimiter for a CSV file is :


a. Semi colon
b. Colon
c. Comma
d. Hyphen

4. _____ module of Python provides the functionality to read and write tabular data in
CSV file.
a. pickle b. csv c. file d. ccv

5. Which function is used to open a csv file ?


a. Open()
b. csv.open()
c. writer()
d. csv.writer()

7. Which among the following is not a function of csv module?


a. reader()
b. read()
c. writer()
d. writerows()

8. In Python, default newline character is :


a. \f b. \t c. \n d. \v

9. CSV module allows to write multiple rows using function.


a. writerows( )
b. writerow( )
c. writer( )
d. None of the above

10. The opening function of a csv file is similar to the opening of:
a. Binary file
b. Text File
c. Both of them
d. None of them

11. The _______argument of open function is to specify how Python handle the
newline
characters in csv file
a. newline b. line c. mode d. char

49 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
12. Which among the following is an iterable object?
a. writer
b. file
c. reader
d. All of the above

13. To specify a different delimiter while writing into a csv file,argument is used with writer
object:
a. newline b. separator c. character d. delimiter

14. Which mode opens the file for exclusive creation, which fails in the case where file
already exists
a. a b. w c. x d. r

15. The file mode to open a CSV file for reading as well as writing is .
a. a+ b. w+ c. r+ d. All the above.

16. Identify the line number which may cause an error: import csv #Line1
line=[[1,2,3],[4,5,6]]#Line 2 with open("sample.csv","w",newline="") as csvfile: #Line3
writer=csv.writer(csvfile,delimiter="|") #Line4 for line in writer: #Line5
writer.writerow(line)

a. Line1 b. Line2 c. Line 4 d. Line

17. The CSV files are files.


a. Plain text file
b. Binary
c. Data
d. Python

18. The writer () function has how many mandatory parameters?


a. 1 b. 2 c. 3 d. 4
19. Which of the following parameter needs to be added with open function to avoid blank
row followed by each record in the CSV file?
a. quotechar
b. quoting
c. newline
d. skiprow

20. Ajaikrishna wants to separate the values by a $ sign. Suggests him a pair of function and
parameter to use it.
a. open, quotechar
b. writer, quotechar
c. open, delimiter
50 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
d. writer, delimiter

21. Tejalakshmi of Class 12 have written the below code. Observe and fill in the given
blanks so that it opens the file “data.csv” and read and print all the records.

I. What must be filled in line 1?


a. Open(“data.csv”,”r”)
b. open(“data.csv”)
c. “data.csv”
d. File

II. What must be filled in Line 2?


a. csv.reader()
b. csv.read()
c. csv.write()
d. csv.writer()

III. What must be filled in line 3?


a. data.csv b. f c. r d. None

IV. What must be filled in line 4?


a. data b. f c. “File” d. row

V. What is the default data type of data read from this file?
a. List b. String c. Tuple d. Integer
22. Sudev, a student of class 12th, is learning CSV File Module in Python. During examination,
he has been assigned an incomplete python code to create a CSV file ‘customer.csv’. Help him
in completing the code which creates the desired CSV file.

51 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Identify suitable code for the blank space in line marked as Statement-1.
a) include b) add c) Import d) import

II. Identify the missing code for the blank space in line marked as Statement-2.
a) Customer
b) reader

52 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
c) csvwriter
d) writer

III. Identify the argument name for the blank space in line marked as Statement-3?
a) Row
b) Rec
c) row
d) rec

IV. Identify the missing file name for the blank space in line marked as Statement-4?
a) customer
b) customer.csv
c) customer.txt
d) customer.dat

V .Identify the object name for the blank space in line marked as Statement-5?
a) i
b) Rec
c) row
d) rec

23. Daya of class 12 is writing a program to create a CSV file “empdata.csv” with empid, name
& mobile number. Also, to search a particular empid and display its record details. He has
written the following code. As a programmer, help him to successfully execute the given task.

53 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Choose the module he should import in Line1.
a) math b) pickle c) csv d) random

II. Choose a code to write the column heading from fields list in Line2.
a) writerows(fields) b) writerow(field)
c) writerow(fields) d) writerows(fields)

III. Choose a code to write the row from rows list in Line3.
a) writerows(row) b) writerow(row)
c) writerow(rows) d) write_row(row)

IV. Choose a code for line 4 to read the data from a csv file.
a) csv.reader(f) b) csv.read(f) d) pickle.load(f) e)f.read()

V. Choose the correct variable (list value) to check “emplid” in Line5


a) Row[0]
b) Rec[0]
c) row[0]
d) rec[0]

25. Rinsha of class 12 is writing a program to create a CSV file “user.csv” which will contain
user name and password for some entries. She has written the following code. As a
programmer, help her to successfully execute the given task.

54 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I. Name the module she should import in Line 1.
a. CSV b. csv c. math d. File

II. In which mode, Rinsha should open the file to add data into the file.
a. r b. a c. w d. w+

III. Fill in the blank in Line 3 to read the data from a csv file.
a. writer()
b. reader()
c. write()
d. read()
IV. Fill in the blank in Line 4 to close the file.
a. End() b. Close() c. close() d. end()

55 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWERS

QNO OPT QNO OPT QNO OPT QNO OPT


1 A 11 a 16 d
2 B 7 b 12 c 17 a
3 C 8 c 13 d 18 a
4 B 9 a 14 c 19 c
5 B 10 b 15 d 20 d

QNO OPT QNO OPT QNO OPT


I b I d I c
II a II c II c
21 III c 22 III b 23 III b
IV d IV b IV a
V b V d V c

QNO
OPT
I b
II b
25 III b
IV c

28. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has
created a csv file named Result.csv, to store the results of students in different sports events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'

For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions:

Accept() – to accept a record from the user and add it to the file Result.csv. The column
headings should also be added on top of the csv file.

wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.

56 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWER:
def Accept(): sid=int(input("Enter
Student ID ")) sname=input("Enter
Student Name") game=input("Enter
name of game")
res=input("Enter Result")
headings=["Student ID","Student Name","Game
Name","Result"] data=[sid, sname, game, res]
f=open("Result.csv", "a", newline="") csvwriter=csv.writer(f)
csvwriter.writerow(headings) csvwriter.writerow(data)
f.close()

def wonCount():
f=open("Result.csv","r")
csvreader=csv.reader(f,delimiter=",")
head=list(csvreader) print(head[0])
for x in head: if x[3]=="WON":
print (x)
f.close()

29. Kiran is a Python programmer working in a shop. For the employee’s tax collection, he has
created a csv file named protax.csv, to store the details of professional tax paid by the
employees. The structure of protax.csv is : [empid, ename, designation, taxpaid]
Where,
empid is employee id (integer) ename is
employee name (string) designation is
employee designation(string)
taxpaid is the amount of professional tax paid by the employee(string)
For efficiently maintaining data of the tax, Kiran wants to write the following user defined
functions:
Collection() – to accept a record from the employee and add it to the file protax.csv.
Totaltax() – to calculate and return the total tax collected from all the employees.
As a Python expert, help him complete the task.
ANSWER:
def Accept():
empid=int(input("Enter Employee ID "))
ename=input("Enter Employee Name")
designation=input("Enter the Designation")
taxpaid=input("Enter the tax amount")
data=[empid, ename, designation, taxpaid]
f=open("protax.csv", "a", newline="")
csvwriter=csv.writer(f) csvwriter.writerow(data)
f.close()

57 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
def Totaltax():
f=open("protax.csv","r")
csvreader=csv.reader(f,delimiter=",")
content=list(csvreader)
total=0 for row in content: total+=int(row[3]) f.close() return total 30. Arun of
class 12 was writing a program to read the CSV file “mydata.csv” which will contain user name
and password for some entries. As a programmer, help him to write the following user defined
functions: adddata() – to add a new entry to the file “mydata.csv.
display() – to display the content of the file “mydata.csv”.
ANSWER: def adddata():
userid=input("Enter Username:")
passwd=input("Enter th password: ")
entry=[userid,passwd]
f=open("mydata.csv", "a", newline="")
csvwriter=csv.writer(f)
csvwriter.writerow(entry)
f.close()

def display():
f=open("mydata.csv","r")
csvreader=csv.reader(f,delimiter=",")
content=list(csvreader) for rec in
content:
print(rec)
f.close()

DATA STRUCTURE

Data Structure: Data structures deal with how the data is organized and held in the memory.

Stack: Stack is a data structure in which insertion and deletion can take place only at one end
according to the Last-In-First-Out (LIFO) concept.

Applications of Stack
1. Reversing a word/line: This can be accomplished by pushing each character on to a stack as
it is read. When the line is finished, characters are popped off the stack and they will come
off in the reverse order.
2. The compilers use stacks to store the previous state of a program when a function is called
during recursion.
3. Backtracking is a form of recursion. But it involves choosing only one option out of
possibilities. Used in solving Puzzle Sudoku.
4. Undo mechanism in Text editors by keeping all the text changes in a stack.

58 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Implementation of stack – menu oriented program

1. Write the Python Code to implement stack.


L = [] def PUSH():
N = int(input("Enter the Number:"))
L.append(N)

def POP():
if L == []:
print("List is Empty - UNDERFLOW")
else:
N = L.pop()
print("The Element Deleted in Stack is :", N)

def DISPALL():
if L == []:
print("List is Empty")
else:
print("List in LIFO ORDER:")
for i in range(len(L)-1, -1, -1):
print(L[i], end='<--')

while True:
print("\n\n\tMENU:")
print("\t----")
print("1. PUSH")
print("2. POP")
print("3. DISPLAY
ALL") print("4.
EXIT") ch=
int(input("Enter the
Choice:")) if ch == 1:
PUSH() elif ch == 2:
POP() elif ch == 3:
DISPALL() elif ch
== 4: break
else:
print("Give correct choice")

QUESTIONS – BASED ON CBSE PATTERN

59 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1 A list, NList contains following record as list elements: 3
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the following user
defined functions in Python to perform the specified operations on the stack named
travel. (i) Push_element(NList): It takes the nested list as an argument and pushes a
list object containing name of the city and country, which are not in India and distance
is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the
function should display “Stack Empty” when there are no elements in the stack. For
example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty

A
n
s

2. A stack S contains Name of countries.Write a function POP(A), to remove Name from 3


stack. Function should handle underflow condition and should return removed element.

A def POP(A):
n
if len(A) = = 0:
s
print(“UNDERFLOW”)
else:
60 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
val=A.pop( )
return val
3. Write a function PUSH(STACK,Name) to add new name to the STACK data structure . 3
Also display all the names having at least 4 characters from the stack.

A def PUSH(STACK,Name):
n
STACK.append(Name)
s
#code for displaying
if len(STACK)==0:

print(“Empty stack”)
else:
top=len(STACK)-1
for i in range(top,-1,-1):
if len(STACK[i])>=4:
print(STACK[i] )
5. UNSOLVED EXERCISE: 3
Coach Abhishek stores the races and participants in a dictionary. Write a program, with
separate user defined functions to perform the following operations:
a. Push() Push the names of the participants of the dictionary onto a stack, where the
distance is more than 100.
b. PoP() Pop and display the content of the stack.

For example:
If the sample content of the dictionary is as follows: Races ={100:'Varnika', 200 :'Jugal',
400:'Kushal', 800:'Minisha'}}
The output from the program should be: Minisha Kushal Jugal

SAMPLE QUESTIONS:
MCQ/Very Short Answer Type Questions(1-mark)
1. Which list method can be used to perform Push operation in a stack implemented by list?
a) append() b)extend() c) push() d) insert()

2. Which list method can be used to perform Pop operation in a stack implemented by list?
a) pop() b) pop(1) c) remove() d) pop(0)

6. What do you mean by Data Structure?


7. LIFO data structure is?

61 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8. Can we have nested list?
9. Name one linear data structure.
10. Name one non-linear data structure.
11. Name the operation for insertion in a stack.
12. Name the operation for deletion from a stack.
13. Name the function to find length of a list.
14. Indexing in list starts from?

Short Answer Type Questions(2-marks)

1. How is Data Structure different from Data Type?


2. Define Stack and Queue
3. Name some operations commonly performed on data structures?
4. What is a list?
5. What is traversing? Write python code to traverse a list.
6. Name the methods used for inserting and deleting elements from a list.
7. Write some applications of stack.
Application based Short Answer Type Questions(2-marks)

8. Predict the output with respect to the list L=[40,20,30,10,50]


(a) print(L)
(b) print(len(L))
(c) L.pop() ; print(L)
(d) L.append(70); print(L)
(e) L.sort(); print(L)

9. Find the output:


(a) secondlist=[1,2,3,[4,5,[6,7,8],9],10,11] print(len(secondlist) )
L=[1, 2, 3, [4, 5, [ 6, 7, 8 ], 9 ] ,10, 11]
(b) L[1]
(c) L[3]
(d) L[3][1]
(e) L[3][2][0]
(f) L[3][2]
(g) L[3][2][1]
(h) L[3][3]

10. Predict the output:


(a) b=[[9,6],[4,5],[7,7]] X=b[:2]
X.append(10)
print(X)

(b) b=[[9,6],[4,5],[7,7]] X=b[:2]

62 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
X[1].append(10)
print(X)
11. Consider STACK=[‘a’,’b’,’c’,’d’]. Write the STACK content after each operations:
(a) STACK.pop( )
(b) STACK.append(‘e’)
(c) STACK.append(‘f’)
(d) STACK.pop( )

12. Write a program to implement a stack for the students(studentno, name). Just implement
Push.

13. Write a program to implement a stack for the students(studentno, name). Just implement
Pop and display.

14. If L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"] ,
then find the output:
(a) L[0][0]
(b) L[3][0][2]
(c) L[3:4][0]
(d) L[3:4][0][1]
(e) L[3:4][0][1][3]
(f) L[0:9][0]
(g) L[0:9][0][3]
(h) L[3:4][1]

15. What is the difference between pop() and pop(0)?

Long Answer Type Questions (3-marks)


1. Write a function in Python Push (nums), where nums is a list of numbers. From this list
push all odd numbers into a stack implemented by using a list. Display the stack if it has at least
one element, otherwise display appropriate error message.

2. Write a function in Python PUSH(pbook),where pbook is a dictionary of phone book(name


and mobile numbers), from this dictionary push all phone numbers of persons whose name
contains the letter ‘a’ in their names to a stack implemented by using list and also the display
the stack if it has at least one element, otherwise display “stack empty” message
>>>mydict={"Shyam":9999123123,"Veena:8888345345, "Minu":9999123123, "Tejas::
7777678678}
>>> push(mydict)
Stack elements after push operation :
[9999123123, 7777678678]

63 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3. Write a function in Python nameadd(L), where L is a list of names. The function should
add all the names whose length is longer than 5 characters on to the stack. It should also display
the stack if it has at least one element, otherwise display “stack empty” message.
For example: nameadd( [‘Shyamlal’, ‘Gopi’, ‘Anand’, ‘Mritunjay’] )
The above function call should give output as: Stack is: [‘Shyamlal’, ‘Mritunjay’]

4. Write a function in Python PUSH(mydict),where mydict is a dictionary of phone


book(name and mobile numbers), from this dictionary push only phone numbers having 10
digits into a stack implemented by using list . Display the stack if it has at least one element,
otherwise display
“stack empty” message.
>>>mydict={1234567890:"Shyam",94567892:"Ram",8657456789012:"Karun",
9674123789:"Tharun"}
>>> push(mydict) after push operation output : Stack is:
[9674123789, 1234567890]

ANSWER KEY

I. MCQ/ Very Short Answer Type Questions(1-mark)


2. (a) append()
3. (a) pop()

6. Data Structure means organization of data. A data structure has well defined operations
or behaviour.
7. STACK
8. Yes
9. Lists
10. Graphs
11 PUSH
12 pop
13. len()
14. 0

Short Answer Type Questions(2-marks)


1. Data Structure provides information regarding organization of data whereas Data
Type provides information regarding the domain of values and operations that
can be performed on data.
2. Stack – A stack is a linear list also known as LIFO list with the special property
that items can be added or removed from only one end called the top.
Queue – A queue is a linear list also known as FIFO list with the special property that items can
be added at one end and removed from the other.
3. Traversal, Insertion, Deletion, Searching, Sorting, Merging etc.
4. A list is a mutable sequence of data elements indexed by their position. A list is
represented using [ ] . e.g L=[10,20,30]
64 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5. Traversing means accessing or visiting or processing each element of any data
structure. L=[10,20,30,40,50] for x in L: print(x)
6. Various methods for inserting elements in a list are - insert(), append(), extend()
and methods used for deleting items from a list are – pop() , remove(), clear()
7. Reversing a string, compilers use stack to store previous state of program, undo
mechanism in text editors and backtracking.

Application based Short Answer Type Questions(2-marks)


8. (a) Ans: [40, 20, 30, 10, 50]
(b) Ans: 5
(c) Ans:50
[40, 20, 30, 10]
(d) Ans: [40, 20, 30, 10, 70]
(e) Ans: [10, 20, 30, 40, 70]
9. (a) Ans:6
(b) Ans: 2
(c) Ans:[4, 5, [6, 7, 8], 9]
(d) Ans:5
(e) Ans:6
(f) Ans: [6, 7, 8]
(g) Ans:7
(h) Ans:9
10. (a) Ans: [[9, 6], [4, 5], 10]
(b) Ans: [[9, 6], [4, 5, 10]]

11. Ans: ['a', 'b', 'c']


Ans: ['a', 'b', 'c',’e’]
Ans: ['a', 'b', 'c',’e’,’f’]
Ans: ['a', 'b', 'c',’e’]
12. stk=[] def PUSH():
sno=int(input('Enter student number:'))
sname=input('Enter student name:')
s=[sno,sname]
stk.append(s)

13. stk=[] def stkpop(): if stk==[]: print('Stack empty') else:


print('Element popped:', stk.pop())

def display(): if stk==[]:


print('Stack empty') else:
print('Stack is:', stk[: :-1])

14. (a) Ans: ‘P’


(b) Ans: ‘d’

65 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
(c) Ans: ['modern', 'programming']
(d) Ans: 'programming'
(e) Ans: 'g'
(f) Ans: 'Python'
(g) Ans: 'h'
(h) Ans: IndexError: list index out of range
15. Ans: pop() will delete the last element of a list whereas pop(0) will delete
element at index zero of a list

Long Answer Type Questions (3-marks)

1.
stk=[] def
Push(nums):
for i in nums:
if i%2==1:
stk.append(i)

if stk==[]:
print('stack is empty')
else: print('stack is:',
stk[: :-1])

2
.
stk=[] def
push(pbook):
for k in d:
if 'a' in k:
stk.append(d[k])

if stk==[]:
print('stack empty')
else: print('stack
is:', stk)

3. stk=[] def
nameadd(L):
for i in L: if
len(i)>5:
stk.append(i)

if stk==[]:

66 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
print('stack empty')
else: print('stack
is:', stk)

4. stk=[] def
push(mydict):
phonebook=list(mydict.keys())
for mob in phonebook: if
len(str(mob)) == 10:
stk.append(mob) if stk==[]:
print('stack empty')
else:
print('stack is:', stk)
COMPUTER NETWORKS

A group of two or more similar things or people interconnected with each other is called
network. Examples are social network and mobile network
Computer Network: A Computer network is an interconnection among two or more
computers or computing devices. Th advantages of computer networks are:
● Resource Sharing
● Collaborative Interaction
● Cost Saving
● Increased storage
● Time Saving
Evolution of Network:
(I)ARPANET (Advanced Research Project Agency Network)
● It came into existence in 1960s
● A project for interconnecting, US department of defense with academic and research
organization across different places for scientific collaboration.
(II)NSFNET (National Science Foundation Networks)
● It came into existence in 1986
● It was the first large-scale implementation of Internet technologies in a complex
environment of many independently operated networks
(III) INTRANET
● It is a local or restricted communication system ● It is managed by a
person or organization.
● Intranet users can avail services from internet but Internet user
cannot access intranet directly
(III) INTERNET
● It came into existence in 1960s
● It is known as Network of Networks
● A global computer network providing variety of information and communication
facilities consisting of interconnected networks using standardized communication
protocols.
67 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DATA COMMUNICATION TERMINOLOGIES
DATA: Data means information in digital form such as text, audio, video which is stored
processed and exchanged between digital devices like computer, mobile phones or laptop.
Computers process the raw data into meaningful information. Information is processed data.
COMMUNICATION: The exchange of information between two or more networked or
interconnected devices is called communication
COMPONENTS OF DATA COMMUNICATION

a) SENDER: Sender is a device which is capable of sending data over a communication


network. In data communication Sender is also called Source.

b) RECEIVER: Receiver is a device which is capable of receiving data over a


communication network. In data communication Receiver is also called Destination.

c) MESSAGE: message is the information being exchanged between a sender and a receiver
over a communication network.

d) COMMUNICATION MEDIUM: Communication medium is the path or channel through


which the information is moved from the sender to the receiver. A communication medium can
be either wired/guided or wireless/unguided.

e) PROTOCOLS: The set of standard rules which are followed in data communication are
known as Data Communication Protocols. All the communicating devices like sender receiver
and other connected devices in the network should follow these protocols .

Why Protocols are needed?


The communicating devices may be in different geographical areas. The speed of these devices
may be different. Also, the data transfer rates of different networks may be different. These
complexities make it necessary to have a common set of rules to ensure the secure
communication of data. Some commonly used Protocols in data communication are:
● Transmission Control Protocol (TCP)
● Internet Protocol (IP)
● File Transfer Protocol (FTP)
● Simple Mail Transport Protocol (SMTP)
● Hyper Text Transfer Protocol (HTTP)

MEASURING CAPACITY OF COMMUNICATION MEDIA


Capacity of a communication channel means the maximum quantity of signals that a
communication channel can carry. The capacity of a communication medium is measured by its
bandwidth and data transfer rate.

BANDWIDTH: Bandwidth is the difference between the highest and lowest frequencies a
transmission media can carry. The unit of bandwidth is Hertz.
68 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DATA TRANSFER RATES: Data transfer rate is the number of bits transmitted through a
channel per unit of time. Data transfer rate is measured in bits per second (bps). It is also
measured in Kilobits per second (Kbps), Megabits per second (Mbps) or Gigabits per second
(Gbps).

IP ADDRESS: IP address or Internet Protocol address is a unique numeric address assigned to


every device connected to a network. It uniquely identifies every node connected to a local
network or internet. Example IP address: 24.171.248.170

69 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
SWITCHING TECHNIQUES
In large networks, there may be more than one paths for transmitting data from sender to
receiver. The process of selecting a path of data out of the available paths is called switching.
There are two popular switching techniques – circuit switching and packet switching.

1. Circuit Switching : In circuit switching, whenever a source end node wants to


send a message to the destination end node a physical link is first established between the
source and the destination. Then only the data transmission takes place. Example: telephone
network
2. Packet Switching : In the packet switching technique, the whole message is split
into small packets. Now, these packets are transmitted one by one from sender to the receiver
through the intermediary switches in the network. The packets will take shortest path as
possible.

Computer Network Types


A computer network can be categorized by their size, complexity and geographical spread. A
computer network is mainly of four types:

● LAN (Local Area Network)


● PAN (Personal Area Network)
● MAN (Metropolitan Area Network)
● WAN (Wide Area Network)

PAN (Personal Area Network): Personal Area Network is a network of information


technology devices (laptop, mobile phones, media player and play stations) arranged within the
range of an individual person, typically within a range of 10 meters / covers an area of 30 feet.

LAN (Local Area Network): Local Area Network is a group of computers connected to
each other in a small area such as a building, office through a communication medium such as
twisted pair, coaxial cable, etc to share resources.

MAN (Metropolitan Area Network): A metropolitan area network is a network that


covers a larger geographic area that is spread over an area as big as a city by interconnecting
different LAN to form a larger network through a telephone exchange line.

WAN (Wide Area Network): A Wide Area Network is a network that extends over a large
geographical area such as states or countries through a telephone line, fiber optic cable or
satellite links. The internet is one of the biggest WAN in the world.

70 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Networking Topologies
Bus
It uses a single cable, called a trunk or segment, along which all the computers of the network
are connected

Star
All computers are connected using cable segments to a central component called a switch. The
signals from the transmitting computer go through the switch to all the others.

Tree
Tree Topology is a topology which is having a tree structure in which all the computers are
connected like the branches which are connected with the tree.

NETWORK PROTOCOL: A protocol means the rules that are applicable for a network.
Protocols defines standardized formats for data packets, techniques for detecting and correcting
errors etc.
TCP/IP (Transmission Control Protocol/ Internet Protocol
● The IP protocol ensures that each computer or node connected to the Internet is
assigned an IP address, which is used to identify each node independently.

71 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
● TCP ensures that the message or data is broken into smaller chunks, called IP packets.
Each of these packets are routed (transmitted) through the Internet, along a path from one
router to the next, until it reaches the specified destination. TCP guarantees the delivery of
packets on the designated IP address. It is also responsible for ordering the packets so that they
are delivered in sequence.
FTP (File Transfer Protocol): It is a standard internet protocol provided by TCP/IP used for
transmitting the files from one host to another. It is mainly used for transferring the web page
files from their creator to the computer that acts as a server for other computers on the internet.
It is also used for downloading the files to computer from other servers.
SMTP (Simple Mail Transfer Protocol.): SMTP is a set of communication guidelines that
allow software to transmit an electronic mail over the internet is called Simple Mail Transfer
Protocol.
Point-to-Point Protocol (PPP) is protocol that is used to directly connect one computer system
to another. Computers use PPP to communicate over the telephone network or the Internet.
Post Office Protocol version 3 (POP3) Protocol: (POP3) is a standard mail protocol used to
receive emails from a remote server to a local email client. POP3 allows you to download
email messages on your local computer and read them even when you are offline. en J, and
JVM Telnet Telnet is a program that allows a user to log on to a remote computer. Telnet
provides a connection to the remote computer in such a way that a local terminal appears to be
at the remote side.
VoIP : VoIP stands for Voice over Internet Protocol. It is also referred to as IP telephony,
internet telephony, or internet calling.
Web Services: Web Services means the services provided by World Wide Web. The World
Wide Web provides services like chatting, emailing, video conferencing, e-learning, e-
shopping, e-reservation, e-groups and social networking.
World Wide Web (WWW): The World Wide Web commonly referred to as WWW, W3, or
the Web is an interconnected system of public webpages accessible through the Internet.It was
invented by Tim Berners-Lee in 1989. Major components of WWW are:
1. Web Server – It is a computer that stores website resources (web pages, images, videos,
etc.).
2. Web Browser (Client) - A software application used to access the web resources.
3. Webpage - Hypertext documents formatted in Hypertext Mark-up Language (HTML)
and displayed in a web browser.
4. Website - A website is a collection of inter-linked web pages that is identified by a
common domain name (website name) and stored on a web server.
5. HTTP Protocol - It governs data (web page) transfer between a server and a client.
6. HTML- A mark-up language used to specify the structure of a webpage.
7. URL- Address used to identify documents and other web resources on the internet.

Web Architecture
Web is working based on a client-server architecture.

72 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Client: It is a computer capable of requesting, receiving & displaying information in the form
of web pages or using a particular service from the service providers (Servers).
Servers: It is a remote computer which provides/transfers information to the client (in the form
of web pages) or access to particular services.

Difference between Internet and WWW


Internet World Wide Web(WWW)
Internet stands for Interconnected Networks WWW stands for World wide Web
Internet is a means of connecting a World Wide Web which is a collection of
computer to any other computer anywhere information which is accessed via the
in the world. Internet.
WWW is service on
Internet is infrastructure. top of that infrastructure.

WWW is more software-oriented as


Internet is primarily hardware-based
compared to the Internet.
Internet uses TCP/IP protocol. WWW uses HTTP Protocol.

HTML (Hypertext Mark-up Language): It is a mark-up language that tells web browsers
how to structure the web pages you visit. It has a variety of tags and attributes for defining the
layout and structure of the web document. A HTML document has the extension .htm or .html.
Hypertext is a text which is linked to another html document via clickable links known as
hyperlinks.
XML (eXtensible Mark-up Language): XML is a mark-up language like HTML but it is
designed to transport or store data. It does not have predefined tags but allows the programmer
to use customized tags. An XML document has the extension .xml.

HTML v/s XML


HTML XML
HTML stands for Hyper Text Mark-up XML stands for eXtensible Mark-up
Language Language
HTML is a case insensitive. XML is case sensitive.
Predefined tags (commands). User defined tags (commands).
It is used for presentation of the Data. It is used for transportation of the Data.
Small errors can be ignored. Errors not allowed.

73 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Closing tags are optional. Compulsory to use closing tags.

HTTP - Hyper Text Transfer Protocol: HTTP is used to transfer data across the web. HTTP
specifies how to transfer hypertext (linked web documents) between two computers. It allows
users of the World Wide Web to exchange information found on web pages.
Hypertext Transfer Protocol Secure (HTTPS) is an extension of the HTTP which is used for
secure communication over a computer network.

Domain Names: Every device connected to the Internet has a numeric IP address which is very
difficult to remember. Each computer server hosting a website or web resource is given a name
known as Domain Name corresponding to unique IP addresses. For example, IP addresses and
domain names of some websites are as follows:
Domain Name IP Address
ncert.nic.in 164.100.60.233
cbse.nic.in 164.100.107.32
The process of converting a hostname (such as www.google.com) into the corresponding IP
address (such as 172.217.14.196) is called domain name resolution. Specialized DNS servers
are used for domain name resolution (DNS resolution).
URL-Uniform Resource Locator: Every web page that is displayed on the Internet has a
specific address associated with it, this address is known as the URL. The structure of a URL
can be represented as follows:
http://www.example.com/planet/earth/river.jpg

Protocol Domain name foldername filename


The URL consists of four basic parts, namely, protocol, hostname, folder name and the
filename. Each one of these has a specific function.
1) The “protocol” indicates the type of Protocol (http/https/ftp etc.) being used. The
protocol is always followed by “://” and the host name.
2) The host name/domain name is the Internet address of a remote computer on which the
files reside.
3) The folder name indicates the name of the directory in which the files are located.
4) The filename specifies the name of the specific document to be displayed in the
browser. The filename itself consists of two pieces of information, the name of the file
to be displayed and the file extension, which specifies the file type (.htm for HTML file,
.txt for a text file, .bmp for a bitmap image, etc.)
The structure of a URL can be represented as follows:
Websites: A website is a collection of linked web pages (plus their associated resources) that
share a unique domain name.
Web page: Web page is an electronic document designed using HTM linked with hyperlinks.
Web Browser: Web browser is software program to navigate the web pages on the internet.
E.g., Google Chrome, Mozilla Firefox, Internet Explorer, Safari, Opera etc.
Cookie: A cookie is a small text file that stores information stored on your computer. Cookies
often store your settings for a website, such as your preferred language or location, pages

74 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
visited. Web Server: A web server is a computer or a group of computers hosting one or more
websites. E.g., Apache, IIS etc.
Web Hosting: Web hosting is the process of uploading/saving the web content on a web server
to make it available on WWW.

Model Questions I. Multiple Choice Questions


1. What are the three common types of computer networks?
a. ROM, MAN, LAN b. RAM, WAN, LAN
c. MAN, LAN, WAN d. None of the above
2. What is the acronym for LAN?
a. Local Area Network b. Local Access Network
c. Line And Networking d. Line-less Networking
3. Define what a LAN is?
a. Connected devices share the resources of a single processor or server within a small
geographic area
b. Normally find within a business and school
c. These are computers that share resources over a large area
d. None of the above
4. Mr. John is a small businessman who runs Hardware. He has been experiencing problems
with his small accounting department, which he depends on to provide sales reports. Mr.
John wants to share information between his 7 computer stations and have one central
printing area. What type of network would you recommend to Mr. John?
a. MAN b. LAN
c. WAN d. SAN
5. WAN covers a larger geographical area than MAN?
a. True b. False
6. A network that consists of both LANs and MANs is called a Wide area network?
a. True b. False
7. Arrange the Following Types of Networks according to their size, from largest to smallest?
a. LAN, WAN, MAN b. WAN, LAN, MAN
c. MAN, LAN, WAN d. WAN, MAN, LAN
8. You are a member of a club that deals with computer networks. The club has to take a
project to build a MAN. Where would this project likely take place?
a. A small building/organization b. University or college
c. Home d. None of the above
9. What is the acronym MAN stand for?
a. Magnetic Access Network b. Metropolitan Area Network
c. Multi-Area Network d.. Multi-Access net
10. In your school there is a library, and you can use the internet to do research, this library
will most likely be a WAN network?
a. True b. False
75 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
11. Types of Networks are Categories by their Geographical Area cover?
a. True b. False
12. Metropolitan Area Network Normally Require an Internet connection?
a. True b. False
13. What’s a web browser?
a. A kind of spider
b. A computer that store www files
c. A person who likes to look at websites
d. A software program that allows you to access sites on the World Wide Web
14. A _____ is a document commonly written and is accessible through the internet or other
network using a browser?
a. Accounts b) Data
c) Web page d) Search engine
15 Which of the following is used to read HTML code and to render Webpage?
a) Web Server b) Web Browser
c) Web Matrix d) Weboni
16. Which of these tech company owns Firefox web browser?
a) Lenovo b) IBM
c) Apple d) Mozilla
17. Which of the following browsers were/are available for the Macintosh?
a) Opera b) Safari
c) Netscape d) All of these
18. What is the name of the browser developed and released by Google?
a) Chrome b) Googly
c) Heetson d) Titanium
19. Which of the following is a Web Browser?
a) MS-office b) Notepad c) Firefox d) Word 2007
20. Which of the following is not a web browser?
a) Chrome b) Microsoft Edge c) Safari d) Ubuntu
21.URL stands for
(a) Uniform Research Limited (b) Uniform Resource Locator
(c) Uniform Resource Labs (d) Uniform Research Locator
22. LinkedIn is an example for _____________________ website.
(a) E-learning (b) E-commerce
(c) Video conferencing (d) Social networking
23. Which of the following is not a web service?
(a) Distance Learning (b) E-mailing
(c) Video conferencing (d) Social networking
24. Web browsers are also called as _______________
(a) Web Servers (b) Web Clients (c) Web Hosting (d) Web Designing
25. Working of WWW based on ___________________ architecture.
(a) Peer-To-Peer architecture (b) Client-Client architecture
(c) Client-Server architecture (d) Server-Server architecture

76 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
26. ________________ is a computer software capable of requesting, receiving & displaying
information in the form of webpages.
(a) Web Servers (b) Web Browsers
(c) Web Designers (d) Web Camera
27. A ____________ is a program or automated script which browses the World Wide Web in
a methodical, automated manner.
(a) Web Servers (b) Web Browsers
(c) Web Designers (d) Web Crawler
28.________________ is a mark-up language that helps in developing web pages.
(a) HTTP (b) HTML (c) XML (d) C++
29. ________________ is a language used to transport data over internet.
(a) HTTP (b) HTML (c) XML (d) C++
30.___________ is a set of rules for communication between two computers over a network.
(a) Modem (b) Protocol
(c) Switch (d) IP address
31.In web services, the communication takes place between
(a) Two electronic devices (b) Two human beings
(c) Two spiders (d) None of the above
32.Web services means services provided by ________________________
(a) Microsoft (b) Google
(c) BSNL (d) World Wide Web

II. Very Short Answer Type Questions(1-mark)


1. Name The transmission media best suitable for connecting to hilly areas.
2. How many pair of wires are there in twisted pair cable (Ethernet)?
3. Name a device that forwards data packets along networks.
4. What is the full form of WWW?
5. What is the full form of Internet?
6. Who invented the WWW in 1989?
7. Special software’s that is used to view webpages are ____________
8. ________ are used to store webpages, so whenever a request, it will serve the request.
9.____________ are programs /computers used to store information’s in the form of
webpages.
10. Web pages that are linked to each other via __________
11. ____________ protocol is used to transfer web pages over internet.
12. Full form of HTTP?
13._____________ is a massive collection of digital pages to access information over the
Internet 14. Write any 2 differences between HTML & XML?
15.___________ is a real-time communication between two or more users via computer.
16.___________ helps us to learn anywhere using Internet.
17.___________ allows customers to conduct financial transactions on a secure Website.
18. Internet can be used to get reservation of trains and air planes through _______ service.
19. ___________ helps to create and maintain social relationship over web.
20. Expand the following abbreviations:

77 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a. HTTP
b. XML
c. HTTPS
d. HTML
e. VoIP
21. Name any two common web browsers.
22. Full form of Email is ______________________
23.What out of the following, you will use to have an audio visual chat with an expert sitting in
a faraway place to fix-up technical issues?
(i) E-mail (ii) VoIP (iii) FTP
24. Match the following
Web Services Description
A Video conferencing P Without ever having to go booking office
Self-paced learning modules allow students to
B E-Shopping Q
work at their own speed
Each of the end user has a camera as well as
C E-mail R microphone to capture video and audio in real
time and it will be transmitted over internet
Purchasing products through computers/mobile
D E-reservation S
devices
Messages normally reaches a recipients account
E E-learning T
within seconds

25. Match the following


Web Services Applications
A Video conferencing P IRCTC
B E-Shopping Q Diksha App
C E-mail R GEM
D E-reservation S Gmail
E E-learning T Instagram
F Social Networking U VConSol

III.Short Answer Type (Theory with Answers)


1. What are Protocols? Name the protocol used to transfer a file from one device to the other.
Protocols are set of rules that are followed while transmitting data through a computer
network. Protocols determines how to data can be moved securely from a source device to a
destination device. The protocol used for transferring a file from one device to another is the
File Transfer Protocol (FTP)

2. What is meant by an IP Address? Give an example for IP Address.


An IP Address is a numerical address that uniquely identifies every device connected to a
network or internet. The user’s physical location can be tracked by using an IP Address. IP
V4 (IP Version 4) is a popular version of IP Address. IP Address (in IP V4) consists of four set
of numbers separated by a dot. These numbers can range from 0 to 255.

78 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
An example IP Address format is given below:
192.158.12.38
3. Explain how an IP Address become helpful in investigating cyber-crimes.
IP address can be used to trace the physical location of a user connected to a network. By this
many cyber crime can be investigated and traced out efficiently tracking the exact location
from where the cybercrime is carried out.

4. Why Protocols are needed in the case of Data Communication?


The communicating devices may be in different geographical areas. The speed of these devices
may be different. Also, the data transfer rates of different networks may be different. These
complexities make it necessary to have a common set of rules i.e., Protocols to ensure the
secure communication of data
5. What is the difference between World Wide Web & Internet?
Internet means interconnected networks that spread all over the world (i.e. the physical
infrastructure), while WWW means the information’s (available in the form of webpages) that
can be accessed through internet.

6. What is a protocol, give some examples?


Protocols are set of rules that are followed while transmitting data through a computer
network. Protocols determines how to data can be moved securely from a source device to a
destination device. The protocol used for transferring a file from one device to another is the
File Transfer Protocol (FTP)

7. What is the difference between E-mail and chat?


In order to chat, you need to have an account on the same service as the person you are
chatting with. e.g. on the other hand, in case of E-mail, it is not necessary, i.e. you can have an
account from any provider and you can establish your own.

8. What are cookies?


Cookies are files stored temporarily on www browser’s computer, which allow the www
server to store persistent information associated with browsing user on user’s system.

9. What is the difference between domain name and IP address? IP addresses look like this:
192.168.12.134.
Domain names look like this: “www.google.com”
Domain names are easier for us to remember and use, while computers are quite handy with
numbers. Thus, we use DNS (Domain Naming System) to translate domain names into the IP
addresses.
IP address is a unique identifier for a computer or device on internet. A domain name (website
name) is a name that identifies one or more IP addresses (when hosted at different servers for
load balancing).

10. Give one suitable example of each URL and domain name?
URL: https://kvsangathan.nic.in/hq-gyan-kosh
Domain name: kvsangathan.nic.in
79 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
11. Differentiate between XML and HTML.
XML was designed to describe data and to focus on what data is.
HTML was designed to display data and to focus on how data looks.
HTML is about displaying information while XML is about describing information.

12. Distinguish between website and web browser.


Website:- It is a collection of inter-linked web pages stored in a server.
Web Browser:- It is a software application for retrieving, presenting and traversing
through information resources in the form of web pages available on the World Wide
Web.

13. Differentiate between the terms Domain Name and URL in context of web services. Also
write one example of each to illustrate the difference.
Domain Name URL
A domain name or website name URL is a string that represents the complete web
is a human-friendly text form of address of any web page. It’s used to locate a
the IP address. webpage.
It is the part of the URL that is It is the string that represents a complete web
more human friendly. address that contains the domain name.
Example: kvsangathan.nic.in Example: https://kvsangathan.nic.in/contact-us

22.Differentiate between communication using Optical Fiber and Ethernet Cable in context of
wired medium of communication technologies.
Optical Fibre - Very Fast - Expensive - Immune to electromagnetic interference
Ethernet Cable - - Slower as compared to Optical Fiber - Less Expensive as compared
to Optical Fiber - prone to electromagnetic interference

IV. Previous CBSE Board Questions


1) Ravi was trying to log-in to his internet-banking account. He noticed that the URL of
the net banking starts with 'https'. The 's' in 'https' stands for _______ (i) Simple 0(ii)
Smart (iii) Secure (iv) Strength

2) What is mean by the homepage of a website?

3) What is the significance of the URL?

4) Which of the following is not a network protocol? (i) HTML (ii) HTTP (iii) SMTP
(iv) FTP

5) Which of the following internet protocols provides secure data transmission between
server and browser with the help of encryption.
a) HTTP b) HTTPS c) TELNET d) ARPANET

80 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6) Devanand, a student of Class XII, is not able to understand the difference between web
client and web-server. Help him in understanding the same by explaining their role and
giving suitable example of each.

7) Write the full form of Cc and Bcc (used in email communication). Explain the
difference between them.

8) Define Internet and write its two uses in our daily life. How is it different from the
World
Wide Web (WWW).

9) Web _________ is a software used to view web pages.

10) In a network, _____________ is a computer that provides data and resources to other
computers.

11) How is a website and a webpage related?

12) Microsoft Edge, Apple Safari are examples for __________________

13) What is the use of a server in a computer network?

14) Among the following service available on the World Wide Web are?
i) Email ii) HTML iii) XML iv) Video conferencing
a) (i) and (ii) (b) (i) and (iv)
(c) (ii) and (iii) (d) None of the above
15) HTML and XML are _______________
a) Programming Languages (b) Scripting Languages
(c) Mark-up Languages (d) None of the above
16) XML uses _____________
a) User defined tags (b) Predefined Tags
(c) Both user defined and predefined tags (d) None of the above
17) XML was not designed to ____________________
a) store the data (b) present the data
(c) carry the data (d) both a & c
18) Which of the following will you suggest to establish the online face to face
communication between the people in the Regional Office Ernakulum and Delhi
Headquarter?
a) Cable TV (b) Email (c) Text chat
(d) Video Conferencing
19) What kind of data gets stored in cookies and how is it useful?

20) What do the following top level domains signify?


a) .com
b) .org
81 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
21) “With XML you invent your own tags”, Explain this statement with the help of
example. 22) Define Domain Name Resolution?

23) ____________ tags are case sensitive and _____________ tags are not case sensitive.
(a) HTML, XML (b) HTTP, XML
(c) XML, HTTP (d) XML,HTML

24) Which of the following is not a web browser ?


(a) Google Chrome (b) Internet Explorer (c) Mozilla Firefox (d) Photoshop

25) Which protocol helps us to browse through web pages using internet browsers?

26) Name any one internet browser.

27) XML stands for


(A) Xtra Markup Language
(B) Extensible Markup Language
(C) Extensible Marking Language
(D) Extensive Marked Language
28) We can upload a file to a web server using a protocol called __________.
(A) FPT (B) IP (C) TCP (D) FTP

29) _____________ delivers the requested web page to web browser.

30) MyPace University is setting up its academic blocks at Naya Raipur and is planning to
set up a network. The University has 3 academic blocks and one Human Resource
Center as shown in the diagram below: Study the following structure and answer
questions (a) to (e)

Center to Center distances between various blocks/center is as follows:


Law Block to business Block 40m
Law block to Technology Block 80m
Law Block to HR center 105m
Business Block to technology Block 30m
Business Block to HR Center 35m
Technology block to HR center 15m

Number of computers in each of the blocks/Center is as follows:


Law Block 15
Technology Block 40
HR center 115
Business Block 25
82 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a) Suggest the most suitable place (i.e., Block/Center) to install the server of this
University with a suitable reason.
b) Suggest an ideal layout for connecting these blocks/centers for a wired connectivity.
c) Which device will you suggest to be placed/installed in each of these blocks/centers to
efficiently connect all the computers within these blocks/centers?
d) Suggest the placement of a Repeater in the network with justification.
e) The university is planning to connect its admission office in Delhi, which is more than
1250km from university. Which type of network out of LAN, MAN, or WAN will be
formed? Justify your answer.

Test Your Self : PART I


1 Write any 1 advantage and 1 disadvantage of Bus topology.

2. What happens to the Network with Star topology if the following happens:
(i) One of the computers on the network fails?
(ii) The central hub or switch to which all computers are connected, fails?

3. Two doctors have connected their mobile phones to transfer a picture file of a person
suffering from a skin disease. What type of network is formed?

4. SunRise Pvt. Ltd. is setting up the network in the Ahmadabad. There are four
departments named as MrktDept, FunDept, LegalDept, SalesDept.

Distance between various buildings is given as follows:


MrktDept to FunDept 80 m
MrktDept to LegalDept 180 m
MrktDept to SalesDept 100 m
LegalDept to SalesDept 150 m
LegalDept to FunDept 100 m
FunDept to SalesDept 50 m

Number of Computers in the buildings


MrktDept 20
LegalDept 10
FunDept 8
SalesDept 42

i) Suggest a cable layout of connections between the Departments and specify topology.
ii) Suggest the most suitable building to place the server with a suitable reason. iii)
Suggest the placement of i) modem ii) Hub /Switch in the network. iv) The

83 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
organization is planning to link its sale counter situated in various part of the same
city/ which type of network out of LAN, WAN, MAN will be formed? Justify.

5. Name the protocol Used to transfer voice using packet switched network.
6. What is HTTP?
7. Write the purpose of the following devices:
(i). Network Interface Card
(ii). Repeater

Test Your Self : PART II


1. The ‘Grand Plaza ’ Mall has a computer network. The network is in one building. Name this
type of network( out of LAN/MAN/WAN).

2. Identify the type of topology on the basis of the following:


a. Since every node is directly connected to the server, a large amount of cable is needed
which
increases the installation cost of the network.
b. It has a single common data path connecting all the nodes

3. The following is a 32 bit binary number usually represented as 4 decimal values, each
representing 8 bits, in the range 0 to 255 (known as octets) separated by decimal points. 192.158.1.38
What is it? What is its importance?

4. Dinsey has to share the data among various computers of his two offices branches situated in
the same city. Name the network (out of LAN, WAN, PAN and MAN) which is being formed in this
process.

5. . Global Pvt. Ltd. is setting up the network in the Bangalore . There are four departments
Distances between various buildings are as follows:
Accounts to Research Lab 55 m
Accounts to Store 150 m
Store to Packaging Unit 160 m
Packaging Unit to Research Lab 60 m
Accounts to Packaging Unit 125 m
Store to Research Lab 180 m

Number of Computers
Accounts 25

84 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Research 100
Lab
Store 15
Packaging 60
Unit

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


ii) Suggest the most suitable place (i.e. buildings) to house the server of this organization.
iii) Suggest the placement of the following device with justification:
a) Repeater b) Hub/Switch

6. Write one example each of URL and IP address.

ANSWER KEY I. Multiple Choice Questions(MCQ)

1. c 2. a 3. a 4. b 5. a

6. a 7. d 8. d 9. b 10. a

11. a 12. a 13. d 14. c 15. b

16. d 17. b 18. a 19. c 20. d

21. b 22. d 23. a 24. b 25. c

26. b 27. d 28. b 29. c 30. b

31. a 32. d

II. Very Short Answer Type Questions(1-mark)


1. Microwave / Radio wave
2. Two insulated copper wires
3. Router
4. World Wide Web
5. Interconnected Networks
6. Tim Berners-Lee
7. Web browsers
8. Web servers

85 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
9. Web servers
10. hyperlinks
11. HTTP- HyperText Transfer Protocol
12. HyperText Transfer Protocol
13. World Wide Web(WWW) or Web
14. Refer comparison table
15. Chat
16. E-learning
17. Internet banking
18. E-reservation 19. Social networking websites 20.
a. HTTP- HyperText Transfer Protocol
b. XML – eXtensible Mark-up Language
c. HTTPS - HyperText Transfer Protocol Secure
d. HTML - HyperText Mark-up Language
e. VoIP-Voice over Internet Protocol
21. Google Chrome, Mozilla Firefox
22. Electronic mail
23. Ii.VoIP 24.
A Video conferencing P Each of the end user has a camera as well as
microphone to capture video and audio in real time
and it will be transmitted over internet
B E-Shopping Q Purchasing products through
computers/mobile devices
C E-mail R Messages normally reaches a recipients account within
seconds
D E-reservation S Without ever having to go booking office
E E-learning T Self-paced learning modules allow students to work at
their own speed
25.
Web Services Applications
A Video conferencing P VConSol
B E-Shopping Q GEM
C E-mail R Gmail
D E-reservation S IRCTC
E E-learning T Diksha App
F Social Networking U Instagram

IV.Previous CBSE Board Questions - Answers


1. (iii) Secure
2. The default (first) page of a website is called a Homepage.
3. URL specifies unique address of each document on the internet.
4. (i) HTML
Internet Protocols for communication over the Internet, the communicating devices must
follow certain rules. These rules are called Internet protocols.

86 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
For email communication, we use SMTP and POP.
For communication between browser and server HTTP and HTTPS protocols are used. We
can use TELNET to access services available on a remote computer.
5. b) HTTPS
6. Web-Client: An application that requests for services from a webserver. Example: Web
Browsers, Chatting Applications
Web-Server: Web-server is a software (or any dedicated computer running this software) that
serves the request made by web-clients. Example: Apache Server.
7. Cc : Carbon Copy: every recipient can check who else has received the mail. Bcc :
Blind Carbon Copy: no recipient can check who else has received the mail.
8. The Internet is a worldwide network that links many smaller computer-networks. Uses
of the Internet 1. E-learning 2. E-commerce
The difference between the internet and www:
Internet means interconnected networks that spread all over the world (i.e. the physical
infrastructure), while WWW means the information’s (available in the form of webpages) that
can be accessed through internet.
9. Web Browser
10. Server
11. A website is a collection of interlinked webpages.
12. Web Browsers
13. Role of server is to serve various clients (sharing data or resources among multiple
clients)
14. (b) (i) and (iv)
15. (c) Mark-up Languages
16. (a) User defined tags
17. (b) present the data
18. (d) Video Conferencing
19. Cookies can store a wide range of information, including personally identifiable
information (such as your name, home address, email address, or telephone number).
Cookies often store your settings for a website, such as your preferred language or location.
When you return to the site, browser sends back the cookies that belong to the site. This allows
the site to present you with information customized to fit your needs.
20. (a) .com - commercial
(b) .org - organization
21. XML tags are created by the user as there are no standard tags.
Ex : <name>Nayana<name>
22. The process of converting domain names (website names) into corresponding IP address
with the help of DNS servers is called domain name resolution.
23. (d) XML,HTML
24. (d) Photoshop
25. HTTP - Hyper Text Transfer Protocol
26. Google Chrome or any other valid browser name
27. (B) Extensible Markup Language
28. (D) FTP
29. Web Server
87 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
30 a. Most suitable place to install the server is HR center, as this center has maximum number
of computers. c. Switch
d. Repeater may be placed when the distance between 2 buildings is more than 70 meter.
e. WAN, as the given distance is more than the range of LAN and MAN.

Test Yourself: PART I


1. Advantage: Since there is a single common data path connecting all the nodes, the bus
topology uses a very short cable length which considerably reduces the installation
cost. Disadvantage: Fault detection and isolation is difficult. This is because control
of the network is not centralized in any particular node. If a node is faulty on the bus,
detection of fault may have to be performed at many points on the network. The faulty
node has then to be rectified at that connection point.
2. (i). failure in one cable will not affect the entire network
(ii). If the central hub or switch goes down, then all the connected nodes will not be able to
communicate with each other.

3. PAN

4. i. Star Topology should be used.

ii) As per 80 – 20 rule, SalesDept because it has maximum no. of computers. iii)Each
building should have hub/switch and Modem in case Internet connection is required.
iv)MAN (Metropolitan Area Network)

5. VoIP

6. HTTP is a protocol that is used for transferring hypertext(i.e. text, graphic, image,
sound, video, etc,) between 2 computers and is particularly used on the World Wide
Web
(WWW) 7.

(i) Network Interface Card (NIC) is a network adapter used to set up a wired network. It acts
as an interface between computer and the network.
(ii) A repeater is a device that amplifies a signal being transmitted on the network.

88 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Test Yourself: PART II
1. LAN
2.
a. Star Topology
b. Bus Topology
3. It is an IP Address. It is used to identify the computers on a network
4. MAN
5. (i)
(ii)The most suitable place/ building to house the server of this organization would be building
Research Lab, as this building contains the maximum number of computers
(iii). a)Repeater : distance between Store to Research Lab is quite large, so a repeater
would ideally be placed.
b)Hub/Switch : Each would be needed in all the buildings to interconnect the group of
cables from the different computers in each building.
6.IP address 192.168.1.1
URL : https://www.apple.com/

89 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
DBMS-DATABASE MANAGEMENT SYSTEM
DBMS: A database management system (DBMS) is a software that is responsible for storing,
maintaining and utilizing databases.
Examples- MySQL, Oracle, PostgreSQL, SQL Server, Microsoft Access, MongoDB.

Relational model:
The relational model uses a collection of tables to represent both data and the relationships
among those data. Each table has multiple columns, and each column has a unique name.
The columns of the table correspond to the attributes of the record type and a row in a table
represents a relationship among a set of values.

Relation: A Relation is logically related data organized in the form of tables.


Attribute/ Field: Column of a table is called Attribute or Field.
Tuple/ Entity/ Record: Rows of a table is called Tuple or Record.
Domain: It is collection of values from which the value is derived for a column.
Degree - Number of columns (attributes) in a table.
Cardinality - Number of rows (Records) in a table.

Primary Key – A primary is an attribute or set of attributes in a relation that uniquely


identifies tuples (rows) in that relation.

90 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Candidate Key –It is an attribute or a set of attributes or keys participating for Primary Key,
to uniquely identify each tuples in that relation.

Alternate Key – A candidate key that is not the primary key is called alternate key or
secondary key.

Foreign Key – Foreign keys are the attributes of a relation that points to the primary key of
another relation

Model Questions
I. Multiple choice Questions(MCQ):
1. DBMS stands for_____________
a) Data Base Management Software
b) Data Base Maintenance System
c) Data Basic Management System
d) Data Base management system 2. In RDBMS, R stands for_________
a) Relational
b) Rotational
c) Rational
d) None of the above

3. A Database contains one or more_______


a) Data
b) Tables
c) Files
d) Links

4. What is not true in respect of DBMS?


a) Database enforces standards
b) Database increases redundancy
c) Database facilitates sharing of data
d) Database helps to maintain integrity

5. Cardinality is total ___________


a) number of rows in a table
b) number of columns in a table
c) number of data items in a table
d) none of the above

6. Degree refers to total_________


91 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a) number of rows in a table
b) number of columns in a table
c) number of data items in a table
d) none of the above

7. Data about data is _________


a) Data redundancy
b) Meta Data
c) Database schema
d) None of the above

8. Repetition of data is called ..............


a) Data redundancy
b) Data Description
c) Data inconsistency
d) None of the above

9. Mismatched redundant copies of data is known as data ............


a) Dependence
b) Inconsistency
c) Isolation
d) Redundancy

10. A ............ is an organized collection of structured data.


a) Database
b) File
c) DBMS
d) Information

11. A data ................ is a set of rules that define valid data.


a) Query
b) Constraint
c) Dictionary
d) All of the above

12. A relational database consists of a collection of ..............


a) Fields
b) Records
c) Keys
d) Tables

13. A row in a database.


92 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a) Field
b) Record
c) Key
d) Table
14. The term ____________ is used to refer to a field in a table.
a) Attribute
b) Row
c) Tuple
d) Instance

15. Which of the following statements is not true about relational database?
a) Relational data model is the most widely used data model.
b) The data is arranged as a collection of tables in relational database.
c) Relational database increases data redundancy and inconsistency.
d) None of the above.
16. Which of the following is a disadvantage of file processing system?
a) Data redundancy
b) Data isolation
c) Data inconsistency
d) All of the above

17. Table: Employee


EMPID ENAME SALARY DEPTNO Email

1001 George 30000 10 George23@yahoo.co.in


1002 Mary 32000 12 Mary_123@yahoo.co.in

1003 Alwin 25000 12 Al_win@gmail.com

1004 Sumit 20000 11 Sumit_222@yahoo.co.in

Answer the questions based on the table Employee.


a) The cardinality of the table Employee is ……
i) 5
ii) 4
iii) 3 iv)
6
b) The degree of the table Employee is …….
i) 3
ii) 4
iii) 5 iv)
6

c) Which column can be made as the primary key in the table Employee?
93 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
i) E
MPID
ii)
EMAIL
iii) Both i and ii
iv) None of the above

d) If two columns are added to the table Employee, then the cardinality and degree
of the table is …… and …… respectively. i) 4 , 7 ii) 7, 4 iii) 6,5 iv) 5,6
18. An attribute in a relation is a foreign key if it is the ________ key in any other relation.
a) Candidate
b) Primary
c) Super
d) Sub

19. A(n) ________ in a table represents a logical relationship among a set of values. a)
Column
b) Key
c) Row
d) Attribute

II. Very Short Answer Questins:

1) What is meant by a database?


2) Define primary key?Give an example.
3) What do you mean by candidate key?
4) What is meant by degree and cardinality of a table?
5) What is meant by DBMS?
6) What is meant by database schema?
7) What is meant by data constraint?
8) What is meant by relation?

ANSWERS:
I. Multiple Choice Questions (MCQ )

94 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1 d 2 a 3 b 4 b
5 a 6 b 7 b 8 a

9 b 10 a 11 b 12 d

13 b 14 a 15 c 16 d
17a) (ii) 17b) (iii) 17c) (iii) 17d) (ii)

18 b 19 c

II. Very Short Answer Answers:


1 A database is an organized collection of structured information, or
interrelated data, typically stored in a computer system.

2 A primary key is a column or set of columns that contain values that uniquely
identify each row in a table.
For example Rno can be primary key of the table student.
Table:Student
RNO NAME MARK

100 Tanay 30
101 Kiran 50

102 Manu 30

3 It is an attribute or a set of attributes capable of being the Primary Key, to


uniquely identify each record in that table.

4 Degree refers to the number of attributes/columns in a relation. Cardinality


refers to the number of tuples/rows in a relation.

5 RDBMS (Relational Database Management System) is the software used to


store, manage, query, and retrieve data stored in a relational database.

6 Database schema is also called the visual or logical architecture as it tells us


how the data are organized in a database.

7 Restrictions or limitations on the type of data that can be inserted in one or


more columns of a table to ensure accuracy and reliability of data in the
database.

8 A relation is a named, two dimensional table storing logically related data.

STRUCTURED QUERY LANGUAGE(SQL)


SQL(Structured Query Language) is a language that is used to manage data that is held in a
relational database management system.

95 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
1.4 SQL Commands
SQL commands are used to communicate with the database to perform specific tasks,
functions, and queries of data.
1.5 Types of SQL Commands
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1.5.1 DDL or Data Definition Language : DDL is a set of SQL commands used to create,
modify, and delete database structures/tables but not data. List of DDL commands:
CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
1.5.2 DML (Data Manipulation Language): DML commands deal with the manipulation of
data present in the tables. List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.
1.6 DATATYPES

⮚ Text Data types


Char(size) – fixed length of size bytes
Varchar(size)-variable length of size bytes
⮚ Number Data types
Integer(size)or Int- It represents a number without decimal point
Float(Size)-It represents a floating point number

96 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
➢ Date data type Date
1.7 CONSTRAINT: A Constraint is a condition or check applicable on a field or set of fields.
Types of Constraints:

⮚ Unique Constraint :-This ensures that no rows have the same value in the specified
column(s). There can be many unique constraints defined on a table.
Syntax: Create table EMP (ecode integer unique, ename char(20),sex char(1) );

⮚ Primary key Constraint: This declares a column as the primary key of the table This is
similar to unique constraint except that a table can have only one primary key and also that,
a primary key does not allow NULL values but Unique key allows NULL values.
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
CREATE TABLE Persons ( ID int NOT NULL, LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int, PRIMARY KEY (ID));

⮚ Not null: This constraint ensures column should not contain NULL
Syntax: Create table EMP(ecode integer Not null unique, ename char(20),sex char(1) );
1.8 DATABASE COMMANDS IN MYSQL
⮚ CREATE DATABASE: used for creating a database in MySQL. Syntax:
mysql>CREATE DATABASE movies;

⮚ SHOW DATABASES: Display list of existing databases


Syntax: mysql>SHOW DATABASES;

⮚ USE : Select a particular database.


Syntax: mysql>USE database_name;

⮚ DROP DATABASE: Used to drop an existing SQL database.


Syntax :mysql>DROP DATABASE database_name;
➢ CREATE TABLE: Used to create a new table in a database.
Syntax: CREATE TABLE table_name ( column1 datatype, column2
datatype, column3 datatype, ....);
Example: The following example creates a table called "Persons" that contains five columns:
PersonID, LastName, FirstName, Address, and City:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
97 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
);

⮚ SHOW TABLES: Display all the names of tables present in the database
Syntax: mysql> SHOW TABLES;

⮚ DESCRIBE TABLE : Shows the structure of the table, such as column names, constraints on
column names, etc. The DESC command is a short form of the DESCRIBE command. Both
DESCRIBE and DESC commands are equivalent.
Syntax mysql> DESCRIBE | DESC table_name;

➢ ALTER TABLE Statement: Used to add, delete, or modify columns/constraints in an


existing table.

ALTER TABLE - ADD Column/Attribute syntax: ALTER TABLE

table_name ADD column_name datatype;

Example ALTER TABLE Customers ADD Email varchar(255);

ALTER TABLE - DROP COLUMN

Syntax: ALTER TABLE table_name DROP COLUMN column_name;

Example ALTER TABLE Customers DROP COLUMN Email;

ALTER TABLE – ADD PRIMARY KEY

Syntax: ALTER TABLE table_name ADD PRIMARY KEY (Column_name);

Example ALTER TABLE Persons ADD PRIMARY KEY (ID);

ALTER TABLE – DROP PRIMARY KEY

Syntax: ALTER TABLE table_name DROP PRIMARY KEY;

Example : ALTER TABLE Persons DROP PRIMARY KEY;

➢ DROP TABLE Statement: Used to drop an existing table in a database.

Syntax: DROP TABLE table_name;

Example: DROP TABLE Shippers;

➢ INSERT INTO Statement: Used to insert new records in a table.


Syntax 1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Syntax 2: Add all column data without specifying column names

98 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
INSERT INTO table_name VALUES (value1, value2, value3, ...);

➢ DELETE Statement: Used to delete existing records/rows in a table.

Syntax: DELETE FROM table_name WHERE condition;

Example: DELETE FROM Customers; # Delete all rows from table Customers

➢ SELECT Statement: Used to select data from a database.

Syntax1: SELECT column1, column2, ... FROM table_name;

Syntax2: SELECT * FROM table_name; #selects all columns from table

➢ SELECT DISTINCT Statement : Used to return only distinct (different) values.

Syntax: SELECT DISTINCT column1, column2, ...FROM table_name;

Example: SELECT DISTINCT Country FROM Customers;

SQL Aliases: SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable. An alias only exists for the
duration of that query. An alias is created with the AS keyword.

Alias Column Syntax: SELECT column_name AS alias_name FROM table_name;

Alias Table Syntax: SELECT column_name(s) FROM table_name AS alias_name;

WHERE Clause: The WHERE clause is used to filter records and extract only those
records that fulfill the specified condition. It is used in select, update and delete SQL
statements

WHERE Syntax: SELECT column1, column2, ...FROM table_name WHERE condition;


Operators in The WHERE Clause

The following operators can be used in the WHERE clause:


Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

99 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
<= Less than or equal

<> Not equal. Note: In some versions of SQL


this operator may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a


column
The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators.
● The AND operator displays a record if all the conditions separated by AND are TRUE.
● The OR operator displays a record if atleast one of the conditions separated by OR is TRUE.
● The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax : SELECT column1, column2, ... FROM table_name

WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax: SELECT column1, column2, ... FROM table_name

WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax: SELECT column1, column2, ... FROM table_name

WHERE NOT condition;

The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.


IN Syntax: SELECT column_name(s) FROM table_name

WHERE column_name IN (value1, value2, ...);

The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates. The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax: SELECT column_name(s) FROM table_name

WHERE column_name BETWEEN value1 AND value2;

100 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

● The percent sign (%) represents zero, one, or multiple characters


● The underscore sign (_) represents one, single character

The percent sign and the underscore can also be used in combinations!

LIKE Syntax: SELECT column1, column2, ... FROM table_name

WHERE columnN LIKE pattern;


LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or Finds any values that have "or" in any position
%'

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second
position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length

WHERE CustomerName LIKE Finds any values that start with "a" and are at
'a__%' least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends
with "o"

101 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
What is a NULL Value?

A field with a NULL value is a field with no value.

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax: SELECT column_names FROM table_name

WHERE column_name IS NULL;

Example: SELECT CustomerName, ContactName, Address FROM Customers

WHERE Address IS NULL;

IS NOT NULL Syntax: SELECT column_names FROM table_name

WHERE column_name IS NOT NULL;

Example: SELECT CustomerName, ContactName, Address FROM Customers

WHERE Address IS NOT NULL;

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending(ASC -default) or


descending order (DESC).

ORDER BY Syntax: SELECT column1, column2, ... FROM table_name

ORDER BY column1, column2, ... ASC|DESC;

Example

SELECT * FROM Customers ORDER BY Country DESC;

SELECT * FROM Customers ORDER BY Country DESC, CustomerName;

➢ UPDATE Statement: Used to modify the existing records in a table.

Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ...

WHERE condition;

Example: UPDATE Customers

SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'

102 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
WHERE CustomerID = 1;
Aggregate (Group) function
● Aggregate functions are the functions that operate on a set of rows to give one result
per group.
● These sets of rows on which group function is applied may be the whole table or the
table split into groups by the use of GROUP by clause. Types of Group Functions
Function Description

sum() Find the sum of numeric values

avg() Find the average of numeric values

count() Counts the number of rows in a table

max() Find the maximum among all the values in a column

min() Find the minimum among all the values in a column


Remember the following points about group functions:
● All group functions, except count(*) ignore NULL values ● Functions -sum(), avg()
are used with NUMERIC data.
● Functions -min() and max() can be used with any data type
Example: Consider the following table employee

Q: Find the sum, average, minimum, maximum value of salaries of employees in the employee
table

Count() function

103 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Count () has got three formats:
Count(*) : This function returns the number of rows in the table that satisfy the criteria of
select statement. It includes duplicate rows and rows with NULL values in any of the column
Example: Count the number of employees in the employee table.

Count(<col name>): This function returns the number of not null values in the specified
column, but includes duplicate values in counting
Example: count the number of grades of employees in the employee table.

Count(DISTINCT <col name>): This function returns the number of unique, not null values
in the specified column.
Example: Count the number of different grades of the employee

Grouping Records (Group by clause)


● To divide the rows in a table into smaller groups of information, group by clause is
used.
● It combines all identical rows in a group of fields.
● A column name is used for grouping
Syntax;-
SELECT [DISTINCT] <COL LIST> FROM <TABLE NAME>
[WHERE <CONDITION>]
[GROUP BY < COLUMN NAMES>]
[HAVING <CONDITION>]
[ORDER BY <COL NAME>/<EXPR> ASC/DESC];

NOTE -

104 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
● Group by expression specifies the columns whose values determine the basis for
grouping rows Example
Q. Display the no of employees in each zone.

Q. Display the no of employees in each zone whose salary is greater than 32000

Having clause
● This clause is used to restrict rows resulting after grouping.
● Steps followed in execution of select with group by and having clause- 1. Rows
are grouped according to the columns in the group by clause.
2. Then the group function is applied.
3. Groups matching with Having clauses are displayed.
Example
Q. Display only whose departments with sum of salaries whose total salary is greater than
70000

105 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Cartesian Product (Cross Join or unrestricted join)
Returns a result in which Each row of the first table is paired with all the rows in the second
table which is rarely useful.

Example- Consider the following tables

Q: To display the cartesian product of the employee names and their department name

Joins in MySQL: A join is used when data from two or more tables is required based on the
common values existing in corresponding columns of two tables.There are many types of joins
such as:

106 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Equi join
● Specified columns from the joining tables are checked for equality.
● Values from joining tables are retrieved only if the condition in where clause is
satisfied.

SYNTAX:-
SELECT <column_name (s)>
FROM <table_name1>, <table_name2>, ...., <table_nameN>
WHERE <table_name1>.<column_name> = <table_name2>.<column_name>;

Q: to display the name of the employee and their department

You should always qualify the common columns when joining tables by using the “.” (dot)
operator.
Natural Join
This clause is based on all the columns in the two tables that have the same name. It selects the
rows from two tables that have equal values in the matched columns. The Resulting table
displays the common columns only once in the result.
SYNTAX:-

SELECT [column_names | *]
FROM table_name1
NATURAL JOIN table_name2;

Example- consider the same tables employee and department.

107 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Q : To display the name of employee and department of all employee

ASSERTION AND REASONING QUESTIONS


1. Assertion(A): The resultset refers to a logical set of records that are fetched from the
database executing an SQL Query.
Reason (R): Resultset stored in a cursor object can be extracted by using fetch(…)
functions.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
2. Assertion(A): In SQL, aggregate function avg()calculates the average value on a set of
values and produce a single result.
Reason (R): The aggregate functions are used to perform some fundamental arithmetic
tasks such as min(), max(), sum() etc.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A (c) A is true but R is
false
(d) A is false but R is true
3. Assertion(A): Primary key is a set of one or more attributes that identify tuples in a
relation.
Reason (R): The primary key constraint is a combination of the NOT NULL and UNIQUE
constraints.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
4. Assertion(A): Foreign key is a non-key attribute whose value is derived from primary
key of another table.
Reason (R): Each foreign key refers a candidate key in a relation.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
108 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5. Assertion(A): The SELECT statement in SQL is used to retrieve data from one or more
tables.
Reason(R): The SELECT statement can be used to retrieve all columns or a subset of
columns from a table.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
6. Assertion(A): The WHERE clause in SQL is used to filter data based on a specified
condition.
Reason(R): The WHERE clause is always required when using the SELECT statement
in SQL
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
7. Assertion (A): The ORDER BY clause in SQL is used to sort the result set in ascending
or descending order.
Reason(R): The ORDER BY clause can only be used with the SELECT statement in
SQL.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
8. Assertion (A): The IN operator in SQL is used to match a value with a list of values.
Reason(R): The IN operator can only be used with the where clause in SQL.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
9. Assertion (A): The between operator in SQL is used to match a value with in a range of
values.
Reason(R): The between operator can only be used with numerical values in SQL.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true
10. Assertion (A): The LIKE operator in SQL is used to match a value with a pattern.
Reason(R): The % and _ wildcard characters can be used with the LIKE operator in
SQL.
(a) Both A and R are true and R is the correct explanation of A
(b) Both A and R are true and R is not the correct explanation of A
(c) A is true but R is false
(d) A is false but R is true

109 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
ANSWERS
1. (b)
2. (b)
3. (a)
4. (b)
5. (a)
6. (b)
7. (a)
8. (b)
9. (b)
10. (a)

110 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
I Interface Python with SQL database

Database connectivity

Database connectivity refers to connection and communication between an application

and a database system.

The term “front-end” refers to the user interface, while “back-end” means the server,

application and database that work behind the scenes to deliver information to the user.

● Mysql.connector

Library or package to connect from python to MySQL.

Before we connect the program with mysql , we need to install connectivity package

named mysql-connector- python

● Command to install connectivity package pip install


mysql-connector-python ● Command to import connector
import mysql.connector

Steps for creating database connectivity

applications i) Start Python start python editor to

create our own python script.

ii) Import mysql.connector package

Import statement as shown below:

import mysql.connector
12

or

import mysql.connector as con

iii) Establishing a connection to MySQL DATABASE.


We need to establish a connection to a mysql database using connect () function of
mysql.connector package.

The connect statement creates a connection to the mysql server and returns a

MySQL connection object.

A database connection object controls the connection to the database. It represents a


unique session with a database connected from within a program.

111 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Syntax:
<Connection object> = mysql.connector.connect (host=<hostname>,user=<username>,
passwd=<password>, database=<database>)

Where,

Hostname-The hostname of database server or IP address

User -Username on MYSQL

Password-Password of the database user

Database-Name of the database

Example:

import mysql.connector
con=mysql.connector.connect(host=”localhost”,user=”root”, passwd=”manager “ ,
database=”student12”)

iv) Creating a cursor Object


It is a useful control structure of database connectivity. It will let us execute all the queries we
need. Cursor stores all the data as a temporary container of returned data and allows traversal so
that we can fetch data one row at a time from cursor. Cursors are created by the
<connectionobject>.cursor()method.
A Database cursor is a special control structure that facilitates the row by row processing
of records in the result set.

Syntax:

<cursor object>=<connectionobject>.cursor()
cursor=con.cursor()

112 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
v) Execute SQL query:

We can execute SQL query using<cursorobject>. execute() function .

Syntax:

<cursor object>.execute(<sql query string>)

cursor.execute(“select * from student”)

The above code will execute the SQL query and store the retrieved records

(resultset) in the cursor object(cursor).

Result set refers to a logical set of records that are fetched from the database

by executing an SQL query and made available in the program.

vi) Extract data from Result set:

The records retrieved from the database using SQL select query has to be

extracted as record from the result set. We can extract data from the result

set using the following fetch () function.

⮚ Multiple ways to retrieve data:


fetchall()

fetchone()

fetchmany()

❖ fetchall()

Fetches all the rows from the result set in the form of a tuple containing the records.

❖ fetchone()

Fetches only one row from the result set in the form of a tuple containing a record

Syntax:

<data>=<cursor>.fetchall()

<data>=<cursor>.fetchone()

data=cursor.fetchall()

113 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
for row in data:
print(row)

vii) Closing cursor and connection we

must close the connection established.

Syntax:

<connectionobject>.close()

con.close()

3 Python connectivity program to display entire content from a table.

import mysql.connector

mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"

, database="class12") if mycon.is_connected(): print("successfully connected")

cursor=mycon.cursor() st="select * from employee" cursor.execute(st)

data=cursor.fetchall() count=cursor.rowcount print("Number of records in the

employee table",count) print("Details of the records of the employee") for row

in data: print(row) mycon.close() else: print("connection problem")

114 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
4 Python connectivity program to display the record from a table by using a parameterised
query.

import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",

database="class12") if mycon.is_connected(): print("successfully connected")

cursor=mycon.cursor() eid=input("enter the employee id") st="select * from

employee where empid='{}'".format(eid) cursor.execute(st)

data=cursor.fetchall() print("Details of the records of the employee") for row

in data: print(row) mycon.close() else: print("connection problem")

115 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Python connectivity program to insert a new record to a table by using a parameterised
query.

import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="class12") if con.is_connected(): print("successfully connected")
cur=con.cursor() empid=int(input("enter empid:")) ename=input("enter
name:") desg=input("enter designation:")

sex=input("enter sex:") salary=float(input("enter salary:")) cur=con.cursor()

str=("insert into employee(empid,ename,desg,sex,sal)values({},'{}','{}','{}','{}')".format

(empid,ename, desg,sex,salary))

cur.execute(str) con.commit()

print("successfully inserted")

con.close() else:

print("connection problem")

116 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
6 Python connectivity program to update a record of a table by using parameterised query.
(Update salary of employees using employee id)

import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="manager",

database="class12") if con.is_connected(): print("successfully connected")

cur=con.cursor() eid=int(input("enter empid:")) salary=float(input("enter

salary:")) cur=con.cursor() str=("update employee set sal={}where

empid={}").format(salary,eid) cur.execute(str) con.commit()

print("successfully updated record") con.close() else: print("connection

problem")

117 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 Python connectivity program to delete a record from table by using parameterised query.
(Delete employee details by using employee id)

import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",database="cl

a ss12") if con.is_connected(): print("successfully connected") cur=con.cursor()

eid=int(input("enter empid:")) cur=con.cursor() str=("delete from employee where

empid={}").format(eid) cur.execute(str) con.commit() print("successfully deleted

record:") con.close() else: print("connection problem")

Questions
1 Write a python connectivity program to display only first three records from a table?

import mysql.connector

mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",

database="class12") if mycon.is_connected(): cursor=mycon.cursor()

st="select * from employee" cursor.execute(st) data=cursor.fetchmany(3)

print("Details of the records of the employee") for row in data:

print(row)

118 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
mycon.close() else:

print("connection problem")

2 Write a python connectivity program to display first record from a table?

import mysql.connector

mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager",

database="class12") if mycon.is_connected(): cursor=mycon.cursor()

st="select * from employee" cursor.execute(st) data=cursor.fetchone()

print("Details of the records of the employee") print(data) mycon.close() else:

print("connection problem")

119 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3 Write a python connectivity program to display the records of all female managers from a
table named employee and also find out the number of female managers. If the details are
not existing, then print “Record Not Found” message?

import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"
, database="class12") if mycon.is_connected(): cursor=mycon.cursor()
st="select * from employee where desg='Manager' and sex='F'"
cursor.execute(st) data=cursor.fetchall() count=cursor.rowcount if count>0:

print("Number of Female Managers:",count)

print("Details of the records of the employee")

for row in data: print(row)

mycon.close() else: print("Record not

found") else:

print("connection problem")

120 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
4 Write a python connectivity program to display the records of all managers from a table
named employee using parameterised query and also findout the number of managers. If
the details are not existing, then print “Record Not Found” message? import
mysql.connector

mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"

, database="class12") if mycon.is_connected(): cursor=mycon.cursor()

designation=input("enter the designation") st="select * from employee where

desg='{}'".format(designation) cursor.execute(st) data=cursor.fetchall()

count=cursor.rowcount if count>0:

print("Number of Managers",count)

print("Details of managers from employee table")

for row in data: print(row) mycon.close()

else: print("Record not found") else:

print("connection problem")

121 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
5 Write a python connectivity program to update salary from a table named employee .Use
parameterised query and count the number of updated record. If the details are not
existing,then print “Record Not Found” message?

import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="manager",

database="class12") if con.is_connected(): print("successfully connected")

cur=con.cursor() eid=int(input("enter empid:")) salary=float(input("enter

salary:")) cur=con.cursor() str=("update employee set sal={}where

empid={}").format(salary,eid) cur.execute(str) con.commit()

count=cur.rowcount if count>0: print("successfully updated

record:",count) con.close() else: print("Record not found") else:

print("connection problem")

6 Write a python connectivity program to delete the record from a table named employee
using parameterised query and also count the number of deleted record. If the details are
not existing,then print “Record Not Found” message?

import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",database="cl
a ss12") if con.is_connected():

122 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
cur=con.cursor() eid=int(input("enter empid:"))

cur=con.cursor() str=("delete from employee where

empid={}").format(eid) cur.execute(str) con.commit()

count=cur.rowcount if count>0: print("successfully

deleted record:",count) con.close() else:

print("Record not found") else: print("connection

problem")

CBSE TYPE QUESTIONS AND ANSWERS

123 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7 Shyam has created a table named Student in MYSQL database, SCHOOL:

• rno(Roll number )- integer


• name(Name) - string
• Per(Percentage) – float
Note the following to establish connectivity between Python and MySQL:

•Username - root • Password - manager • Host – localhost


Shyam, now wants to display the records of students whose percentage is more than
90. Help Shyam to write the program in Python import mysql.connector
mycon=mysql.connector.connect(host="localhost",user="root",passwd="manager"
, database="school") cursor=mycon.cursor() per=90

st="select * from student where per>{}".format(per)


cursor.execute(st) data=cursor.fetchall()

print("Details of the records of the employee")


for row in data: print(row) mycon.close()

124 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
8 Shyam has created a table named ‘Student’ in MYSQL database, ‘SCHOOL’:

• rno(Roll number )- integer


• name(Name) - string
• Per(Percentage) – float
Note the following to establish connectivity between Python and MySQL:

•Username - root • Password - manager • Host – localhost


Shyam, now wants to insert records of students . Help Shyam to write the program in
Python. import mysql.connector

con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="school") cur=con.cursor() rno=int(input("Enter the Roll number:"))
name=input("Enter the name") per=float(input("enter the percentage:"))
cur=con.cursor() str=("insert into student(rno,name,per)values({},'{}',
{})").format(rno,name,per) cur.execute(str) con.commit() print("successfully
inserted record:") con.close()

9 Shyam has created a table named ‘Student’ in MYSQL database, ‘SCHOOL’:

• rno(Roll number )- integer


• name(Name) - string
• Per(Percentage) – float
Note the following to establish connectivity between Python and MySQL:

•Username - root • Password - manager • Host – localhost

125 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Shyam, now wants to increase the percentage of students by 2% ,who got less than
40 percentage. Help Shyam to write the program in Python. import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="school") cur=con.cursor() per=40 cur=con.cursor()

str=("update student set per=per+2 where


per<{}").format(per) cur.execute(str) con.commit()
print("successfully updated record:") con.close()

10 Shyam has created a table named ‘Student’ in MYSQL database, ‘SCHOOL’:

• rno(Roll number )- integer


• name(Name) - string
• Per(Percentage) – float
Note the following to establish connectivity between Python and MySQL:

•Username - root • Password - manager • Host – localhost


Shyam, now wants to delete the records of students who got less than 33
percentage. Help Shyam to write the program in Python. import mysql.connector
con=mysql.connector.connect(host="localhost",user="root",password="manager",
database="school") cur=con.cursor() cur=con.cursor() per=33

str=("delete from student where


per<{}").format(per) cur.execute(str) con.commit()
print("successfully deleted record:") con.close()

126 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
**********************************************************

Sample Paper - 1
Computer Science (083)
Class : XII Maximum Marks: 70 Time Allowed: 3 hours

General Instructions:
• Please check this question paper contains 35 questions.
• The paper is divided into 4 Sections- A, B, C, D and E.
• Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
• Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
• Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
• Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
• Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
• All programming questions are to be answered using Python Language only.

SECTION A

1. State True or False 1


Python supports dynamic typing.

2. Identify the odd one from this list: 1


a) Tuple b) Dictionary c) List d) String
3. Choose the correct option. 1
d = { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
print(sorted(d))
a) { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
b) [“Amul”, “Amul”, “BR”, “Naturals”]
c) [“Amul”, “BR”, “Naturals”]
d) {“Amul”:500, “BR”:300, “Naturals”:100}

4. Evaluate the following 1


expression: 20+10* 2**2**3
a) 2580 b) 660 c) 7680 d) 540
5. If S=’computer science model examination ’, what will the following
command return?
print(S.capitalize())
a) Computer science model examination
b) Computer Science Model Examination
c) computer science model examination
d) COMPUTER SCIENCE MODEL EXAMINATION
6 Identify the function which is not a MySQL function.
a) Sum()
b) Count()
c) Max()
d) Average()

127 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
7. Choose the correct option from the following: 1
The tell() function
a) Places the file handle at the position that we specify
b) Sets the file handle at the beginning of the file
c) Returns the byte number of the position of the file handle.
d) Brings the file handle to the end of the file
8. The command used to insert a new column to an already existing table is: 1
a) Update
b) Alter
c) Insert
d) modify
9. Assuming the table emp to exist, what will the following command 1
do? Delete from emp;
a) Will delete the table emp
b) Will delete all the attributes in it
c) Will delete all the tuples in it.
d) Wrong syntax
10. Find the erroneous statement from the following: 1
Str=’Hard Work Is The Key To ess’
Succ print(Str) for I in len(str): # Statement 1
if Str[I]==’ ‘: # Statement 2
Str[I]=’ - ’ # Statement 3
# Statement 4
Str=’Good Luck’
(a) Statement 2 # Statement 5
(b) Statement 4
(c) Statement 5
(d) Statement 2 and 4

11. An Alternate key is a --------------- key, but not a Primary Key. 1


a) Candidate
b) Unique
c) Foreign
d) None of these

128 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
12. Identify the correct option(s) to open the text file in read mode. 1
i) sf =open('student.txt','w') ii) sf = open('student.txt','r')
iii) sf = open('student.txt') iv) sf = open('student.txt','rb')
a) Option i
b) both iii & iv
c) both ii and iii
d) both ii and iv

13. The wild card character ‘_’ indicates: 1


a) one character
b) Any number of characters
c) Specific number of characters mentioned
d) One column
14. Fill in the blank: 1
Protocol is used to browse the internet.

(a) VoIP (b) SMTP (c) PPP (d)HTTP


15. What will be the output of the 1
following: A=”Model Exam”
B=A
print(id(A)==id(B))
a) True
b) False
c) 0
d) 1

16. Which of the following is an optional argument of the 1


connect()function in python mysql.connector module?
a) Host
b) User
c) Password
d) database

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):- The default delimiter in CSV files is comma(,). 1
Reasoning (R):- The default delimiter of the CSV file can be overridden
129 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
with the help of the ‘delimiter’ attribute.
18. Assertion (A):- If the arguments in a function call statement match the 1
number and order of arguments as defined in the function definition, such
arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains
default argument(s) followed by positional argument(s).
SECTION B
19. (i) Expand the following terms: POP3 , URL 1+1
(ii) Give one difference between Web Server and Web Site.
OR
(i) Write down any one advantage of computer networks
(ii) Define Gateway
20. Roshan tried to define a function to input an integer and print its factors. But he 2
encountered certain syntax and logical errors in his code. Rewrite the corrected
code and underline the corrections made.
def factors():
n=input("Enter the
number") for i in range(
0,n) If
n% i = 0 :
print(i)
21. 1
Write a function countNow(STUDENT) in Python, that takes the dictionary,
STUDENT as an argument and displays the names (in uppercase) having 4
characters.
For example, Consider the following dictionary
STUDENT={1:"ARUN",2:"AVINASH",3:"PRIYA",4:"NIHA",5:"JEWEL"}
The output should be:
ARUN
NIHA
OR
Write a function, JUMBLE(STRING), that takes a string as an argument and
returns another string where uppercase letter is converted to lowercase and vice
versa.
For example, if the string is "HeLlO", then the output will be :hElLo
22. Predict the output of the Python code given below: 2
D = ["P",20,"R",10,"S",30]
T=0

A = "" B = 0 for C in
range(1,6,2):
T= T + C
A= A + D[C-1]+"$"
B = B + D[C]

130 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
23 Write the Python statement for each of the following tasks using BUILT-IN 1+1
functions/methods only:
(i) To delete last element in the list L1.
(ii) To find the length of a string named message
OR
A list named MARK stores marks obtained by a student in 5 subjects. Write the
Python command to import the required module and (using built-in function) to
display the average mark of the student.

24. Ms. Shalu has just created a table named “Staff” containing Columns Sname, 2
Department and Salary.
After creating the table, she realized that she has forgotten to add a primary key
in the table. Help her in writing an SQL command to add a primary key -
StaffId of integer type to the table Staff.
Thereafter, write the command to insert the following record in the table:
StaffId - 111
Sname- Shalu
Department: Marketing
Salary: 45000
OR
Kiran is working in a database named SCHOOL, in which he has created a table
named “STUDENT” containing columns UID, SName, Gender and Category.
After creating the table, he realized that the attribute, Category has to be deleted
from the table and a new attribute Stream of data type string has to be added.
This attribute Stream cannot be left blank. Help him to write the commands to
complete both the tasks.
25. Predict the output : 2

def Find (P, Q = 20) :


P=P+Q Q
= P - Q print
(P,"@",Q)
return P

R =380
S= 120
R=Find(R, S)
print(R,"*",S)
S=Find(S)
print(R,"*",S)
print (T,B,sep='#')
print(A)

SECTION C

26. 3
Predict the Output :

131 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Text1="ChandraYAAN-3"
Text2="" I=0 while I<len(Text1): if
Text1[I]>="0" and Text1[I]<="9":
Val = int(Text1[I])
Val = Val + 1
Text2=Text2 + str(Val) elif
Text1[I]>="A" and Text1[I] <="Z":
Text2=Text2 + (Text1[I+1]) elif
Text1[I]>="a" and Text1[I] <="z":
Text2=Text2 + Text1[I].upper() else:
Text2=Text2 + "*"
I=I+1
print (Text2)
27 Consider the given table Employee and answer the following questions

EmpID EmpName Designation Salary DoJ


E101 Sam Systems 30000 2020-09-12
Engineer
E102 Krish Technical Lead 35000 2020-03-07
E103 Mia Lead Consultant 43000 2019-02-16
E104 Isabel Manager 50000 2018-02-20
E105 Nasrin Lead Consultant 50000 2018-10-04
E106 Ayan Systems 32000 2021-01-15
Engineer
E107 Sen Manager 55000 2017-11-25

Write the output of the queries based on Employee table


(i) select EmpName, Designation from Employee where EmpName like '___';

(ii) select distinct Designation from Employee;

(iii)select EmpID,EmpName, Designation from Employee where Designation


in ('Technical Lead', 'Lead Consultant’);
28. Write a Python function ReversWords() to read the text file 3
“Python.txt” and display the words starting with ‘P’ or ‘p’ in
reverse order and all other words as such.
Eg:If the file contains the following text:
Python is a popular programming
language. Then it is to be displayed as->
nohtyP is a ralupop gnimmargorp
language.

132 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
OR
Write a function AMCount() to display the no.of occurrences of
‘A’ and ‘M’ ( ‘a’ and ‘m' also)separately of a text file
STORY.TXT.

29. Consider the table EMPLOYEES shown below and write SQL 3
commands for (i) to (iii)

EM NAME DESIGN SALA BEN ADDRESS CITY


PID ATION RY EFI
TS
200 Akash Manager 15000 2000 Christ Nagar Jaipur
201 Ajit Manager 12000 1500 Delhi Road Agra
202 Ramesh Salesman 8000 800 Bandra Mumbai
203 Deepak Clerk 5000 500 Holy Palace Mumbai
204 Aman Officer 10000 1000 Badarwa Haryana
(i) To display Name , Designation and Address of all employees
whose name starts with character ‘A’
(ii) To display the NAME,DESIGNATION,ADDRESS and TOTAL
SALARY of all employees where TOTAL SALARY is calculated
as SALARY + BENEFIITS
(iii) To display the number of employees designation wise

30. Write Addnew(Book) and Remove(Book) functions in python to add a new 3


book and remove a book from a List of books, considering them to act as
PUSH and POP operations of the data structure Stack.

SECTION D
Consider the following tables DOCTOR and SALARY. Write SQL commands 4
31 for the following statements.
TABLE : DOCTOR

ID NAME DEPT SE EXPERIENC X E


101 JOHN ENT M 12
104 SMITH ORTHOPEDI M 6
C
107 F GEORGE CARDIOLOG M 11
Y
114 LARA DUTT SKIN F 10

109 K MEDICINE F 4
GEORGY
105 JOHNSON ORTHOPEDI M 7
C
117 LUCY ENT F 8

133 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
111 BILL G MEDICINE F 15

130 MORPHY ORTHOPEDI M 16


C
TABLE : SALARY

ID BASI ALLOWANC CONSULTATIO


C E N
101 12000 1000 300
104 24000 2300 500
107 32000 3200 500
114 12000 1000 600
109 41000 1700 100
105 27100 1100 200
117 11000 1200 300
111 18900 1600 200
130 42000 2600 300
(i) Display NAME of all doctors who are in “ORTHOPEDIC”
having more than 10 years’ experience from the table
DOCTOR.
(ii) Display the average salary of all doctors working in “ENT”
department using the DOCTOR and SALARY. (Salary=
Basic + Allowance)
(iii) Display the minimum ALLOWANCE of female doctors.
(iv) Display the highest consultation fee amount for all male
doctors.
32 Write a Program in Python that defines and calls the following user defined 4
functions:
a) 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.
b) search()- To display the records of the furniture whose price is more
than 10000.

33 SAP Methodologies is planning to expand their network in India starting with


three cities in India to build infrastructure for research and development of
their chemical products. The company has planned to setup their main office
in Chennai at three different locations and have named their offices as
Production Unit, Finance Unit and Media Unit. The company has one more
research office namely Corporate Unit in Mumbai. A rough layout of the
same is as follows:

134 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
Approximate distance between these units is as follows:

PRODUCTION FINANCE 70M


UNIT UNIT
PRODUCTION MEDIA UNIT 15kM
UNIT
PRODUCTION CORPORATE 2112 Km
UNIT UNIT
FINANCE UNIT MEDIA UNIT 15Km

WIN NO.COMPUTERS
G
PRODUCTION UNIT 15
0
FINANCE UNIT 35
MEDIA UNIT 10
CORPORATE UNIT 30
Suggest the kind of network required (out of LAN, MAN, WAN) for each of
the following units:
(a) Production Unit and Media Unit
(b) Production Unit and Finance Unit
(ii) Name the device you suggest for connecting all computers within each
unit?
(iii) Which of the following communication media, will you suggest to be
procured by the company for connecting their local office units in Chennai
for very effective (high speed) communication?
(a) Telephone cable
(b) Optical fiber
(c) Ethernet cable
(iv) Among the different units in Chennai, which unit can be made the
Server. Justify your reason.
(v) Suggest a cable/wiring layout for connecting the company’s local
office units located in Chennai.

135 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
34 i)Differentiate between binary file and csv file: 2+3
ii)Raghav is a Python programmer , created a binary file record.dat with
employee id, 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.

OR
i)Differentiate between seek( ) and tell( ) functions
ii)Anushka wants to increase the price by 10% for those items which are less
than 250. The details of the items (itemno, iname and price) are stored in a
file named ‘items.dat’. She wants to store the modified data in another file
named
items_copy.dat. Anushka has written a function named Price_Change() . Help
Anushka to accomplish the task

136 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
35 Define the term Domain with respect to RDBMS. Give one example to
support your answer.
Sunil wants to write a program in Python to read a record from the table
named student and displays only those records who have marks between 80
and 95: 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 vidyalaya.

OR
i)Define Candidate Key ii)Write a program to insert the following
record in the table Student: RollNo – integer
Name – string
Class – integer
Marks – integer
Note the following to establish connectivity between Python and MYSQL:
Username is root
Password is abcd
The table exists in a MYSQL database named XIICS.
The details (RollNo, Name, Class and Marks) are to be accepted from the
user.

Sample Paper 1 – Marking Scheme


Computer Science (083)

Class : XII
SECTION A
1. State True or False 1
Python supports dynamic typing
Ans: True
2. Identify the odd one from this list: 1
a)Tuple b) Dictionary c) List d)
String

137 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
3. Choose the correct option. 1
d = { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
print(sorted(d))
a) { “Naturals”:100 , “Amul” : 200, “BR”: 300 , “Amul” : 500 }
b) [“Amul”, “Amul”, “BR”, “Naturals”]
c) [“Amul”, “BR”, “Naturals”]
d) {“Amul”:500, “BR”:300, “Naturals”:100}

4. Evaluate the following 1


expression: 20+10* 2**2**3
a) 2580 b) 660 c) 7680 d) 540
5. If S=’computer science model examination ’, what will the following 1
command return?
print(S.capitalize())
a) Computer science model examination
b) Computer Science Model Examination
c) computer science model examination
d) COMPUTER SCIENCE MODEL EXAMINATION
6. Identify the function which is not a MySQL function. 1
a) Sum()
b) Count()
c) Max()
d) Average()
7. Choose the correct option from the following: 1
The tell() function
……………………………….
a) Places the file handle at the position that we specify.
b) Sets the file handle at the beginning of the file.
c) Returns the byte number of the position of the file handle.
d) Brings the file handle to the end of the file.
8. The command used to insert a new column to 1
an already existing table is:
a) Update
b) Alter
c) Insert
d) modify

9. Assuming the table ‘emp’ to exist, what will 1


the following command do? Delete from emp;

a) Will delete the table emp


b) Will delete all the attributes in it
c) Will delete all the tuples in it.
d) Wrong syntax

138 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
10. Find the erroneous statement from the 1
following:

Str=’Hard Work Is The Key To Success’


print(Str) # Statement 1 for I in len(str):
# Statement 2 if Str[I]= =’ ‘: #
Statement 3
Str[I]=’ - ’ # Statement 4 Str=’Good
Luck’ # Statement 5
(a) Statement 2
(b) Statement 4
(c) Statement 3 and 5
(d) Statement 2 and 4
11. An Alternate key is a key, but not a 1
Primary Key.
a) Candidate
b) Unique
c) Foreign None of these

12. Identify the correct option(s) to open the text 1


file in read mode. (Assume the file already
exists)
i) sf =open('student.txt','w')
ii) sf = open('student.txt','r')
iii) sf = open('student.txt') iv)
sf = open('student.txt','rb') a)
Option i
b) both iii & iv
c) both ii and iii
d) both ii and iv
13. The wild card character ‘_’ indicates: 1
a) one character
b) Any number of characters
c) Specific number of characters mentioned
d) One column
14. Fill in the blank: 1
protocol is used to browse the internet.
(a) VoIP (b) SMTP (c) PPP (d)HTTP

15. What will be the output of the following: 1


A=”Model Exam”
B=A
print(id(A)==id(B))
a) True
b) False
c) 0

139 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
d) 1
16. Which of the following is an optional argument 1
of the connect() function in python
mysql.connector module?
a) Host
b) User
c) Password
d) database
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):- The default delimiter in CSV files is comma(,). 1
Reasoning (R):- The default delimiter of the CSV file can be overridden
Ans with the help of the ‘sep’ attribute.
(a) Both A and R are true and R is the correct explanation for A
18. Assertion (A):- If the arguments in a function call statement match the 1
number and order of arguments as defined in the function definition, such
arguments are called positional arguments.
Reasoning (R):- During a function call, the argument list first contains
Ans default argument(s) followed by positional argument(s).
(c) A is True but R is False

SECTION B
19. (i) Expand the following terms: HTTP , URL 1+1
HTTP – Hyper Text Transfer Protocol
URL – Uniform Resource Locator

(ii) A web server is a computer system that stores and delivers web pages
to users when they request them.
A website is a collection of web pages, images, videos, and other digital assets
that are hosted on a web server.
Or
i)Write down any one advantage of computer networks
File Sharing / Resource Sharing
ii)Define Gateway
A gateway is a device which connects dissimilar networks

140 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
20 Roshan tried to define a function to input an integer and print its factors. But 2
he encountered certain syntax and logical errors in his code. Rewrite the
corrected code and underline the corrections made.
def factors():
n=input("Enter the
number") for i in range(
0,n)
If n% i = 0
: print(i)
Ans:
def factors():
n=int(input("Enter the
number")) for i in range( 1,n+1):
if n% i = = 0
: print(i)
21 def countNow(STUDENT) : for
name in STUDENT.values():
if len(name)= =4:
print(name)

STUDENT={1:"ARUN",2:"AVINASH",3:"PRIYA",4:"NIHA",5:"JEW
EL"} countNow(STUDENT)
or def
Jumble(str):
n=len(str) str2=""
for i in range(0,n):
if str[i].isupper():
str2=str2+str[i].lower()
elif str[i].islower():

str2=str2+str[i].upper()
else: str2=str2+str[i]
return str2

22 9#60 2
P$R$S$
( 1 mark for each correct line with the appropriate symbol)

23 (i) To delete last element in the list L1. 2


S=L1.pop()
(ii) To find the length of a string named message
n=len(message) or
import statistics
print(statistics.mean(MARK))

141 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
24 ALTER TABLE Staff ADD StaffId INT PRIMARY KEY; 2
INSERT INTO Staff VALUES("Shalu","Marketing",45000,111); Or
To delete the attribute, category:
ALTER TABLE STUDENT DROP category;
To add the attribute, Stream
ALTER TABLE Sports ADD stream varchar(10) NOT
NULL ;

25 500 @ 380 2
500 * 120
140 @ 120
500 * 140

26 hHANDRAAAN-*4 3

27 3
(i) select EmpName, Designation from Employee where EmpName
like '_
_ _';

EmpName Designation
Sam Systems Engineer
Mia Lead Consultant
Sen Manager

(i) select distinct Designation from Employee;

distinct Designation
Systems Engineer
Technical Lead
Lead Consultant
Manager

(iii)select EmpID,EmpName, Designation from Employee


Designation in ('Technical Lead', 'Lead Consultant’);

EmpID EmpName Designation


E102 Krish Technical Lead
E103 Mia Lead Consultant
E105 Nasrin Lead Consultant where
28 def ReversWords(): 3
with open("Python.txt")
as f: ch=f.read()
l=ch.split(
) for i in l:
if i[0] in "Pp": print(i[::-
1],end='
142 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
')
else:

print(i,end=' ')
f.close()
or def
CountAM():
with open("Story.txt") as f:
A=M=0
s=f.read()
for ch in
s:
if ch in "Aa":
A+=1 elif ch
in "Mm":
M+=1
f.close()
print("No.of A and M is", A ," & ", M)

29 (i) To display Name , Designation and Address of all employees 3


whose name starts with character ‘A’
select name,designation,address from employees where name like
'A%';
(ii) To display the NAME,DESIGNATION,ADDRESS and
TOTAL SALARY of all employees where TOTAL SALARY is
calculated as SALARY + BENEFIITS
select name,designation,address,salary+benifits as 'total salary'
from employees;
(iii) To display the number of employees designation wise select
designation,count(*) from employees group by designation
30 Ans. Book=[ ] 3
def Addnew(s):
name=input(“Enter book
name:”)
Book.append(name)
def Remove(Book):
if( Book==[ ]):
print(“Stack Empty.
Underflow”) else:
print(“Deleted book is :”, Book.pop())

31 4
(i) SELECT NAME FROM DOCTOR WHERE
DEPT=”ORTHOPEDIC” AND EXPERIENCE>10;
(ii) SELECT AVG(BASIC + ALLOWANCE) FROM DOCTOR,
SALARY WHERE DOCTOR.ID=SALARY.ID AND
DEPT=”ENT”;
(iii) SELECT MIN(ALLOWANCE) FROM DOCTOR, SALARY
143 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
WHERE DOCTOR.ID=SALARY.ID AND SEX=”F”;
(iv) SELECT MAX(CONSULTATION) FROM DOCTOR,
SALARY WHERE DOCTOR.ID=SALARY.ID AND SEX=”M”;

32 import csv def add():


fout=open("furdata.csv","a",newline='\n')
wr=csv.writer(fout) fid=int(input("Enter
Furniture Id :: ")) fname=input("Enter
Furniture name :: ")
fprice=int(input("Enter price :: "))
FD=[fid,fname,fprice]
wr.writerow(FD)
fout.close()

def search():
fin=open("furdata.csv","r",newline='\n')
data=csv.reader(fin) found=False
print("The Details are") for i in data:
if int(i[2])>10000:
found=True
print(i[0],i[1],i[2]) if
found==False:
print("Record not found")
fin.close()
add()
print("Now displaying")
search()

33 i) a) MAN
b) LAN
ii) Switch/hub iii) Optical Fibre iv) Production Unit- It
contains the maximum no.of computers Star Topology

34 a)Ans : 2+3
Binary file:
• Extension is .dat
• Not human readable
• Stores data in the form of 0s and 1s
CSV file
∙ Extension is .csv
∙ Human readable
∙ Stores data like a text file Program
b)def update_data():
rec={}
fin=open("record.dat","rb")

144 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
fout=open("temp.dat",”wb”)
found=False eid=int(input("Enter employee id to update
their salary :: ")) while True: try:

rec= pickle.load(fin)
if rec["Employee id"]==eid:
found=True
rec["Salary"]=int(input("Enter new salary :: "))
pickle. dump(rec,fout)
else: pickle.dump(rec,fout)
except: break if found==True: print("The
salary of employee id ",eid," has been updated.") else:
print("No employee with such id is not
found") fin.close() fout.close() or
i)Differentiate between seek( ) and tell( ) functions

Ans : The tell function is used to determine the current position of the file
pointer, and the seek function is used to move the file pointer to the specified
position of the file
ii)Anushka wants to increase the price by 10% for those items which
are less than 250. The details of the items (itemno, iname and price) are stored
in a file named ‘items.dat’. She wants to store the modified data in another file
named items_copy.dat. Anushka has written a function named Price_Change()
. Help Anushka to accomplish the task

import pickle def


Price_Change():
f1=open(“items.dat”,’rb’)
f2=open("items_copy.dat","wb")
l=pickle.load(f1)
for i in l:
if i[2]<250:
i[2]=i[2]+i[2]*10/100
pickle.dump(I,f2)
f2.close()
f2=open("items_copy.dat","rb")
l=pickle.load(f2)
print(l)
f1.
close()
f2.close()

145 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
35 i)In relational database terminology, a domain defines the permitted range
of values for an attribute of an entity
ii) import mysql.connector as mysql def sql_data():
con=mysql.connect(host="localhost",user="root",password="tiger",
database="vidyalaya") mycursor= con.cursor()
print("Students with marks between 80 and 95 are : ")
mycursor.execute("select * from vidyalaya where Marks between 80 and
95")
data=
mycursor.fetchall() for i
in data: print(i) or

con1=mysql.connect(host="localhost",user="root", passwd="abcd",
database="XIICS")
mycursor= con1.cursor()
rno=int(input("Enter Roll Number :: "))
name=input("Enter name :: ")
class=int(input("Enter class :: "))
marks=int(input("Enter Marks :: "))
s="insert into student values ({},'{}',{},
{})".format(rno,name,class,marks) mycursor.execute(s) con1.commit()
print("Data Added successfully")

146 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
147 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
KENDRIYA VIDYALAYA SANGATHAN: ERNAKULAM REGION
SAMPLE QUESTION PAPER - 2
COMPUTER SCIENCE (083)
Maximum Marks: 70 Time Allowed: 3 hours
General Instructions:
1. This question paper contains five sections, Section A to E.
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 02 Long Answer type questions carrying 04 marks each.
7. Section E has 03 questions carrying 05 marks each.
8. All programming questions are to be answered using Python Language only.

SECTION A
1. State True or False 1
A variable in python is defined only when some value is assigned to it.
2. …………………..command is used to remove primary key from the table in SQL.
a) delete b)remove c) alter d)drop
3. What will the following expression be evaluated to in Python? 1
print(25 // 4 + 3**1**2 * 2)
a) 24 b) 18 c) 6 d) 12
4. What will be the output of the following Python 1
code? string = "my name is x" for i in string.split():
print (i, end=", ")
a)m, y, , n, a, m, e, , i, s, , x, b)m, y , n, a, m, e , i, s , x,
c)my, name, is, x, d)error
5. Suppose a dictionary D is declared as D={1:"John",2:"Dev",3:"Bob"} 1
which of the following is incorrect? State the reason.
(a) print(D[3]) (b) D[[1,2,3]] = “Python”
(c) D[‘Bob’]=3 (d) print(D[3][1])
6. Observe the following table: 1

What is the degree and cardinality of


the above table?
a)4 and 5 b)5 and 4 c)4 and 6 d) 6 and 4
7. Fill in the blank: 1
…………….. protocol is used to transmit an electronic mail over the internet.

148 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
a)FTP b)SMTP c)VOIP d)HTTP
8. Consider the statements given below and then choose the correct output from the 1
given options:
example="snow world" print(example[-2:1:-3])
a)lo b)lwn c)lwo d)lwn

9. Which of the following statement will return an error? T1 is a tuple 1


a)T1=T1+(23) b)T1=T1+[23] c)Both a and b d)None of the options
10 What possible outputs(s) are expected to be displayed on screen at the time of 1
. execution of the program from the following code?

import random
val=[20,30,40,50,60,70]; Low
=random.randint(2,4) High
=random.randint(3,5) for i in
range(Low, High +1): print
(val[i],end="#")

a) 20#30#40# b) 30#40#50# c) 50#60#70# d)60#70#


11. Which one of the following switches uses store and forward transmission? 1
a) Packet switching b)Circuit switching c)Both a and b d)None of the above
12 Which of the following function headers is correct? 1
.
a) def fun(a = 2, b = 3, c) b) def fun(a = 2, b, c = 3)
c) def fun(a , b =2, c=3) d) def fun(a, b, c = 3,d)
13 What will be the output of the following Python code? 1
. def foo():
try:
print(1)
finally:
print(2)
foo()
a) 1 b) 1 c) 2 d) none of the mentioned
2
14 Which of the following is not an integrity constraint? 1
. a)Not null b) Composite key c) Primary key d) Check
15 A device that forwards data packet from one network to another is called 1
. a……………

a) Bridge b) Router c) Hub d)


Gateway

149 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
16 f = open("test.txt", "w+") 1
. L = ["First Line\n", "Second Line\n", "Third Line"]
f.writelines(L)
f.flush()
f.seek(0)
O = f.readlines()
print(len(O))
a) 33 b) 31 c) 28 d) 3
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): The pop() method can be used to delete elements from a dictionary. 1
. Reason(R): The pop() method deletes the key-value pair and returns the value of deleted
element
18 Assertion (A): Leading whitespace at the beginning of a statement in Python is called 1
. indentation.
Reason (R): In Python, the same level of indentation associates statements into a different
blocks of code.
SECTION B
19 (i) Expand the following terms: 1+1
. (a)NIC (b)SIM (2)
(ii)What is HTML? Where it is used?
OR
(i) Define the term bandwidth. Give any one unit of bandwidth.
(ii) Give one difference between FTP and HTTP.
20 Observe the following code carefully and rewrite it after rmoving all syntax and logical 2
. errors. Underline each correction done in the code.
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()

150 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
21 Write a function frequencyCount( ), which takes the list ( Marks) and empty dictionary 2
. (dict) as arguments. Update the dictionary, each marks as key and frequency of its
occurrence as value and return the dictionary .
Consider the following list Marks=[4,5,6,5,10,6,5,5,40,30,2,4] and dict
The function will return {4: 2, 5: 4, 6: 2, 10: 1, 40: 1, 30: 1, 2: 1}
OR
Write a function LeftShift(lst,x) in python which accepts number in a list (lst) and all the
elements of the list should be shifted to left according to the value of x entered by the
user.
Sample list lst=[20,40,60,30,10,50,90,80,45,29] value of x is 3
Then lst will be [30,10,50,90,80,45,29 20,40,60]
22 Predict the output of the following Python code: 2
. Predict the output of the following Python code: tup1 =
("George","Anderson","Mike","Luke","Amanda")
list1 =list(tup1) list2
= [] for i in list1:
if i[-1]=="e":
list2.append(i) tup2
= tuple(list2)
print(tup2)
23 Write the python statement for each of the following tasks using BUILT-IN 2
. functions/methods only
Consider the list L=[15,25,35,45,65,75,85]

i) Insert value 55 between 45 and 65


ii)Remove all the elements from list
OR
i)To add all the elements in L
ii)physically remove the list L
24 Differentiate between COUNT(*) and SUM( ) functions in SQL with appropriate 2
. example.
(OR)
What do you understand by Candidate keys in a table? Give a suitable example of
candidate keys from a table containing some meaningful data.
25 Predict the output of the following Python code: 2
. def
Bigger(N1,N2): if
N1>N2: return
N1 else:
return N2

L=[32,10,21,54,43]

151 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
for c in range (4,0,-1):
a=L[c] b=L[c-
1]
print(Bigger(a,b),'@', end=' ')
SECTION C

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


. st = "python programming"
count = 4 while
True: if st[0]==
"p": st =
st[2:] elif st[-
2]=="n":
st = st[:4]
else:
count+=1
break print(st)
print(count)
27 Consider the table EMPLOYEE given below and write the output of the SQL queries 3
. that follow

EmpI Gende
Name DoJ City Salary
d r
Londo
101 Leonard 1995-06-06 M 9500
n
102 Priya 1993-05-07 F Delhi 4500
103 Howard 1994-05-06 M Paris 8500
Londo
104 Penny 1995-08-08 F 11000
n
Londo
105 Raj 1995-10-08 M 10000
n

106 Amy 1994-12-12 F Paris 8500


107 Bernadette 1995-12-08 F Lyon 8000
108 Sheldon 1995-06-12 M Seattle 15000
i)SELECT COUNT(*), City FROM EMPLOYEE GROUP BY City HAVING COUNT(*)
> 1;
ii)SELECT MIN(DoJ) FROM EMPLOYEE WHERE GENDER = ‘M’;
iii)SELECT AVG(Salary) from EMPLOYEE WHERE Name LIKE “%o%;

152 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
28 Write a function countline() in python to count the number lines in a text 3
. file ‘Country.txt’, which is starting with an alphabet ‘W’ or ‘H’. If the file
contents are as follows:

Whose woods these are I think I know.


His house is in the village though;
He will not see me stopping here
To watch his woods fill up with snow.

The output of the function should be:


W or w : 1
H or h : 2
(OR)
Write a user defined function countwords( ) to display the total number of words present
in the text file “Quotes.Txt”. If the text file has the following data written in it:

Living a life you can be proud of doing your best


Spending your time with people and activities that are important to you Standing up
for things that are right even when it’s hard Becoming the best version of you

The countwords() function should display the output as:


Total number of words : 40
29 Consider the table MobileMaster 3
. Table: MobileMaster
M_Id M_Company M_Name M_Price M_Mf_Date
MB001 Samsung Galaxy 13000 2014-02-12
MB002 Nokia N1100 7500 2011-04-15
MB003 Realme C35 12000 2021-11-20
MB004 Oppo SelfieEx 12500 2015-08-21
Based on the given table, write SQL queries for the
following: i) Reduce the Mobile Price of all mobiles by 10%
ii) Delete the mobiles with Price less than 12000
iii)Display Mobile company name and Model name separated by comma. in a new
column name ’company&brand’ and price ,in the ascending order of the Price
30 Vedika has created a dictionary containing names and marks as key-value pairs of 5 3
. students. Write a program, with separate user-defined functions to perform the following
operations:
i)Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 70. ii)Pop and display the content of the
stack.

153 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
The dictionary should be as follows: d={“Ramesh”:58, “Umesh”:78,
“Vishal”:90, “Khushi”:60, “Ishika”:95} Then the output will be:
Umesh Vishal Ishika
SECTION D
31 a) Consider the table VEHICLE and TRAVEL given below: 4
. Table: TRAVEL
CNO CNAME TRAVELDATE KM VCODE NOP

101 Arun 2015-12-13 200 V01 32


102 Balaji 2016-06-21 120 V03 45
103 Vignesh 2016-04-23 450 V02 42
104 Selva 2016-01-13 80 V02 40
105 Anupam 2015-02-10 65 V04 2
106 Tarun 2016-04-06 90 V05 4

Table: VEHICLE
VCODE VEHICLETYPE PERKM
V01 VOLVO BUS 150
V02 AC DELUXE BUS 125
V03 ORDINARY BUS 80
V04 CAR 18
V05 SUV 30

• PERKM is Freight Charges per kilometre.


• Km is kilometres Travelled.
• NOP is number of passengers travelling in vehicle.
i)Write the command to view the structure of the table TRAVEL.
ii)Display candidate name and Vehicle Type for each candidate.
iii)Display Customer Name and kilometres Travelled in descending order of
kilometres Travelled. iv) Display the number of customers in each vehicle Type(ie
VCODE)
32 Genesis Infotech plans to develop a computerized system for payroll processing of all its 4
. employees for storing salary details, which stores data in “employee.csv”. The structure
of the file is
[EMPNO,EMPNAME,SALARY] Where
EMPNO is employee No (integer),EMPNAME employee Name(string),SALARY as
salary(integer)
Genesis want develop the following user defined functions:
AddEmp() -To accept a record from user and add to the file
ShowEmp() -Display the details of employees with column headings also display the
number of employees who are drawing a salary of more than Rs 5000 per month.

154 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
SECTION E
33 Oasis Public School, Coimbatore is setting up the network between its different wings of 5
. school campus. There are 4 wings namely SENIOR(S), JUNIOR (J), ADMIN (A) and

HOSTEL (H).

Distances betweenwings are given below:


various
Wing A to Wing S 100m
Wing A to Wing J 200m
Wing A to Wing H 400m
Wing S to Wing J 300m
Wing S to Wing H 100m
Wing J to Wing H 450m t various wings are as
Number of Computers alled afollows:
inst
Wings Number of Computers
Wing A 20
Wing S 150
Wing J 50
Wing H 25
i)Suggest the best-wired medium and mention the topology or layout to connect various 1
wings of Oasis Public School, Coimbatore.
ii)Name the most suitable wing to house the server. Justify your answer. 1
iii)Suggest placement of HUB/SWITCH in the network of the School. 1
iv)Suggest a device that can provide wireless Internet access to all smartphone /laptop 1
users in the campus of Oasis Public School, Coimbatore.
v)Suggest a protocol that shall be needed to provide file transfer within the School 1

155 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
34 i)What is the difference between “w” and “a” modes in python? 2+3
. ii) Consider a file, University.dat, containing records of the following structure: (5)
[Universityname ,collegename, noofstaff]
Write a function CopyCollege(), that reads contents from the file University.dat and copies
the records with University name as Calicut to the file name Calicut.DAT. The function
should return the total number of records copied to the file Calicut.DAT.
OR
i)What is the difference between readline() and readlines() functions? ii)Write a menu
driven program InsertRec() and Searchroll() for adding and searching for a particular roll
number using dictionary on student binary file “student.DAT”. Structure of dictionary is
{Rollno:rollno,”Name”:name,”Marks”:marks}
35 i) Define the term Domain with respect to RDBMS. Give one example to support your 5
. answer
ii) Swaraj wants to write a program in Python to insert the following record in the table
named ‘Employee’ in MYSQL database, COMPANY:
• EID(Employee ID )- integer
• name(Name) - string
• DOB (Date of birth) – Date
• Salary – float
Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password - tiger
• Host - localhost
The values of fields EID, name, DOB and Salary has to be accepted from the user. Help
Swaraj to write the program in Python.

OR
i)what is the difference between primary key and foreign key?
ii) Nayana has created a table named ‘Employee’ in MYSQL database, COMPANY:
• EID(Employee ID )- integer
• name(Name) - string
• DOB (Date of birth) – Date
• Salary – float
Note the following to establish connectivity between Python and MySQL:
• Username - root
• Password - tiger
• Host - localhost
Nayana , now wants to display the records of employees whose salary is more than 25000.
Help Nayana to write the program in python

156 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS
157 |KVSEKM,PART–ASTUDENTSUPPORTMATERIAL,XIICS

You might also like