0% found this document useful (0 votes)
89 views194 pages

Quik RevisionCS Class12

Uploaded by

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

Quik RevisionCS Class12

Uploaded by

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

ARMY PUBLIC SCHOOL

MAMUN
SUBJECT-COMPUTER SCIENCE
SESSION 2024-25

CS REVISION NOTES

1
INDEX OF CONTENTS
SNO TOPIC PAGES
1 Syllabus & Marks Distibutions 4-5
2 Revision of Python topics covered in Class XI 5-23

Functions: types of function (built-in functions, functions defined in module, user defined 24-36
3 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 - Handling Exceptions Using Try-Except Blocks 37-38
4
5 Data Files : Introduction to files, types of files (Text file, Binary file, CSV file), relative 39-47
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, 48-57
6 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 58-60
7
writer(),writerow(),writerows() and read from
a csv file using reader()
8 Data Structure: Stack, operations on stack (push & pop), implementation of stack using 61-61
list.

9 Computer Networks and its terminologies, Important Questions and worksheets 62 - 97


10. 98 - 124
Database Management System (DBMS) & MySQL with Questions/Answers

INTERFACE PYTHON WITH SQL DATABASE 125- 135


11

12 SOLVED SAMPLE PAPER -1 (Question Paper) 136 - 146

13 SOLVED SAMPLE PAPER -1 (Answer & Marking Scheme) 147 – 157

UNSOLVED SAMPLE PAPERS - (Set - 1) / (Set- 2) / Set – 3) 158 - 195


14

2
Computer Science (2024-25)
CLASS XII Code No. 083
Unit wise Syllabus
Unit 1: 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 2: 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 3: 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
3
PYTHON REVISION TOUR
ABOUT PYTHON:
1. Python is a high-level programming language developed by Guido Van Rossum. The language was
released in February 1991 and got its name from a BBC comedy series “Monty Python’s Flying
Circus”.
2. It is an interpreted and platform independent language i.e. the same code can run on any operating
system.
3. It can be used to follow both procedural and object-oriented approaches to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.
BASIC TERMS USED IN PYTHON:
1. Token / Lexical Unit: The smallest individual unit in a python program is known as Token or Lexical
Unit. A token has a specific meaning for a python interpreter. Examples of tokens are: Keywords,
Identifiers, Literals, Operators and Punctuators.

4
2. Keywords: Keywords are the reserved words and have special meaning for Python Interpreters.
Each keyword can be used only for that purpose which it has been assigned. Examples: and, while, del,
with, True, None, False, return, try etc.
3. Identifiers: These are the names given to variables, objects, classes or functions etc. there are some
predefined rules for forming identifiers which should be followed else the program will raise Syntax
Error.
4. Literals: The data items that have a fixed value are called Literals. If a data item holds numeric
values it will be known as Numeric Literal, if it contains String values it will be known as String Literal
and so on. It means the type of value stored by the data item will decide the type of Literal. Python has
one special literal which is None to indicate absence of value.
5. Operators: These are the symbols that perform specific operations on some variables. Operators
operate on operands. Some operators require two operands and some require only one operand to
operate. The operator precedence in Python is as follows:

NOTE: When we compare two variables pointing to same value, then both Equality (==) and identity
(is) will return True. But when same value is assigned to different objects, then == operator will return
True and is operator will return False.
6. Punctuators: These are the symbols that are used to organize sentence structure in programming
languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () , .
7. Variables: In Python, variables are not storage containers like other programming languages. These
are the temporary memory locations used to store values which will be used in the program further.
Each time we assign a new value to a variable it will point to a new memory location where the
assigned value is stored. In Python we do not specify the size and type of variable, besides these are
decided as per the value we assign to that variable.
8. Data Type: It specifies the type of data we will store in the variable according to which memory will
be allocated to that variable and it will also specify the type of operations that can be performed on
that variable. Examples: integer, string, float, list etc.

5
9. Dynamic Typing: It means that it will be decided at the run time that which type of value the
variable will store. It is also called implicit conversion. For example,

Here, we need not to specify the type of value a will store besides we can assign any type of value to a
directly. Similarly, the data type of c will be decided at run time on the basis of value of a and b.
10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly by using
some built-in functions. Here, we can say that we force the variable by applying a built-in function to
change the data type and it is not done at run time. Some common type casting functions are int(),
float(), str(), list(), tuple(), dict() etc.

DATA TYPES IN PYTHON:


Data types are classified in two basic categories: Mutable data types and Immutable data types.
Mutable data types are those data types whose value can be changed without creating a new object. It
means mutable data types hold a specific memory location and changes are made directly to that
memory location. Immutable data types are those data types whose value cannot be changed after
they are created. It means that if we make any change in the immutable data object then it will be
assigned a new memory location.
1. In Numeric data types, Integers allow storing whole numbers only which can be positive or negative.
Floating point numbers are used for storing numbers having fractional parts like temperature, area etc.
In Python, Floating point numbers represent double precision i.e. 15-digit precision. Complex numbers
are stored in python in the form of A + Bj where A is the real part and B is the imaginary part of
complex numbers.

6
2. Dictionary is an unordered set of commas separated values where each value is a key: value pair.
We represent the dictionary using curly brackets {}. Keys in the dictionary should be unique and they
cannot be changed while values of the keys can be changed.
3. Boolean allows storing only two values True and False where True means 1 and False means 0
internally.
4. Sequence data types store a collection or set of values in an ordered manner. We can traverse the
values/elements using indexing.
The sequence data types are:

A. STRING:
Introduction: String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be created by enclosing
one or more characters in single, double or triple quote.
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"

>>> str3 = """Hello World!"""


Indexing: Each individual character in a string can be accessed using a technique called indexing. The
index specifies the character to be accessed in the string and is written in square brackets ([ ]). The
index of the first character (from left) in the string is 0 and the last character is n-1 where n is the
length of the string.

String operations:
(i) Concatenation: To concatenate means to join. Python allows us to join two strings using
concatenation operator plus which is denoted by symbol +.
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string

>>> str1 + str2 #Concatenated strings


'HelloWorld!'
(ii) Repetition: Python allows us to repeat the given string using repetition operator, which is denoted
by symbol *.
>>> str1 = 'Hello' #assign string 'Hello' to str1
>>> str1 * 2 #repeat the value of str1 2 times
'HelloHello'

7
(iii) Membership: Python has two membership operators 'in' and 'not in'. The 'in' operator takes two
strings and returns True if the first string appears as a substring in the second string, otherwise it
returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' not in str1
False
(iv) Slicing: In Python, to access some part of a string or substring, we use a method called slicing. This
can be done by specifying an index range. Given a string str1, the slice operation str1[n:m] returns the
part of the string str1 starting from index n (inclusive) and ending at m (exclusive). In other words, we
can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1]. The numbers of
characters in the substring will always be equal to difference of two indices m and n,
i.e., (m-n).

>>> str1 = 'Hello World!'


>>> str1[1:5] #gives substring starting from index 1 to 4
'ello'
>>> str1[7:10] #gives substring starting from 7 to 9
'orl'
>>> str1[3:20] #index that is too big is truncated down to the end of the string
'lo World!'
>>> str1[7:2] #first index > second index results in an empty '' string
(v) Traversing a string using loops: We can access each character of a string or traverse a string using
for loop and while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch)
H
e
l
l
o

W
o
r
l
d
!

In the above code, the loop starts from the first character of the string str1 and automatically ends
when the last character is accessed.
(B) String Traversal Using while Loop:

8
>>> str1 = 'Hello World!'
>>> index = 0 #len(): a function to get length of string
>>> while index < len(str1):
print(str1[index], end = '')
index += 1

Hello World! #output of while loop


Here while loop runs till the condition index < len(str) is True, where index varies from 0 to len(str1) -1.
(vi) built-in functions:
i. len() : Returns the length of the given string.
>>> str1 = 'Hello World!'
>>> len(str1)
12
ii. title(): Returns the string with first letter of every word in the string in uppercase and rest in
lowercase.
>>> str1 = 'hello WORLD!'
>>> str1.title()
'Hello World!'
iii. lower(): Returns the string with all uppercase letters converted to lowercase
>>> str1 = 'hello WORLD!'
>>> str1.lower()
'hello world!'
iv. upper(): Returns the string with all lowercase letters converted to uppercase
>>> str1 = 'hello WORLD!'
>>> str1.upper()
'HELLO WORLD!'
v. count(str, start, end): Returns number of times substring str occurs in the given string. If we do not
give start index and end index then searching starts from index 0 and ends at length of the string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.count('Hello',12,25)
2
>>> str1.count('Hello')
3
vi. find(str,start, end): Returns the first occurrence of index of substring str occurring in the given
string. If we do not give start and end then searching starts from index 0 and ends at length of the
string. If the substring is not present in the given string, then the function returns -1.

>>> str1 = 'Hello World! Hello Hello'


>>> str1.find('Hello',10,20)
13
>>> str1.find('Hello',15,25)
19
>>> str1.find('Hello')
0
>>> str1.find('Hee')
-1
9
vii. index(str, start, end): Same as find() but raises an exception if the substring is not present in the
given string.
>>> str1 = 'Hello World! Hello Hello'
>>> str1.index('Hello')
0
>>> str1.index('Hee')
ValueError: substring not found

viii. endswith(): Returns True if the given string ends with the supplied substring otherwise returns
False.
>>> str1 = 'Hello World!'
>>> str1.endswith('World!')
True
>>> str1.endswith('!')
True
>>> str1.endswith('lde')
False
ix. startswith(): Returns True if the given string starts with the supplied substring otherwise returns
False
>>> str1 = 'Hello World!'
>>> str1.startswith('He')
True
>>> str1.startswith('Hee')
False
x. isalnum(): Returns True if characters of the given string are either alphabets or numeric. If
whitespace or special symbols are part of the given string or the string is empty it returns False.
>>> str1 = 'HelloWorld'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True
>>> str1 = 'HelloWorld!!'
>>> str1.isalnum()
False
xi. islower(): Returns True if the string is non-empty and has all lowercase alphabets, or has at least
one character as lowercase alphabet and rest are non-alphabet characters
>>> str1 = 'hello world!'
>>> str1.islower()
True
>>> str1 = 'hello 1234'
>>> str1.islower()
True
>>> str1 = 'hello ??'
>>> str1.islower()
True
>>> str1 = '1234'
>>> str1.islower()
False
>>> str1 = 'Hello World!'
>>> str1.islower()
False

10
xii. isupper(): Returns True if the string is non-empty and has all uppercase alphabets, or has at least
one character as uppercase character and rest are non-alphabet characters
>>> str1 = 'HELLO WORLD!'
>>> str1.isupper()
True
>>> str1 = 'HELLO 1234'
>>> str1.isupper()
True
>>> str1 = 'HELLO ??'
>>> str1.isupper()
True
>>> str1 = '1234'
>>> str1.isupper()
False
>>> str1 = 'Hello World!'
>>> str1.isupper()
False
xiii. isspace(): Returns True if the string is non-empty and all characters are white spaces (blank, tab,
newline, carriage return)
>>> str1 = ' \n \t \r'
>>> str1.isspace()
True
>>> str1 = 'Hello \n'
>>> str1.isspace()
False
xiv. istitle(): Returns True if the string is non-empty and title case, i.e., the first letter of every word in
the string in uppercase and rest in lowercase.
>>> str1 = 'Hello World!'
>>> str1.istitle()
True
>>> str1 = 'hello World!'
>>> str1.istitle()
False

xv. lstrip(): Returns the string after removing the spaces only on the left of the string
>>> str1 = ' Hello World! '
>>> str1.lstrip()
'Hello World! '

xvi. rstrip(): Returns the string after removing the spaces only on the right of the string
>>> str1 = ' Hello World!'
>>> str1.rstrip()
' Hello World!'
xvii. strip(): Returns the string after removing the spaces both on the left and the right of the string
>>> str1 = ' Hello World!'
>>> str1.strip()
'Hello World!'

xviii. replace(oldstr, newstr): Replaces all occurrences of old string with the new string >>> str1 = 'Hello
World!'
>>> str1.replace('o','*')
'Hell* W*rld!'

11
>>> str1 = 'Hello World!'
>>> str1.replace('World','Country')
'Hello Country!'
>>> str1 = 'Hello World! Hello'
>>> str1.replace('Hello','Bye')
'Bye World! Bye'
xix. join(): Returns a string in which the characters in the string have been joined by a separator
>>> str1 = ('HelloWorld!')
>>> str2 = '-' #separator
>>> str2.join(str1)
'H-e-l-l-o-W-o-r-l-d-!'
xx. partition()): Partitions the given string at the first occurrence of the substring (separator) and
returns the string partitioned into three parts.
1. Substring before the separator
2. Separator
3. Substring after the separator If the separator is not found in the string, it returns the whole string
itself and two empty strings
>>> str1 = 'India is a Great Country'
>>> str1.partition('is')
('India ', 'is', ' a Great Country')
>>> str1.partition('are')
('India is a Great Country',' ',' ')

xxi. split(): Returns a list of words delimited by the specified substring. If no delimiter is given then
words are separated by space.
>>> str1 = 'India is a Great Country'
>>> str1.split()
['India','is','a','Great', 'Country']
>>> str1 = 'India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']

SUMMARY
 A string is a sequence of characters enclosed in single, double or triple quotes.
 Indexing is used for accessing individual characters within a string.
 The first character has the index 0 and the last character has the index n-1 where n is the length of
the string. The negative indexing ranges from -n to -1.
 Strings in Python are immutable, i.e., a string cannot be changed after it is created.
 Membership operator in takes two strings and returns True if the first string appears as a substring
in the second else returns False. Membership operator ‘not in’ does the reverse.
 Retrieving a portion of a string is called slicing. This can be done by specifying an index range.
 The slice operation str1[n:m] returns the part of the string str1 starting from index n (inclusive) and
ending at m (exclusive).
 Each character of a string can be accessed either using a for loop or while loop.
 There are many built-in functions for working with strings in Python.

12
B. LIST:
Introduction:
The data type list is an ordered sequence which is mutable and made up of one or more elements.
Unlike a string which consists of only characters, a list can have elements of different data types,
such as integer, float, string, tuple or even another list. A list is very useful to group together
elements of mixed data types. Elements of a list are enclosed in square brackets and are separated
by comma. Like string indices, list indices also start from 0.
Indexing: The elements of a list are accessed in the same way as characters are accessed in a string.
List operations (concatenation, repetition, membership & slicing):
Concatenation
Python allows us to join two or more lists using concatenation operator depicted by the symbol +.
>>> list1 = [1,3,5,7,9] #list1 is list of first five odd integers
>>> list2 = [2,4,6,8,10] #list2 is list of first five even integers
>>> list1 + list2 #elements of list1 followed by list2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>>> list3 = ['Red','Green','Blue']
>>> list4 = ['Cyan', 'Magenta', 'Yellow' ,'Black']
>>> list3 + list4
['Red','Green','Blue','Cyan','Magenta', 'Yellow','Black']
Repetition
Python allows us to replicate a list using repetition operator depicted by symbol *.
>>> list1 = ['Hello'] #elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']
Membership
Like strings, the membership operators in checks if the element is present in the list and returns
True, else returns False.
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
True
>>> 'Cyan' in list1
False
Slicing
Like strings, the slicing operation can also be applied to lists.
>>> list1 =['Red','Green','Blue','Cyan', 'Magenta','Yellow','Black']
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']
Traversing a list using loops:
We can access each element of the list or traverse a list using a for loop or a while loop.
(A) List Traversal Using for Loop:
>>> list1 = ['Red','Green','Blue','Yellow', 'Black']
>>> for item in list1:
print(item)
Red
Green
Blue
Yellow
Black
13
Built-in functions:
i. len(): Returns the length of the list passed as the argument. Creates a list if a sequence is passed as
an argument
>>> list1 = [10,20,30,40,50]
>>> len(list1)
5
ii. list(): Creates an empty list if no argument is passed
>>> list1 = list()
>>> list1
[]
>>> str1 = 'aeiou'
>>> list1 = list(str1)
>>> list1
['a', 'e', 'i', 'o', 'u']

iii. append(): Appends a single element passed as an argument at the end of the list The single
element can also be a list
>>> list1 = [10,20,30,40]
>>> list1.append(50)
>>> list1
[10, 20, 30, 40, 50]
>>> list1 = [10,20,30,40]
>>> list1.append([50,60])
>>> list1
[10, 20, 30, 40, [50, 60]]
iv. extend(): Appends each element of the list passed as argument to the end of the given list
>>> list1 = [10,20,30]
>>> list2 = [40,50]
>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]
v. insert(): Inserts an element at a particular index in the list
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,5)
>>> list1
[5, 10, 20, 25, 30, 40, 50]

vi. count(): Returns the number of times a given element appears in the list
>>> list1 = [10,20,30,10,40,10]
>>> list1.count(10)
3
>>> list1.count(90)
0
vii. index(): Returns index of the first occurrence of the element in the list. If the element is not
present, ValueError is generated
>>> list1 = [10,20,30,20,40,10]
>>> list1.index(20)
1
>>> list1.index(90)
ValueError: 90 is not in list
viii. remove(): Removes the given element from the list. If the element is present multiple times, only
the first occurrence is removed. If the element is not present, then ValueError is generated

14
>>> list1 = [10,20,30,40,50,30]
>>> list1.remove(30)
>>> list1
[10, 20, 40, 50, 30]
>>> list1.remove(90)
ValueError:list.remove(x):x not in list
ix. pop(): Returns the element whose index is passed as parameter to this function and also removes it
from the list. If no parameter is given, then it returns and removes the last element of the list
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop(3)
40
>>> list1
[10, 20, 30, 50, 60]
>>> list1 = [10,20,30,40,50,60]
>>> list1.pop()
60
>>> list1
[10, 20, 30, 40, 50]
x. reverse(): Reverses the order of elements in the given list
>>> list1 = [34,66,12,89,28,99]
>>> list1.reverse()
>>> list1
[ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' , 'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion', 'Zebra', 'Tiger']
xi. sort(): Sorts the elements of the given list in-place
>>> list1 = ['Tiger', 'Zebra', 'Lion', 'Cat', 'Elephant', 'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion', 'Tiger', 'Zebra']
>>> list1 = [34,66,12,89,28,99]
>>> list1.sort(reverse = True)
>>> list1
[99,89,66,34,28,12]
xii. sorted(): It takes a list as parameter and creates a new list consisting of the same elements
arranged in sorted order
>>> list1 = [23,45,11,67,85,56]
>>> list2 = sorted(list1)
>>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
xiii. min() / max() / sum(): Returns smallest / largest / sum of elements of the list
>>> list1 = [34,12,63,39,92,44]
>>> min(list1)
12
>>> max(list1)
92
>>> sum(list1)
284

15
SUMMARY
Lists are mutable sequences in Python, i.e., we can change the elements of the list.

• Elements of a list are put in square brackets separated by comma.


• A list within a list is called a nested list. List indexing is same as that of strings and starts at 0. Two-
way indexing allows traversing the list in the forward as well as in the backward direction.
• Operator + concatenates one list to the end of another list.
• Operator * repeats a list by specified number of times.
• Membership operator in tells if an element is present in the list or not and not in does the
opposite.
• Slicing is used to extract a part of the list.
• There are many list manipulation functions
including: len(), list(), append(), extend(), insert(), count(), find(), remove(), pop(), reverse(),
sort(), sorted(), min(), max(), sum().
C. TUPLE:
Introduction:
A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list
or even a tuple. Elements of a tuple are enclosed in parenthesis (round brackets) and are separated
by commas. Like list and string, elements of a tuple can be accessed using index values, starting
from 0.
Indexing:
Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.
Tuple is Immutable:
Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it
has been created. An attempt to do this would lead to an error.
>>> tuple1 = (1,2,3,4,5)
>>> tuple1[4] = 10
TypeError: 'tuple' object does not support item assignment

Tuple operations:
Concatenation
Python allows us to join tuples using concatenation operator depicted by symbol +. We can also
create a new tuple which contains the result of this concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 #concatenates two tuples
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

Repetition
Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can
repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the
second operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 3
('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

16
Membership
The in operator checks if the element is present in the tuple and returns True, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
Slicing
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)

Built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), sum() work same as list.
SUMMARY
• Tuples are immutable sequences, i.e., we cannot change the elements of a tuple once it is
created.
• Elements of a tuple are put in round brackets separated by commas.
• If a sequence has comma separated elements without parentheses, it is also treated as a tuple.
• Tuples are ordered sequences as each element has a fixed position.
• Indexing is used to access the elements of the tuple; two-way indexing holds in dictionaries as in
strings and lists.
• Operator ‘+’ adds one sequence (string, list, tuple) to the end of other.
• Operator ‘*’ repeats a sequence (string, list, tuple) by specified number of times
• Membership operator ‘in’ tells if an element is present in the sequence or not and ‘not in’ does
the opposite.
• Tuple manipulation functions are: len(), tuple(), count(), index(), sorted(), min(), max(),sum().
D. Dictionary:
Introduction:
The data type dictionary falls under mapping. It is a mapping between a set of keys and a set of
values. The key-value pair is called an item. A key is separated from its value by a colon (:) and
consecutive items are separated by commas. Items in dictionaries are unordered, so we may not
get back the data in the same order in which we had entered the data initially in the dictionary.

Creating a Dictionary
To create a dictionary, the items entered are separated by commas and enclosed in curly braces.
Each item is a key value pair, separated through colon (:). The keys in the dictionary must be unique
and should be of any immutable data type, i.e., number, string or tuple. The values can be repeated
and can be of any data type.
#dict1 is an empty Dictionary created
#curly braces are used for dictionary
>>> dict1 = {}
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing items in a dictionary using keys:
We have already seen that the items of a sequence (string, list and tuple) are accessed using a
technique called indexing. The items of a dictionary are accessed via the keys rather than via their
relative positions or indices. Each key serves as the index and maps to a value. The following
example shows how a dictionary returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
17
89
>>> dict3['Sangeeta']
85
#the key does not exist
>>> dict3['Shyam']
KeyError: 'Shyam'
Mutability of dictionary (adding a new item, modifying an existing item): Dictionaries are mutable
which implies that the contents of the dictionary can be changed after it has been created.
Adding a new item
We can add a new item to the dictionary as shown in the following example: >>>
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
The existing dictionary can be modified by just overwriting the key-value pair.
Example to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
#Change marks of Suhel to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,'Sangeeta': 85}
Membership
The membership operator in checks if the key is present in the dictionary and returns True, else it
returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
The not in operator returns True if the key is not present in the dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a dictionary:
We can access each item of the dictionary or traverse a dictionary using for loop.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Method 1
>>> for key in dict1:
print(key,':',dict1[key])
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Method 2
>>> for key,value in dict1.items():
print(key,':',value)
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
18
Built-in functions: len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(),
copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted(), copy();

Method Description Example

len() Returns the length or >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,


number of key: value pairs Sangeeta':85}
of the dictionary passed as >>> len(dict1)
the argument 4

dict() Creates a dictionary from a pair1 =


sequence of key-value pairs [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan':95, 'Ram':89,'Suhel':92,'Sangeeta': 85}

keys() Returns a list of keys in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


the dictionary 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel','Sangeeta'])

values() Returns a list of values in >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


the dictionary 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])

items() Returns a list of tuples (key – >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
value) pair 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92),
('Sangeeta', 85)])

get() Returns the >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,


value corresponding to the 'Sangeeta':85}
key passed as the argument >>> dict1.get('Sangeeta')
If the key is not present in 85
the dictionary it will return >>> dict1.get('Sohan')
None

update() appends the key-value pair >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92,
of the dictionary passed as 'Sangeeta':85}
the argument to the key- >>> dict2 = {'Sohan':79,'Geeta':89}
value pair of the given >>> dict1.update(dict2)
dictionary >>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85,
'Sohan': 79, 'Geeta':89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}

19
del() Deletes the item with >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,
the given key to delete 'Sangeeta':85}
the dictionary from the >>> del dict1['Ram']
memory we write: >>> dict1
del Dict_name {'Mohan':95,'Suhel':92, 'Sangeeta': 85}
>>> del dict1 ['Mohan']
>>> dict1
{'Suhel': 92, 'Sangeeta': 85}
>>> del dict1
>>> dict1
NameError: name 'dict1' is not defined

clear() Deletes or clear all the >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92,


items of the dictionary 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{}

• Dictionary is a mapping (non-scalar) data type. It is an unordered collection of key value pair; key
value pair is put inside curly braces.
• Each key is separated from its value by a colon.
• Keys are unique and act as the index.
• Keys are of immutable type but values can be mutable.

QUESTIONS:
1. What will be the output of the following expression?
float(5 + int(4.39 + 2.1) % 2)
a. 5.0 b. 5 c. 8.0 d. 8
2. What is the value of this expression?
3*1**3
a. 27 b. 9 c. 3 d. 1
3. What can be a possible output at the time of execution of the program from the following code?
import random
AR = [20,30,40,50,60,70];
FROM = random.randint(1,3)
TO = random.randint(2,4)
for K in range(FROM,TO+1):
print (AR*K+,end=”# “)

(i) 10#40#70# (ii) 30#40#50# (iii) 50#60#70# (iv) 40#50#70#

4. Identify the invalid python statement from the following:


a. d = dict() b. l = {} c. f = () d. g = dict {}
5. List AL is defined as follows: AL = [1,2,3,4,5]
Which of the following statements removes the middle element 3 from it, so that list AL equals
[1,2,4,5]. (Multiple options are correct)
a. del a[2] b. a[2:3] = [] c. a[2:2] = [] d. a[2] = [] e. a.remove(3)

6. Select the correct output of the following string operation.

20
str1 = “Waha”
print(str1[:3] + “Bhyi” + str1[-3:])
a. Wah Bhyi Wah b. Wah Bhyi aha c. WahBhyiWah d. WahBhyiWaha

7. Select the correct output of the following code:


event = “G20 Presidency@2023”
L = event.split(“ “)
print(L[::-2])
a. *“G20”+ b. G20 c. *“Presidency@2023”+ d. “Presidency@2023”

8. What is printed when the following code is executed?


K = *“Ram”, “Shyam”, “Sita”, “Gita”+
print(K[-1][-1])
a. R b. m c. Ram d. Gita e. a
9. What will be the output of the following code?
dict = ,“Jo”:1, “Ra”:2-
dict.update(,“Pho”:2-)
print(dict)
a. ,“Jo”:1, “Ra”:2, “Pho”:2- b. ,“Jo”:1, “Ra”:2-
c. ,“Jo”:1, “Pho”:2- d. Error

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


d1 = ,‘a’:10, ‘b’:2, ‘c’:3-
str1 = ‘’
for i in d1:
str1 = str1 + str(d1[i]) + ‘ ‘
str2 = str1[:-1]
print(str2[::-1])
a. 3, 2 b. 3, 2, 10 c. 3, 2, 01 d. Error
ASSERTION & REASON based questions.
1. Assertion (A): List is a mutable data type of Python.
Reason (R): In place change is not possible in list elements.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
2. Assertion (A): in and not in are called membership operators.
Reason (R): They return True based on the presence of a character/substring in a given string
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
3. Assertion (A): Python strings are mutable in nature.
Reason (R): Python strings are stored in memory by storing individual characters in contiguous
memory locations.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.

21
E - Both A and R are false.

4. Assertion (A): append() and extend() are both methods to insert elements in a list.
Reason (R): While append() adds elements at the end of the list, extend can add elements
anywhere in the list.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
5. Assertion (A): A dictionary cannot have two same keys with different values.
Reason (R): Keys of a dictionary must be unique.
A - Both A and R are true and R is the correct explanation of A.
B - Both A and R are true but R is NOT the correct explanation of A.
C - A is true but R is false.
D - A is false but R is true.
E - Both A and R are false.
FILL IN THE BLANKS.
1. The statement is an empty statement in Python.
pass
2. A statement skips the rest of the loop and jumps over to the statement following the
loop.
break
3. Python's cannot be used as variable name.
keywords
4. The explicit conversion of an operand to a specific type is called .
type casting.
5. The data types whose values cannot be changed in place are called types.
immutable
6. The can add an element in the middle of a list.
insert()
7. The only adds an element at the end of a list.
append()
8. The keys of a dictionary must be of type.
immutable
9. Dictionary is an set of elements.
unordered
10. To get all the keys of a dictionary, method is used.
keys()

22
FUNCTION
A function is a programming block of codes which is used to perform a single, related, specific task. It
only works when it is called. We can pass data, known as parameters, into a function. A function can
return data as a result.
Python treats functions like a first-class member. It implies that in Python, functions and other objects
are of same significance. Functions can be assigned to variables, stored in collections, or passed as
arguments. This brings additional flexibility to the language.
Advantages of Functions
 Reducing duplication of code
 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding
Python function types
There are three categories of functions:
 Built-in functions
 Function defined in modules
 User defined functions.
Built-in functions
The functions whose functionality is predefined in Python are referred to as built-in functions.
The python interpreter has several such functions that are always available for use.
E.g. len(), type(), int(), input()
Function defined in modules
These functions are pre-defined in particular modules and can only be used after the specific module is
imported.
E.g. All mathematical functions are defined in the module math.
User-defined functions
Python User Defined Functions allow users to write unique logic that the user defines. It is the most
important feature in Python that consists of custom-defined logics with a set of rules and regulations
that can be passed over the data frame and used for specific purposes.

Structure of functions in Python

Internally Python names the segment with top-level statements (no indentation) as _main_ Python
begins execution of a program from top-level statements.

23
Defining a Function

A function in Python is defined as given below:

def< function name >(parameters):

[“ ” ”<function’s docstring>” “ “]

<statements> [<statements>]

……………………..

 Keyword def that marks the start of the function header.

 A function name to uniquely identify the function. Function naming follows the same rules of
writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are optional.

 A colon (:) to mark the end of the function header.

 Optional documentation string (docstring) to describe what the function does.

 One or more valid python statements that make up the function body. Statements must have the
same indentation level (usually 4 spaces).
 An optional return statement to return a value from the function.

Function header:
The Header of a function specifies the name of the function and the name of each of its parameters. It
begins with the keyword def.
Parameters:
Variables that are listed within the parenthesis of a function header.
Function Body:
The block of statements to be carried out, ie the action performed by the function.
Indentation:
The blank space needed for the python statements. (four spaces convention)
Flow of execution in a function call
The flow refers to the order in which statements are executed during a program run. The function
body is a block of statements and python executes every block in an execution frame.
24
An execution frame contains:
 Some internal information (used for debugging)
 Name of the function
 Values passed to the function
 Variables created within the function
 Information about the next instruction to be executed

Whenever a function call statement is encountered, an execution frame for the function is created and
the control is transferred to it. The statements are then executed and if there is return statement in the
program, it will be executed and returns to the function call statement block.
def message():
print('Hello I am learning how to create function in python.')

def sum(a,b):
c=a+b
print('Sum of %d and %d is %d' %(a,b,c))

# main program
# calling the function message()
message()

# calling the function sum()

sum(10,20)

In the above program, two functions message() and sum() is declared. The message() function does not
accept any argument but displays a text on the screen whenever we call it. On the other hand, the
sum() function accept two arguments and display their sum on the screen. When the main program
calls the function message(), the program flow goes to the body of the function message() and execute
its codes. After that, it returns to the main program and then calls the second function sum() by
sending it two arguments (10,20), the program flow goes to the body of the function sum(), and execute
its code and again returns to the main program. At last, the main programs end.
The function calling another function is called the caller and the functions being called is the called
function or callee.

Parameters and Arguments

The parameters are the variables that we can define in the function declaration. In fact, we utilized
these variables within the function. Also, the programming language in the function description
determines the data type specification. These variables facilitate the function’s entire execution. In
addition, they are known as local variables because they are only available within the function.
The arguments are the variables given to the function for execution. Besides, the local variables of the
function take the values of the arguments and therefore can process these parameters for the final
output.

25
Passing parameters:-
Python support three types of formal arguments/parameters:
1. Positional argument (required arguments):-
When the functions call statement must match the number and order of arguments as define in the
functions definition this is called the positional arguments.
Example:-
def check(a,b,c):
:
Then possible functions call for this can be:-
check(x,y,z) #3 values(all variables) passed
check(2,x,y) #3values(literal+variables)passed
check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed.
Thus through such function calls-
• The argument must be provided for all parameters (required)
• The values of argument are matched with parameters, position(order)wise(positional)
2. Default arguments:-
A parameter having defined value in the function header is known as a default parameter.
Example:-
def interest(principal, time, rate=10):
si=interest(5400,2) #third argument missing
So the parameter principal get value 5400, time get 2 and since the third argument rate is missing,
so default value 0.10 is used for rate.
Default arguments are useful in situations where some parameters always have same value.
Some advantages of the default parameters are listed below:-
• They can be used to add new parameters to the existing functions.
• They can be used to combine similar function in to one.

3. Keyword(or named)arguments:-
Keyword arguments are the named arguments with assigned values being passed in the function call
statement.

Example:-

def interest(prin, time, rate):


return prin * time * rate
print (interest ( prin = 2000 , time = 2 , rate 0.10 ))

26
print (interest ( time = 4 , prin = 2600 , rate = 0.09 ))
print(interest(time=2,rate=0.12,prin=2000))
All the above functions call are valid now, even if the order of arguments does not match.
4. Using multiple argument type together:-
Python allows you to combine multiple argument types in a function call.
Rules for combining all three types of arguments:-
 And argument list must first contain positional(required) arguments followed by any keyword
argument.
• Keyword arguments should be taken from the required arguments preferably.
• You cannot specify a value for an argument more than once.

Example:-

def interest(prin, cc, ime=2, rate=0.09):


return prin * time * rate

Types of user defined function


1. No Argument No return
2. With Argument No return
3. No Argument with return
4. With Argument with return
1. No Argument No return
def Add():
a= int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
print (“The Sum of inputted Numbers is:”, c)
Add()
print(“ Executed”)

2. With Argument No return


def Add(a,b):
c=a+b
print(“The Sum of inputted Numbers is:”, C)
num1= int (input(“Enter First Number”))
num2= int (input(“Enter Second Number”))
Add(num1,num2)

Remember: The variable in main program is differ from the variable in function definition i.e. a and b
should be x and y. In this scenario the variable passed (num1, num2) will be called argument, and when
it replace with the variable defined in the function will be called as parameter.

3. No Argument with return


def Add():
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
c=a+b
return c
27
x= add()
print (“The Sum of inputted Numbers is:”, x)

Note: As return does not show the result we have to store the returned value on another
variable x.
4. With Argument with return
def Add (a,b):
c=a+b return c
a=int (input(“Enter First Number”))
b= int (input(“Enter Second Number”))
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)

Calling function and Called function:


 Function which is called by another Function is called Called Function. The called function contains
the definition of the function and formal parameters are associated with them.
 The Function which calls another Function is called Calling Function and actual Parameters are
associated with them.
 In python, a function must be defined before the function call otherwise python interpreter gives
an error.
Difference between Arguments and parameters
These two terms are very interchangeable, so it is not so important to know the difference. The terms
they refer to are almost identical. However, in order to sound more professional, correct terminology is
important.
Function Parameters: Variables that are in brackets when defining the function. When a method is
called, the arguments are the data passed to the method’s parameters.
Function arguments: Arguments are used to pass information from the rest of the program to the
function. This information return a result. There is no limit to the number of arguments that can be
written. Depending on the type of function you’re performing, there might even be no argument.
Use commas to separate the arguments in a function. Take into account the number of arguments you
put in a function call. The number of arguments must be exactly the same as the number of
parameters.
In the example below, the variable name is the input parameter, whereas the value, “Arnav”, passed in
the function call is the argument.

def welcome(name):
print("Hello! " + name + " Good Morning!!")
welcome("Arnav")
Output:
Hello! Arnav Good Morning!!

Returning a Function
If you wish to return some values from the function to the rest of the program, you can use the return
statement. As the name suggests, it returns a value without printing it. Executing this statement will
cause the Python function to end immediately and store the value being returned into a variable.

28
Scope of variables

Scope means in which part(s) of the program, a particular piece of code or data is accessible or known.
In python there are broadly 2 kinds of Scopes:
 Global Scope
 Local Scope

Global Scope:

 A name declared in top level segment (_main_) of a program is said to have global scope and
can be used in entire program.
 Variable defined outside of the all functions are global variables.

Local Scope:

 A name declared in a function body is said to have local scope i.e. it can be used only within this
function and the other block inside the function.
 The formal parameters are also having local scope.
When dealing with Python functions, you should also consider the scope of the variables. The code in a
function is in its own little world, separate from the rest of the program. Any variable declared in the
function is ignored by the rest of the function. This means that two variables with the same name can
exist, one inside the function and the other outside the function. However, this is not a good practice.
All variable names must be unique regardless of their scope.
Local variable: A variable that is defined within a function and can only be used within that
particular function. With respect to the local variable, the area in a function is called “local area”.
Global variable: A variable that is defined in the main part of the programming and, unlike local
variables, can be accessed via local and global areas.
Example:

Lifetime of Variables:

Lifetime is the time for which a variable lives in memory. For global variables the lifetime is entire
program run i.e. as long as program is executing. For local variable, lifetime is their function’s run i.e. as
long as function is executing.

29
Name Resolution (Scope Resolution)

For every name used within program, python follows name resolution rules known as LEGB rule.
 Local Environment : first check whether name is in local environment, if yes Python uses its value
otherwise moves to (ii)

 Enclosing Environment: if not in local, Python checks whether name is in Enclosing Environment, if
yes Python uses its value otherwise moves to (iii)

 Global Environment: if not in above scope Python checks it in Global environment, if yes Python uses it
otherwise moves to (iv)

 Built-In Environment: if not in above scope, Python checks it in built-in environment, if yes, Python uses
its value otherwise Python would report the error: name <variable> notdefined.
RANDOM MODULE

randint() – function takes starting and ending values both

randrange()-function takes only starting value and ending-1 value

random()-generates decimal values between 0 and 1 but not include 1

Q1 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the minimum values that can be assigned to each of
the variables BEGIN and LAST.
import random
VALUES = [10, 20, 30, 40, 50, 60, 70, 80]
BEGIN = random.randint (1, 3)
LAST = random.randint(2, 4)
for I in range (BEGIN, LAST+1):
print (VALUES[I], end = "-")
(i) 30-40-50- (ii) 10-20-30-40- (iii) 30-40-50-60- (iv) 30-40-50-60-70-

OUTPUT – (i) 30-40-50- Minimum value of BEGIN: 1 Minimum value of LAST: 2


Q2 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables FROM and TO.

import random AR=[20,30,40,50,60,70]


FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO):
print (AR*K+,end=”#“)
(i)10#40#70# (ii)30#40#50# iii)50#60#70# (iv)40#50#70#
Ans
Maximum value of FROM = 3
Maximum value of TO = 4
(ii) 30#40#50#

30
Q3 Consider the following code: import math import random
print(str(int(math.pow(random.randint(2,4),2))))
print(str(int(math.pow(random.randint(2,4),2))))
print(str(int(math.pow(random.randint(2,4),2))))
What could be the possible outputs out of the given four choices?
i) 2 3 4 ii) 9 4 4 iii)16 16 16 iv)2 4 9
Ans
Possible outputs : ii) , iii)

randint() will generate an integer between 2 to 4 which is then raised to power 2, so possible
outcomes can be 4,9 or 16
Q4 Consider the following code and find out the possible output(s) from the options given below.
Also write the least and highest value that can be generated.
import random as r
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15) , end = ‘ ‘)
print(10 + r.randint(10,15))
i) 25 25 25 21 iii) 23 22 25 20
ii) 23 27 22 20 iv) 21 25 20 24

Ans
Possible outputs : i), iii) and iv)
Least value : 10
Highest value : 15
Q5 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum values that can be assigned to each of
the variables BEG and END.

import random
heights=[10,20,30,40,50]
beg=random.randint(0,2)
end=random.randint(2,4)
for x in range(beg,end):
print(heights*x+,end=’@’)

(a) 30 @ (b) 10@20@30@40@50@ (c) 20@30 (d) 40@30@


Ans
(a) & (b)
Maximum value of BEG: 2
Maximum value of END: 4
Q6 What possible output(s) are expected to be displayed on screen at the time of execution of the
program from the following code?
Import random
Ar=[20,30,40,50,60,70]
From =random.randint(1,3)
To=random.randint(2,4)

31
for k in range(From,To+1):
print(ar*k+,end=”#”)
(i) 10#40#70# (iii) 50#60#70# (ii) 30#40#50# (iv) 40#50#70#
Ans: (ii) 30#40#50#
Q7 What possible outputs(s) are expected to be displayed on screen at the time of execution of the
program from the following code. Select which option/s is/are correct?
import random
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' )
print((100) -random.randint(15,25) , end = ' ' )
print((100) *random.randint(15,25) )

(i) 15 122 84 2500 (ii) 21 120 76 1500 (iii) 105 107 105 1800 (iv) 110 105 105 1900

Ans: (i) (ii) are correct answers.

WORKSHEET
Questions (1 mark)
1. Which of the following is the use of function in python?
• Functions are reusable pieces of programs
• Functions don’t provide better modularity for your application
• you can’t also create your own functions
• All of the mentioned
2. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, ‘is maximum’)
elif a == b:
print(a, ‘is equal to’, b)
else:
print(b, ‘is maximum’)
printMax(3, 4)
a) 3 b) 4 c) 4 is maximum d) None of the mentioned
3. What is the output of the below program?
def C2F(c):
return c * 9/5 + 32
print (C2F(100))
print (C2F(0))
a) 212.0
32.0
b) 314.0
24.0
c) 567.0
98.0
d) None of the mentioned

4. The default value for a parameter is defined in function ………..

32
5. Python names the top level segment as…………..
6. Variable declared inside functions may have global scope (True/False)
7. Which arguments given below are skipped from function call?
a)Positional b)Default c)Keyword d)named
8. What is the order of resolving scope in Python?
a) BGEL b)LEGB c)GEBL d)LBEG
9. Complete the function body.
def f(num):
… .......... print (f(8))
a) return 0 b)print(num) c)print(“num”) d)return num
10. The function pow(x,y,z) is evaluated as:
a) (x**y)**z b) (x**y) / z c) (x**y) % z d) (x**y)*z
11. The function seed is a function which is present in the .......................................... module
12. What are the outcomes of the functions shown below?
sum(2,4,6)
sum([1,2,3])
13. What is the output of the functions shown below?
min(max(False,-3,-4), 2,7)
a) 2 b) False c) -3 d) 0
14. What is the output of the program given below?
a = 100
def func (a) :
a = 20
func (a)
print (' a is now ', a)
A. a is now 50 B. a is now 100 C. a is now 2 D. error
15. What will be the output of the following python code:
def A_func (x=10, y=20):
x =x+1 y=y-2
return (x+y)
print(A_func(5), A_func())
a)24,29 b) 15,20 c) 20,30 d) 25,30
16. Consider the following code and choose correct answer:
def nameage(name=”kishan”, age=20):
return age, name
t=nameage(20,”kishan”)
print(t[1])
a)Kishan b) 20 c) (kishan, 20) d) (20,kishan)

QUESTIONS (2 MARKS)
Write the output of the pseudo code:
def absolute_value(num):
if num>= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))

33
QUESTIONS (3 MARKS)
Differentiate ceil() and floor() function?

QUESTIONS (5 MARKS)
What are the arguments supported by python? Explain each of them with a suitable example.
What is the difference between the formal parameters and actual parameters? What are their
alternative names? Also, give a suitable Python code to illustrate both.

ANSWERS

I Answer the following 1 mark


1 A
2 C
3 A
4 Header
5 _main_
6 False
7 B
8 B
9 B
10 C
11 Random
12 The first function will result in an error because the function sum() is used to find the
sum of iterable numbers. Hence the outcomes will be Error and 6respectively.
13 The function max() is being used to find themaximum value from among -3, -4 and
false. Since false amounts to the value zero, hence we are left with min(0, 2, 7) Hence
the output is 0 (false)
14 B
15 A
16 B
II Answer the following 2 marks
2
4
III Answer the following 3 marks

34
Floor Function Ceil Function
floor function returns the integer value just ceil function returns the integer value
lesser than the given rational value. greater than the given rational value

represented as floor(x). represented as ceil(x)


The floor of negative fractional numbers is The ceil of negative fractional numbers are
represented using the floor function represented using ceil function.

It returns the value which is just less than or It returns the value which is just greater than
equal to the given value. equal to the given value.

ANSWER THE FOLLOWING (5 MARKS)


1 Python supports four argument types:
Positional Arguments: Arguments passed to a function in correct positional order, no. of
arguments must match with no. of parameters required.
Default Arguments: Assign a default value to a certain parameter, it is used when the user knows
the value of the parameter, default values are specified in the function header. It is optional in the
function call statement. If not provided in the function call statement then the default value is
considered. Default arguments must be provided from right to left.
Key Word Arguments: Keyword arguments are the named arguments with assigned values being
passed in the function call statement, the user can combine any type of argument.
Variable Length Arguments: It allows the user to pass as many arguments as required in the
program. Variable-length arguments are defined with the * symbol.

2. Actual Parameter is a parameter, which is used in function call statement to send the value from
calling function to the called function. It is also known as Argument.
Formal Parameter is a parameter, which is used in function header of the called function to
receive the value from actual parameter. It is also known as Parameter. For example,
def addEm(x, y, z):
print(x + y + z)
addEm (6, 16, 26)
In the above code, actual parameters are 6, 16 and 26; and formal parameters are x, y and z.

35
EXCEPTION HANDLING
Introduction to Exception Handling
Exception handling is a crucial aspect of programming, aimed at gracefully managing and recovering
from unexpected errors that can occur during program execution. Errors can range from simple typos to
more complex issues like division by zero or attempting to access a nonexistent file. Python provides a
robust mechanism for handling exceptions to prevent program crashes and improve code reliability.
Handling Exceptions Using Try-Except Blocks
The fundamental construct for handling exceptions in Python is the `try-except` block. It allows you to
define a section of code (the "try" block) where you anticipate exceptions might occur. If an exception
occurs within the "try" block, Python immediately jumps to the associated "except" block, where you
can define how to handle the exception.
Here's the syntax for a basic `try-except` block:
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
- `try`: This block contains the code that might raise an exception.
- `except ExceptionType`: If an exception of the specified type occurs in the "try" block, the
code within the "except" block will execute to handle the exception.
Example 1: Handling Division by Zero
try:
numerator = 10
denominator = 0
result = numerator / denominator # This may raise a ZeroDivisionError
except ZeroDivisionError:
print("Error: Division by zero.")
Example 2: Handling File Not Found
try:
file = open("non_existent_file.txt", "r") # This may raise a FileNotFoundError
except FileNotFoundError:
print("Error: File not found.")
The `finally` Block
In addition to `try` and `except`, you can include a `finally` block. Code within the `finally`
block always executes, regardless of whether an exception was raised or not. It is commonly
used to perform cleanup operations, such as closing files or network connections.
try:
# Code that may raise exceptions
except ExceptionType:
# Handle the exception
finally:
# Code that always executes
Example: Using `finally`
try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close() # Close the file, even if an exception occurred or not.
Multiple Choice Questions (MCQ)
1. Which of the following is the primary purpose of exception handling in programming?
- A. To intentionally crash the program
- B. To ignore errors and continue program execution

36
- C. To gracefully manage and recover from unexpected errors
- D. To create errors for testing purposes
Answer: C
2. What is the primary role of the `try` block in a try-except construct?
- A. To execute code that may raise an exception
- B. To handle exceptions
- C. To indicate the end of the try-except construct
- D. To prevent exceptions from occurring
Answer: A
3. In a try-except block, if an exception occurs, which block is executed?
- A. The try block - B. The except block
- C. Both try and except blocks simultaneous - D. None of the above
Answer: B
4. What is the purpose of the `finally` block in exception handling?
- A. To specify the types of exceptions to catch
- B. To execute code regardless of whether an exception occurred or not
- C. To create custom exceptions
- D. To prevent exceptions from propagating
Answer: B
5. Which keyword is used to specify the type of exception to catch in an except block?
- A. `catch` - B. `try` - C. `except` - D. `handle`
Answer: C
6. In a try-except block with multiple except blocks, which block will be executed if an
exception matches multiple except blocks?
- A. The first matching except block encountered from top to bottom
- B. All matching except blocks simultaneously
- C. The last matching except block encountered from top to bottom
- D. None of the above
Answer: A
7. What type of error does a `ValueError` exception typically represent in Python?
- A. A network-related error - B. A division by zero error
- C. An error related to invalid data conversion. - D. A file handling error
Answer: C
8. Which exception is raised when attempting to access a non-existent file?
- A. FileNotFoundError - B. FileNotAccessibleError
- C. NonExistentFileError - D. InvalidFileAccessError
Answer: A
9. What is the main purpose of using a `try-except-finally` construct?
- A. To create custom exceptions - B. To ensure that no exceptions are raised
- C. To gracefully manage exceptions and execute cleanup code
- D. To replace if-else statements
Answer: C
10. What happens if an exception is raised in the `finally` block?
- A. The program crashes
- B. The exception is caught and handled by the `except` block
- C. The program continues executing normally
- D. The `finally` block cannot raise exceptions
Answer: A

37
DATA FILE HANDLING
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb drive etc.

TYPES OF FILE

TEXT FILE

1) A text file stores information in ASCII or unicode characters


2) each line of text is terminated, (delimited) with a special character known as EOL

BINARY FILES

1) A binary file is just a file that contains information in the same format in which the information
is held in memory i.e the file content that is returened to you is raw.
2) There is no delimiter for a line
3) No translation occurs in binary file
4) Binary files are faster and easier for a program to read and write than are text files.
5) Binary files are the best way to store program information.

CSV FILES

1) CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
2) CSV stands for "comma-separated values“.
3) A comma-separated values file is a delimited text file that uses a comma to separate values.
4) Each line of the file is a data record. Each record consists of one or more fields, separated by
commas. The use of the comma as a field separator is the source of the name for this file format

Steps to process a FILE

OPEN THE FILE------> PROCESSING THE FILE ------ >CLOSE THE FILE

OPENING FILES

Using open Function

open() function is used to open a file


Syntax:
file variable/file handle=open(file_name,access mode)
Examples
Programming example description
F= open('abc.txt,'w') this statement opens abc.txt in write mode.file abc.txt will
exist in same folder as python file

38
F= open('D:\\Computer\\abc.txt‟) change the location of file then we have to mention complete
file path with file name . don t forget to mention double slash
in file path
F= open(r'D:\Computer\abc.txt,'w') if you don‟t want to use // then use r in front of file
Note : if file mode is not mentioned in open function then default file mode i.e 'r' is used
2)Use of With Clause
Syntax:
with open(“file name”,access mode) as file object
example with open(“book.txt”,‟r‟) as f

NOTE: no need to close the file explicitly if we are using with clause
CLOSING FILES
close() : the close() method of a file object flushes any unwritten information and close the file object
after which no more writing can be done.
SYNTAX: fileobject.close()

FILE MODE
It defines how the file will be accessed

Text File Binary Description Notes


Mode File
Mode
„r‟ „rb‟ Read only File must exist already ,otherwise python raises I/O
error
„w‟ „wb‟ Write only *If the file does not exist ,file is created.
*If the file exists, python will truncate existing data and
overwrite in tne file. So this mode must be used with
caution.
„a‟ „ab‟ append *File is in write only mode.
*if the file exists, the data in the file is retained and new
data being written will be appended to the end.
*if the file does not exist ,python will create a new file.
„r+‟ „r+b‟ or Read and *File must exist otherwise error is raised.
„rb+‟ write *Both reading and writing operations can take place.
„w+‟ „w+b‟ Write and *File is created if doesn‟t exist.
or read *If the file exists, file is truncated(past data is lost).
„wb+‟ *Both reading and writing operations can take place.
„a+‟ „a+b‟ Write and *File is created if does not exist.
or read *If file exists, files existing data is retained ; new data
„ab+‟ is appended.
*Both reading and writing operations can take place.
TEXT FILE HANDLING
Methods to read data from files
S.N Method Syntax Description
O.
1 Read() <filehandle>.read( [n] ) Reads at most n bytes
If no n is specified, reads the entire file.

39
Returns the read bytes in the form of a string
In [11]:file 1=open(“E:\\mydata\\info.txt”)
In [12]:readInfo=file1.read(15)
In [13]:print(readInfo)#prints firt 15 #characters of
file
In [14]:type(readInfo)
Out[14]:str
2 Readline( ) <filehandle>.readline([n]) Reads a line of input ;if in is specified reads at most
n bytes.
Returns the read bytes in the form string ending
with in(line)character or returns a blank string if
no more bytes are left for reading in the file.
In [20]:file1 = open(“E:\\mydata\\info.txt”)
In [20]: readInfo =file1.readline()
In [22]:print (readInfo)
3 readlines() <filehandle>.readlines() Read all lines and returns them in a list
In [23]:file1 =open(“E:\\mydata\\info text”)
In [24]:readInfo =file1.readlines()
In [25]:print (readInfo)
In [26]:type (readInfo)
Out[26]:list
Writing data into files

S. NO Name Syntax Description


1 Write() <filehandle>.write(str1) Write string str1 to file referenced
by<filehandle>
2 Writelines() <filehandle>.writelines (L) Writes all strings in list L as lines to file
referenced by <filehandle>

RELATIVE AND ABSOLUTE PATH

1) the os module provides functions for working with files and directories ('os' stands for operating
system). os.getcwd returns the name of the current directory
import os

cwd=os.getcwd()

print(cwd)#cwd is current working directory

40
2) A string like cwd that identifies a file is called path. A relative path starts from the current
directory whereas an absolute path starts from the topmost directory in file system.

examples

f=open(„test.txt‟,r) \\test.txt is the relative path

f=open‟(E:\project\myfolder\data.txt‟,r) E:\project\myfolder\data.txt is absolute path

SETTING OFFSETS IN A FILE:

To access the data in random fashion then we use seek () and tell () Method.

tell (): It returns an integer that specifies the current position of the file object in the file.
fileobject.tell()

seek(): It is used to position the file object at a particular position in a file. fileobject.seek(offset [,
reference point]) where offset is the number of bytes by which the file object is to be moved and
reference point indicating the starting position of the file object. Values of reference point as 0-
beginning of the file, 1- current position of the file, 2- end of file.

QUESTIONS
(1 mark questions)
Q1 what is the difference between 'w' and 'a' modes?
Q2 BINARY file is unreadable and open and close through a function only so what are the
advantages of using binary file
Q3 Which of the following functions changes the position of file pointer and returns its new
position?
A. a.)flush()
B. b. tell()
C. c. seek()
D. d. offset()
Q4 which of the following function returns a list datatype

A. d=f.read()
B. d=f.read(10)
C. d=f.readline()
D. d=f.readlines()
Q5 how many file objects would you need to manage the following situations :
(a) to process four files sequentially
(b) To process two sorted files into third file
Q6 The correct syntax of seek() is:

41
A. file_object.seek(offset [, reference_point])
B. seek(offset [, reference_point])
C. seek(offset, file_object)
D. seek.file_object(offset)
Q7 What will be the output of the following statement in python? (fh is a file handle)
fh.seek(-30,2)

Options:- It will place the file pointer:-


A. at 30th byte ahead of current current file pointer position
B. at 30 bytes behind from end-of file
C. at 30th byte from the beginning of the file
D. at 5 bytes behind from end-of file .
Q8 Which Python function is used to open a text file for reading?

A. open("file.txt", "w")
B. open("file.txt", "r")
C. read("file.txt")
D. write("file.txt")
Q 9 text file student.txt is stored in the storage device. Identify the correct option out of the
following options to open the file in read mode.
i. myfile = open('student.txt','rb')
ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r')
iv. myfile = open('student.txt')
A. a. only i
B. b. both i and iv
C. c. both iii and iv
D. d. both i and iii
Q 10 Raman wants to open the file abc.txt for writing the content stored in a folder name sample
of his computer d drive help raman to tell the correct code for opening the file
A. myfile=open(“d:\\sample.txt\\abc”,’w’)
B. myfile=open(“d:\\sample\\abc.txt”,’w’)
C. myfile=open(“d:\\sample\abc.txt”,’w’)
D. all of the above
(2 mark questions)
Q1 write a single loop to display all the contents of a text file file1.txt after removing leading and
trailing WHITESPACES
Q2 what is the output of the following code fragment? explain
out=open('output.txt','w')
out.write('hello,world!\n')
out.write('how are you')
out.close()
42
open('output.txt').read()
Q3 read the code given below and answer the questions
f1=open('main.txt','w')
f1.write('bye')
f1.close()
if the file contains 'GOOD' before execution, what will be the content of the file after execution of
the code
Q4 observe the following code and answer the follow
f1=open("mydata","a")
#blank1
f1.close()
(i) what type of file is mydata
(ii) Fill in the blank1 with statement to write "abc" in the file "mydata"
Q5 A given text file data.txt contains :
Line1\n
\n
line3
Line 4
\n
line6
Q6.What would be the output of following code?
f1=open('data.txt')
L=f1.readlines()
print(L[0])
print(L[2])
print(L[5])
print(L[1])
print(L[4])
print(L[3])
Q6 In which of the following file modes the existing data of the file will not be lost?
i) rb
ii) w
iii) a+b
iv) wb+
v)r+
vi)ab
vii) w+b
viii)wb

43
ix)w+
Q7 what would be the data types of variables data in following statements?
i) Data=f.read( )
ii) Data=f.read(10)
iii) Data=f.readline()
iv)Data=f.readlines()

Q8 Suppose a file name test1.txt store alphabets in it then what is the output of the following code

f1=open("test1.txt")
size=len(f1.read())
print(f1.read(5))
(3 marks questions)
Q 1 Write a user defined function in python that displays the number of lines starting with 'H' in
the file para.txt
Q2 write a function countmy() in python to read the text file "DATA.TXT" and count the number of
times "my" occurs in the file. For example if the file DATA.TXT contains-"This is my website. I
have diaplayed my preference in the CHOICE section ".-the countmy() function should display
the output as:"my occurs 2 times".
Q3 write a method in python to read lines from a text file DIARY.TXT and display those lines which
start with the alphabets P.
Q4 write a method in python to read lines from a text file MYNOTES.TXT and display those lines
which start with alphabets 'K'
Q5 write a program to display all the records in a file along with line/record number.
Q6 write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting
with @ sign.
Answers
(1 mark questions)
Ans 1 w mode opens a file for writing only. it overwrites if file already exist but 'a mode appends
the existing file from end. It does not overwrites the file
Ans 2 binary file are easier and faster than text file.binary files are also used to store binary data
such as images, video files, audio files.
Ans3 c) seek()
Ans4 d) f.readlines()
Ans 5 a)4 b)3
Ans 6 a)
Ans 7 b)
Ans 8 b)
Ans 9 C)
Ans 10 b)
(2 marks questions)

Ans 1 for line in open(“file1.txt”):

print(line.strip())

44
Ans 2 The output will be

Hello,world!

How are you?

The first line of code is opening the file in write mode,the next two line writes text t file .the last
line opens the file and from that reference reads the file content.file() performs the same functions
as open().Thus,the file(“output.txt”)will give the references to open the file on which read() is
applied.

Ans 3 The file would now contains “Bye”only because when an existing file is openend in write
mode .it truncates the existing data in file .

Ans 4 i)Text file

ii) File.write(“abc”)

Ans5Line1

Line3

Line 6

Line 4

Ans6 ab and a+b mode

Ans 7 a)string b)string c)string d)list

Ans 8 No Output

Explanation: the f1.read() of line 2 will read entire content of file and place the file pointer at the
end of file. for f1.read(5) it will return nothing as there are no bytes to be read from EOF
and,thus,print statement prints nothing.

3 marks question
Ans.1
def count H ():
F = open (“para.txt” , “r” )
lines =0
l=f. readlines ()
for i in L:
if i [0]== ‘H’:
Lines +=1
print (“No. of lines are: “ , lines)
45
Ans.2
def countmy ():
f=open (“DATA.txt” ,”r”)
count=0
x= f.read()
word =x.split ()
for i in word:
if (i == “my”):
count =count + 1
print (“my occurs” ,count, “times”)
Ans.3
def display ():
file=open(‘DIARY.txt ‘ , ‘r’)
lines= file.readline()
while line:
if line[0]== ‘p’ :
print(line)
line=file.readline ()
file.close()
Ans.4
def display ():
file=open(MYNOTES.TXT’ , ‘r’)
lines=file.readlines()
while line:
if line[0]==’K’ :
print(line)
line=file.readline()
file.close()
Ans5
f=open(“result.dat” , “r”)
count=0
rec=””
While True:
rec=f.readline (0)
if rec == “ “ :
break
count=count+1
print (count,rec)
f.close()
Ans.6
def filter (oldfile, newfile):
fin =open (oldfile, “r”)
fout= open (newfile, “w”)
while True:
text =fin.readline ()
if len(text)==0:
break
if text[0]== “@”:
continue
fout.write(text)
fin.close()
fout.close()
filter(“source.txt” , “target.txt”)
46
BINARY FILES IN PYTHON:
A Binary file stores the information in the form of a stream of bytes. A binary file stores the data in the
same way as stored in the memory. In Binary file there is no delimiter for a line. The file contents
returned by a binary file is raw i.e. with no translation, thus Binary files are faster than text files. To
work with binary files, you need to open them using specific file modes:

To open a binary file follow this syntax:


file = open(, mode)
For example:
f = open(“one.dat”,”rb”)
Binary File Modes:

 rb: Read a binary file. The file pointer is placed at the beginning of the file. This is the default
mode for reading.
 rb+: Read and write a binary file. The file pointer is placed at the beginning of the file.
 wb: Write to a binary file. This mode will overwrite the file if it exists, or create a new file if it
doesn't.
 wb+: Write and read a binary file. This mode will overwrite the file if it exists, or create a new
file if it doesn't.
 ab: Append to a binary file. The file pointer is at the end of the file if it exists. If the file does not
exist, it creates a new file for writing.
 ab+: Append and read a binary file. The file pointer is at the end of the file if it exists. If the file
does not exist, it creates a new file for writing.

Closing a Binary File


Always close a file after you're done using it to ensure that all resources are properly released. Use the
close() method:
Differences Between Binary Files and Text Files

1. Nature of Data

Binary Files: Store data in binary format (0s and 1s). The data is not human-readable and can represent various
types of data, including images, audio, and executable code.

Text Files: Store data in plain text format. The data is human-readable and consists of characters encoded in
formats such as ASCII or Unicode.

2. Usage

Binary Files: Used for data that is not meant to be read directly by humans, such as media files, compiled
programs, and data serialization.

Text Files: Used for data that needs to be read and edited by humans, such as source code, configuration files,
and documents.

3. Encoding

Binary Files: No specific encoding scheme; the interpretation of bytes depends on the file format.

Text Files: Use character encoding schemes like ASCII, UTF-8, or UTF-16 to represent text.

47
Python objects (list, dictionary etc) have a specific structure which must be maintained while storing or
accessing them. Python provides a special module called pickle module for this.

PICKLING refers to the process of converting the structure(list/dictionary) to a byte of stream before
writing it to a file. The process to converts any kind of python objects (list, dict etc.) into byte streams (0s and
1s).

UNPICKLING is used to convert the byte stream back to the original structure while reading the
contents of the file.

pickle Module: -

Before reading or writing to a file, we have to import the pickle module.


Eg.
import pickle

pickle module has two main methods: dump() and load()

pickle.dump() – This method is used to write the object in the file which is opened in ‘wb’ or ‘ab’ i.e. write
binary or append binary access mode respectively.

Syntax :
pickle.dump(<structure>,<FileObject>)

Here, Structure can be list or dictionary.

FileObject is the file handle of file in which we have to write.

# Simple program to write a list data into a binary file

import pickle
fo = open("binary_file1.dat","wb")
Laptop = ["Dell","HP","ACER"]
pickle.dump(Laptop,fo)
fo.close()

pickle.load() – This method is used to read data from a file and return back into the structure (list/dictionary).

Syntax :
<structure> = pickle.load(<FileObject>)

Structure can be any sequence in Python such as list, dictionary etc. FileObject is the file handle of file in which
we have to write.

# Program to read data from a binary file


fbin = open("binary_file1.dat","rb")
x=pickle.load(fbin)
print(x)
fbin.close()
# Simple program to write a dictionary data into a binary file
import pickle
f=open("my_bin1.bin","wb")
D1={3:'Maruti',2:'Honda',4:'Hundai',1:'BMW'}
pickle.dump(D1,f)
f.close()

48
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()

#Write data to a Binary File:


import pickle
list =[ ] # empty list
while True:
roll = input("Enter student Roll No:")
sname=input("Enter student Name:")
student={"roll":roll,"name":sname} # create a dictionary
list.append(student) #add the dictionary as an element in the list
choice=input("Want to add more record(y/n):")
if(choice=='n'):
break
file=open("student.dat","wb") # open file in binary and write mode
pickle.dump(list, file)
file.close()
OUTPUT:
Enter student Roll No: 1201
Enter student Name: Anil
Want to add more record(y/n): y
Enter student Roll No: 1202
Enter student Name: Sunil
Want to add more record(y/n): n
Read data from a Binary File:
To read the data from a binary file, we have to use load() function
Example:
import pickle
file = open("student.dat", "rb")
list =pickle.load(file)
print(list)
file.close()
OUTPUT:
[{'roll':'1201','name':'Anil'},{'roll':'1202','name':'Sunil'}]

Update a record in Binary File:


def update():
name=input("Enter the name to be updated ")
newstu=[]
while True:
try:
stu=p.load(f)
for i in stu:
if i[1].lower()==name.lower():
rno=int(input("Enter the updated Roll number"))
s=[rno,name]
newstu.append(s)
else:
newstu.append(i)
except:
break
f.close()
f=open("student.dat","rb+")
update()

49
p.dump(newstu,f)
print(“Record updated”)
f.close()
OUTPUT:
Enter the name to be updated Sunil
Enter the updated Roll number 1204
Record updated
Delete a record from binary file:
import pickle
def deletestudent():
roll=input('Enter roll number whose record you want to delete:')
list = pickle.load(fw)
found=0
lst= []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found=1
fw=open(“student.dat”,”rb+”)
delestudent()
pickle.dump(lst,fw)
fw.close()
if found==1:
print(“Record Deleted”)
else:
print(“Record not found”)
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
QUESTION ANSWERS: SET 1

1 Which type of file does not have delimiters? 1

2 The process of converting the structure to a byte stream before writing to the file is 1
known as .

3 The process of converting byte stream back to the original structure is known as 1

4 Raman open a file in readmode, but the file doesn’t exist in the folder. 1
Python raised an error for the code. What type of error will be shown?

5 The prefix in front of a string makes it raw string that is no special meaning 1
attached to any character

6 Pickling is otherwise known as 1

7 CSV files are opened with argument to supress EOL translation 1

50
8 Which of the following statement is incorrect in the context of binary files? 1
a. Information is stored in the same format in which the information is held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing

9 What is EOFError? How can we handle EOFError in python 2

10 How text files and binary files are stored inside computer memory? 2

11 Name any two exceptions that occur while working with pickle module. 2

12 What is the difference between writer object’s writerow() and writerows() function? 2

13 Binary files are the best way to store program information. Discuss 3

Answers :

Sample Answers
1. Binary files
2. Pickling
3. Unpickling
4. FileNotFoundError
5. r
6. Serialization.
7. Newline
8. Every line ends with a new line character
9. EOFError is raised when one of the built-in functions input() or raw_input() hits an end-of-file
condition (EOF) without reading any data. We can overcome this issue by using try and except
keywords in Python, called Exception Handling.
10. A text file stores information in the form of a stream of ASCII or Unicode characters based on the
default state of programming languages. Binary file store information as stream of bytes .
11. Pickle.PicklingError and pickle.Unpickling Error
12. writer.writerow(row): Write the row parameter to the writer’s file object, formatted according to
delimiter defined in writer function. writerows(rows): Writes multiple rows (sequence) to the writer’s
file object.
13. .Binary files store the information in the form of a stream of bytes similar to the format a computer
memory holds data. Also there is no delimiter for a line and no translations occur in binary files. Thus
binary files are faster and easier for a program to read and write. So the best method for a data or
program information is to store it as binary files.

51
QUESTION ANSWERS: SET 2
1 Write Python statements to open a binary file "student.dat" in both read & write 1
mode.

2 Which of the following statement is true? 1


a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
3 Read the following Python code carefully and answers the question given afterthe 1
code

import pickle
#open file in binary mode for writing.
with open('emp.dat', ' ___ ') as outfile: #Line 1
#Store data in list
employee = [101,'Simran',20000]

#Line 2
Fill in the blank in line 1 to open file in binary mode for append data to the file. Fill in
the blank in line 2 to pickle the list and write to file

4 Raghav is trying to write a tuple t = (1,2,3,4,5) on a binary file test.bin. 1


Consider the following code written by him.

import pickle
t = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle _________ #Statement 1
myfile.close()
Identify the missing code in Statement 1.
a. dump(myfile,t)
b. dump(t, myfile)
c. write(t,myfile)
d. load(myfile,t)
5 Computers store every file as a collection of ……… 1
a)strings
b)Bytes
c)characters
d)object
e)none of the above
6 The default file-open mode is ……….. 1

52
a) r
b) a
c) w
d)w+
e)none of the above
7 Which of the following file mode open a file for reading and writing both in the binary 1
file?
a) r
b) rb
c) rb+
d) rwb
8 The file mode is used to handle binary file for reading. 1
a)rb
b)wb
c)r+
d)wb+
e)None of the above
9 Which of the following file mode opens a file for reading and writing both as well as 1
overwrite the existing file if the file exists otherwise creates a new file?
a) w
b) wb+
c) wb
d) rwb
10 module is used to store data into an python objects with their structure. 1
a) csv
b)pickle
c)os
d)numpy
11 What are the two types of data files? Give examples for each. 2

12 What is pickling and unpickling of data? 2

13 What is aBinary File? Give examples 2

14 How can you delete a file? Write a pseudocode to delete a file 2

15 Write a function to read name and roll no from a binary file. 2

16 Amritya Seth is a programmer, who has recently been given a task to write a python 5
code to perform the following binary file operations with the help of two user defined
functions/modules:

a. AddStudents() to create a binary file called STUDENT.DAT containing student


information – roll number, name and marks (out of 100) of each student.

b. GetStudents() to display the name and percentage of those students who have a
percentage greater than 75. In case there is no student having percentage > 75 the
function displays an appropriate message. The function should also display the average
percent. He has succeeded in writing partial code and has missed out certain
53
statements, so he has left certain queries in comment lines. You as an expert of Python
have to provide the missing statements and other related queries based on the
following code of Amritya Answer any four questions (out of five) from the below
mentioned questions.

import pickle
def AddStudents():
#1 statement to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")

Percent = float(input("Percent :"))


L = [Rno, Name, Percent]
#2 statement to write the list Linto the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
Total=0
Countrec=0
Countabove75=0

with open("STUDENT.DAT","rb") as F:
while True:
try:
#3 statement to readfrom the file
Countrec+=1
Total+=R[2]
if R[2] > 75:

print(R[1], " has percent =",R[2])


Countabove75+=1
except:
break

54
if Countabove75==0:
print("There is no student who has percentage more than 75")
average=Total/Countrec print("average percent of class = ",average)
AddStudents()
GetStudents()
1. Which of the following commands is used to open the file “STUDENT.DAT” for
writing only in binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
2. Which of the following commands is used to write the list L into the binary file,
STUDENT.DAT? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)

c. pickle.dump(L,F) d.
f=pickle.dump(L)
3. Which of the following commands is used to read each record from the binary file
STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)

c. r= pickle.read(f)
d. pickle.load(r,f)
4. Which of the following statement(s) are correct regarding the file access modes?

a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it
exists and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it
exists and creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file
exists
5. Which of the following statements correctly explain the function of seek()
method?
a. tells the current position within the file.
b. determines if you can move the file position or not.

55
c. indicates that the next read or write occurs from that position in a file.
d. moves the current file position to a given specified position

17 Compare Text files, Binary Files and CSV files. 5

ANSWERS
1.file = open("student.dat", "rb+")
2.pickling is used for object serialization
3.a) ab b)pickle.dump(employee,outfile)
4. dump(t, myfile)
5. b
6.a
7.c
8.c
9.b
10 b
11. c

12. There are two types of files: Text Files- A file whose contents can be viewed using a text editor is
called a text file. A text file is simply a sequence of ASCII or Unicode characters. Python programs,
contents written in text editors are some of the example of text files. Binary Files-A binary file stores
the data in the same way as as stored in the memory. The .exe files, mp3 file, image files, word
documents are some of theexamples of binary files. We can’t read a binary file using a text editor
13. Pickling is the process of transforming data or an object in memory (RAM) to a stream of bytes
called byte streams. These byte streams in a binary file can then be stored in a disk or in a database or
sent through a network.
Unpickling is the inverse of pickling process where a byte stream is converted back to Python object
14. 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.Binary Files contain raw data so are not in human readable format.
It can be read by using some special tool or program.
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc

15. To delete a file, import the OS module, and run its os.remove() function. import os
os.remove("demofile.txt")
16. I. a) II. c) III. a) IV. a) V.d)
17. Do Yourself

56
CSV FILES
CSV stands for Comma Separated Values. It is a type of plain text file that uses specific structure to
arrange tabular data i.e. data stored in rows and columns such as a spreadsheet or database.
CSV is like a text file, It is in human readable format and extensively used to store tabular data, in a
spreadsheet or database.
Each line of the csv file is a data record. Each record consists of one or more fields, separated by
commas. The separator character of CSV files is called a delimiter.
Default delimiter is (,). Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.
READING FROM A CSV FILE
To read data from csv files, reader() method of csv module is used. csv.reader() returns a reader
object.
STEPS TO READ
1. import csv module
import csv
2. Open csv file in read mode.
f = open(“csv_demo.csv”,”r”)
3. Create the reader object.
demo_reader = csv.reader(f)
4. Fetch data through for loop, row by row.
for x in demo_reader:
print(x)
5. Close the file
f.close()
WRITING IN TO CSV FILES:
To write data into csv files, writer() function of csv module is used.
csv.writer(): This function returns a writer object which writes data into writer object.
Significance of writer object
The csv.writer() returns a writer object that converts the data into a delimited string. The string can be
later converted into csv files using the writerow() or writerows() method.
Syntax:
<writer_object>.writerow() :

Writes one row of data in to the writer object.


<writer_object>.writerows()
Writes multiple rows into the writer object.
# Program to write data into a CSV File and to read data stored in csv file
import csv
f=open("mycsv.csv","w",newline='')
w=csv.writer(f)
lst=["RNO","NAME","MARKS"]
w.writerow(lst)
n=int(input('Enter how many students record you want to add'))
for x in range(n):
r=int(input('Enter rno'))
57
n=input('Enter name')
m=int(input('Enter marks'))
lst2=[r,n,m]
w.writerow(lst2)
f.close()
f=open("mycsv.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
# Program to write Employee Name, EmpID and Dept for some employees in a csv file then display
records of all the employees.
import csv
f=open("emp.csv","w",newline='')
emp_writer = csv.writer(f)
emp_writer.writerow(["EmpName","EmpID","Dept"])
emp_rec = []
while True:
print("Enter Employee details: ")
empname = input("EmpName : ")
eid = int(input("EmpID : "))
dept = input("Department : ")
emp_rec.append([empname,eid,dept])
ch = input("Do you want to continue ?? (Y?N)")
if ch == "N" or ch =="n":
break
emp_writer.writerows(emp_rec)
f.close()
f=open("emp.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()

Question based on CSV file Handling: -


Madhwan, is doing internship in “SQUARE Solutions Pvt. Ltd.”. He wrote the following python code to
store student’s data in csv file (Student.csv) handling. Unfortunately, he forgot some steps of the
python code. Please help him to create a CSV File 'Student.csv' by completing the code.
CSV File
1,SAKSHAM,XII,A
2,ARNAV,XI,A
3,SHREEVALI,XII,A
4,BHOOMI,XI,A
5,SWARIT,XII,A
The Incomplete Code written by Madhwan is as follows: -
import #Statement-1
csvfh = open( , ____ , newline='') #Statement-2
stuwriter = csv. #Statement-3
data = []
header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']
58
data.append(header)
for i in range(5):
roll_no = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
section = input("Enter Section : ")
rec = [ ____ ] #Statement-4
data.append(rec)
stuwriter. (data) #Statement-5
csvfh.close()

a) Identify the suitable code for Statement-1.


a) csv file
b) CSV
c) csv
d) Csv
Correct Answer : c) csv
b) Identify the correct parameters for Statement-2?
a) "School.csv","w"
b) "Student.csv","w"
c) "Student.csv","r"
d) "School.csv","r"
Correct Answer: b) "Student.csv","w"
c) Choose the function name (with argument) to complete Statement-3
a) reader(csvfh)
b) reader(MyFile)
c) writer(csvfh)
d) writer(MyFile)
Correct Answer : c) writer(csvfh)
d) Identify the suitable code for Statement-4.
a) 'ROLL_NO', 'NAME', 'CLASS', 'SECTION'
b) ROLL_NO, NAME, CLASS, SECTION
c) 'roll_no','name','Class','section'
d) roll_no,name,Class,section
Correct Answer : d) roll_no,name,Class,section
e) Choose the function name that should be used for Statement-5 to create the desired CSV File.
a) dump()
b) load()
c) writerows()
d) writerow()
Correct Answer : c) writerows()

59
DATA STRUCTURE ( STACK)
Stack: A stack is a data structure whose elements are accessed according to the Last-In First-Out
(LIFO) principle. This is because in a stack, insertion and deletion of elements can only take place
at one end, called top of the stack. Consider the following examples of stacks:
1. Ten glass plates placed one above another. (The plate that is kept last must be taken out first).
2. The tennis balls in a container. (You cannot remove more than one ball at a time)
3. A pile of books.
4. Stack of coins
The Significance of Stack Top : If we want to remove any coin from the stack, the coin on the top
of the stack has to be removed first. That means, the coin that In the above picture coins are kept one
above the other and if any additional coin is to be added, it can be added only on was kept last in the
stack has to be taken out first.
Note: Stack Work on LIFO (Last In First Out) principle.

Operations on Stack :
We can perform two operations on stack are: Push and Pop
Push (Add/Insert): Adding an element in stack is called Push operation.
When the stack is empty, the value of top is Basically, an empty stack is initialized with an invalid
subscript. Whenever a Push operation is performed, the top is incremented by one and then the new
value is inserted on the top of the list till the time the value of top is less than or equal to the size of the
stack.
The algorithm for Push operation on a stack:
1. Start 2. Initialize top with -1 3. Input the new element
4. Increment top by one. 5. Stack[top]=new element. 6. Print “Item inserted” 7. Stop
Pop (Removing (deleting) an element from the stack.
Removing existing elements from the stack list is called pop operation. Here we must check if the stack
is empty by checking the value of top. If the value of top is -1, then the stack is empty and such a
situation is called Underflow. Otherwise, Pop operation can be performed in the stack. The top is
decremented by one if an element is deleted from the list. The algorithm for pop operation is as follows:

Example Question :
A list, NList contains following record as list elements:
[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.
• 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.
• 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.

ANSWER:
travel=[]
def Push_element(NList):
for L in NList:
if(L[1] != 'India' and L[2]<3500):
travel.append([L[0],L[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print('Stack Empty')

60
COMPUTER NETWORKS
Syllabus:
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

Evolution of networking:

What is Network?
It is a collection of Inter-connected computers and other devices that are able to communicate with
each other i.e. it is a collection of hardware and software components that are connected together for
effective information interchange wherein, one system/device is the sender and the other is the
receiver.

Advantages of Computer Network:


a. Resource sharing
b. Remote access
c. Cost saving
d. Collaborative user interaction
e. Time saving
f. Enhanced storage
Drawbacks
a. Poor handling can cause chaos
b. If the files are stored centrally, it may sometimes become impossible to carry out any task
c. File security becomes high priority task in case of shared network
d. One may need specified staff to ensure data security
61
Evolution of Networking

Network Communication dates back to the earliest times since the evolution of human race on earth.
All the living organisms communicate with each other on one way or the other. The early man used to
communicate using the symbolic language, then with the development of modern languages and
intelligence, the communication media came into picture. And, with the advent of computer systems,
the data communication became important so as to take necessary decisions and pass the messages
quickly.
In year 1967, the very first network came into existence, namely-ARPANET.

ARPANET

(Advanced Research Project Agency Network) that was designed to survive any nuclear threat. It was the
first system to implement the TCP/IP protocol suite and was based on Client-Server architecture.

NSFNet

National Science Foundation Network, was started in 1980 with a view to enhance Academic and
Scientific Research. It connected its server with the ARPANET in year 1986. In the year 1990, the
NSFNet, ARPANET and other smaller networks clubbed together to form the INTERNET
(Interconnected Networks) and hence the foundation of modern INTERNET was laid down.

Internet:

It is the global network of interconnected devices that may/may not follow same set of rules, and connect
together for sharing information and establishing communication. It is made up of two parts:
a. IntraNet:
The word Intra means inside or within. Therefore, Intranet means
the network within an organization. It is created using the
protocols of LANs and PANs. Example: Wipro uses internal
network for business development
b. Extranet:
It is the network that lies outside the limits of the IntraNet. Dell
and Intel use network for business related operation.
c. Interspace:
It is the client-server software program that allows multiple users to communicate with each
other using real-time audio, video and text in a dynamic 3D environment.

62
Data communication terminologies:

COMMUNICATION

The exchange of information between two or more networked or interconnected devices is called
communication. These devices must be capable of sending /receiving data over a communication
medium.
Data:
It is raw facts and figures that are yet to get a defined meaning. Examples: 11, A123x@r67Y, etc.
Information:
The processed form of data that had a defined meaning is known as the information. Examples: Roll No.
11, Password: A123x@r67Y, etc.

COMPONENTS OF DATA COMMUNICATION

The five main components of data communication are as follows:


SENDER: Sender is a device which is capable of sending data over a communication network. In data
communication Sender is also called Source.
RECEIVER: Receiver is a device which is capable of receiving data over a communication network. In
data communication Receiver is also called Destination.
MESSAGE: message is the information being exchanged between a sender and a receiver over a
communication network.
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.

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.
Examples of some commonly used Protocols in data communication are given below:
∙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.
Data Channel:
It is a medium to carry information or data from one point to another.
Baud:
It is the measurement of the data transfer rate in a communication channel.
Bits per Second:
63
It is the rate by which the data transfer is measured. It is used to measure the speed of information
through high-speed phone lines or modems. It is denoted ad Bps, kbps, Mbps, Gbps, etc.
Bandwidth:
It is the difference between the highest and lowest frequencies in a channel. The high bandwidth
channels are known as Broadband Channels, and the low bandwidth channels are called as the
Narrowband Channels.
Data Transfer Rate:
It is the amount of data transferred per second by a communication channel or a computing storage
device. When applied to the data transmission rate, the abbreviations like K, M, G, T are added to the
data rate that denote Kilo, Mega, Giga, and Tera respectively. They work in the power of 1024.
Example 1 GB = 1024 MB, 1 TB = 1024 GB.

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. An
IP address allows computers to send and receive data over the internet. They can also be used to track
down a user's physical location.
There are two versions for IP address IPV4 and IPV6. IP addresses are binary numbers but are typically
expressed in decimal form (IPv4) or hexadecimal form (IPv6) to make reading and using them easily.
The commonly used IP address is IPV4. An IPv4 address consists of four numbers, each of which
contains one to three digits, with a single dot (.) separating each set of digits. Each of the four numbers
can range from 0 to 255. Example IP address: 24.171.248.170

Switching Techniques:

These are used for transmitting data across the networks. The various switching techniques are:
a. Circuit Switching:
Here, the connection between the sender and receiver is established first, and then the data is transmitted
from the source computer to destination computer. Before transferring the data, a call setup is required
for establishing connection between sender and receiver. It is best for connections that require consistent
bit rate for communication.
Advantages:
1. Since a dedicated communication channel is set up before communicating the message, the data
transmission is reliable and is suitable for long and continuous communication.
2. Circuit switching uses fixed bandwidth as well as data rates.
3. As the data is communicated continuously, no need of sequencing or re ordering it at the receiving
end.
Disadvantages:
1. Time required to setup a physical connection between the sender and the receiver makes delay in
communication
2. Since a communication channel is dedicated for a particular transmission, it cannot be utilized for
other communication, even if the channel is free.
3. More expensive since connection has to be established every time before communication.
b. Packet Switching:
It is the most efficient data communication technique used to send and receive data over the internet.
Instead of using the dedicated circuit for data communication, the data is independently routed through
the network and reassembled at the destination computer system. Data is divided into fixed size packets
before transmission. Each packet contains a fraction of data along with addressing information.
64
Advantages:
1. Packet switching is effective type of data transmission technique as it effectively utilizes the
communication channel. Multiple users can share the channel simultaneously utilizing the bandwidth
effectively.
2. It is cost effective and easy to implement compared to circuit switching.
3. As the messages are sent as small sized packets, the data transmission is quick and easy.

Disadvantages:
1. In packet switching the movement of packets may not be in correct order. Hence it is not suitable for
voice communication.
2. Unorganized movement of packets makes it necessary to implement proper sequencing and reordering
techniques.
3. As the packets flow through multiple paths from the source to the destination, complex security
protocols are required to ensure reliable communication.
c. Message Switching:
In this technique, the message is sent to the switching office first that stores the data in the buffer, and
then the switching office finds the free link to the receiver, and then sends the data to the receiver. There
is no limit to the size of the message block to be transmitted over the network.

Transmission media:
All the computers or connecting devices in the network, must be connected to each other by a
Transmission Media or channel. The selection of Media depends on the cost, data transfer speed,
bandwidth anddistance.Transmission media may be classified as-
Guided Media (Wired )
Twisted Pair Cable
Coaxial Cable
Optical Fiber
Unguided Media (Wireless)
Microwave
Radio wave
Satellite
Others (Blue tooth, Infrared and Laser etc.)

65
1. Twisted Pair Cables
It is most common type of media consisting insulated pairs of wires twisted around each other. Twisting
helps to reduce crosstalk and Electro Magnetic Interference.
It comes in Shielded (STP) or Unshielded Twisted Pair (UTP) types. In UTP, pairs are covered by an
extra insulation to further reduce the signal interference.
CAT 5 and CAT 6 are commonly used in the networking.
Advantages:
It is simple, flexible, low weight and inexpensive.
It is easy to install and maintain and requires RJ-45 Connector.
Disadvantages:
Suitable for short distance (up to 100 mt.). For long distance Repeater is required.
It supports low bandwidth and offers up to 100 Mbps speed.

2. Coaxial cable

This types of cable consists a solid insulated wire core surrounded by wire mesh or shield, each
separated by some find of foil or insulator. The inner core carries the signal and mesh provides the
ground. Co-axial Cable or coax, is most common in Cable TV transmission. Generally it is used in Bus
topology network.
It is two type- Thinnet (185 mt), Thicknet(500 mt)
A connector known as a vampire tap or BNC connector to connect network devices.
Advantages:
 It offers high bandwidth and better speed than other cables.
 Suitable for Broadband transmission (cable TV) and can be used in shared cable
network.
Disadvantages:
 It is expensive compared to Twisted Pair cable.
 Not compatible with modern cables like UTP and STP

3. Fiber Optic

Optical Fiber consists of thin glass or glass like material and carry light. Signal are modulated and
transmitted in light pulses from source using Light Emitting Diode (LED) or LASER beam.
The Fiber cable consists Core (Glass or Plastic) covered by Cladding, which reflects light back to the
core. Also a Protective cover including Buffer Jacket is used for extra protection.
Two types of transmission i.e. Single mode (LESER) and Multimode (LED) is possible.
Advantages:
66
 It is free from EMI since no electrical signal are carried.
 Offers secure and high speed transmission up to a long distance.
Disadvantages:
 Expensive and quite fragile.
 Complicated Installation procedure and difficult to join two fiber or broken fiber.
 Not suitable for domestic purposes due to high maintenance cost.

Wireless Transmission Media


∙ In wireless communication technology, information travels in the form of electromagnetic signals
through air. ∙ Electromagnetic spectrum of frequency ranging from 3 KHz to 900 THz is available for
wireless communication.
∙ Radio Waves
1. Waves of frequency range 3 KHz - 1 GHz
2. Omni-directional, these waves can move in all directions
3. Radio waves of frequency 300KHz-30MHz can travel long distance
4. Susceptible to interference
5. Radio waves of frequency 3-300KHz can penetrate walls
6. These waves are used in AM and FM radio, television, cordless phones.

Microwaves
1. Electromagnetic waves of frequency range 1GHz - 300GHz.
2. Unidirectional, can move in only one direction.
3. Cannot penetrate solid objects such as walls, hills or
mountains.
4. Needs line-of-sight propagation i.e. both communicating
antenna must be in the direction of each other.
5. Used in point-to-point communication or unicast communication such as radar and
satellite.
6. Provide very large information-carrying capacity.

Infrared waves
1. Electromagnetic waves of frequency range 300GHz - 400THz.
2. Very high frequency waves.
3. Cannot penetrate solid objects such as walls.
4. Used for short-distance point-to-point communication such as mobile-
to mobile, mobile- to-printer, remote-control-to-TV,

67
Bluetooth:
Bluetooth is a short-range wireless technology commonly used for
connecting devices like smartphones, laptops, and peripherals (e.g., wireless
keyboards, mice, and headphones). It
operates in the 2.4 GHz frequency band and supports relatively low data transfer
rates compared to Wi-Fi.

Satellite Communication:
Satellite communication involves transmitting data to and from
Earth through communication satellites. It is used for long-distance
communication in remote areas or where traditional wired
communication is not feasible.

Network devices
For smooth functioning of computer network, other than computers and wirings, many devices play an
important role. These devices are known as the Network Devices.

Modem:
Modulator-Demodulator allows us to reach the global network with ease. It is used to send and receive
the data over the telephone lines or cable connections. Since, the ordinary telephone lines cannot carry
the digital information, a modem changes the data from analog to digital format and vice versa.
Modems are of two types:
 Internal modems: The modems that are fixed in the computer systems are Internal Modems.
 External Modems: The modems that are connected externally are called External Modems.

Registered Jack-45 (RJ-45):


Registered Jack-45 of Rj-45 is an 8-wire connector that is
commonly used on computers in a local area network. It looks
similar to a standard phone connector (RJ-11), but is wider than
the RJ-11 connector, as it uses 8 wires instead of 4. These are
used to connect computers in Ethernet LAN.
NIC:
Network Interface Card (NIC) is a device used to connect the network with the Internet. It is sometimes
called ad the TAP (Terminal Access Point). Since different manufacturers give different names to this
device, hence, it is sometimes referred to as NIU (Network Interface Unit).
The NIC has a unique physical address to each card, and it is known as MAC (Media Access Control)
Address.
MAC Address:
It is a b-byte address assigned to each NIC card and is separated by a colon. Example:
10 : E8 : 05 : 67 : 2A : GS
Manufacturer ID Card No.

Ethernet Card:
It is a LAN architecture developed by Xerox Corp along with the DEC
and Intel. It uses a bus or star topology for data transfer and can attain a

68
speed of up to 10 Gbps. It can connect devices in both wired and wireless
LAN or WAN.
Router:
It is responsible for forwarding data from one network to another. The main purpose of router is sorting
and distribution of the data packets to their destination based on the IP address. The router uses the
Logical address scheme.

Hub:
It is a device that connects several devices to a network and transmits the information to all the connected
devices via broadcast mode.
The hubs are of two types:
Active hubs: these electrically amplify the signal as it moves from one
connected device to another.
Passive hubs: these allow the signals to pass from one device to another
without any change.

Switch:
It is a device that is used to divide network into smaller networks
called subnets or LAN segments. This helps to avoid network traffic
as it divides the traffic into smaller parts. It is responsible for
filtering of data packets and then transmission over the network.

Repeaters:
A repeater is a network device that amplifies, restores and re-broadcasts signals for long-distance
transmission.

Bridge:
It is a device that links two networks. It is smart system that knows which system lies on which side and
in which network. These can handle the networks that follow different protocols.

Gateway:
It connects two dissimilar networks and establishes an intelligent connection between local and external
networks with completely different architecture. It is also known as protocol translator.

Wi-Fi Card:
It is the LAN adapter whether external or internal with a built-in antenna and
wireless radio. Its main benefit is that it allows a computer to setup the system
as workstation without considering the availability of hard- line access.

Network topologies and Network types:


Network Topologies
The term topology means the way of connecting different systems to form a network. Some of the
commonly used topologies are as follows:
Bus Topology:
 In a bus topology, all devices are connected to a single communication line called the bus or
backbone.

69
 Data is transmitted from one end of the bus to the other, and all devices receive the data
simultaneously.
 It is relatively easy to implement and works well for small networks. However, a single break in
the bus can disrupt the entire network.
Star Topology:
 In a star topology, all devices are connected to a central hub or
switch.
 Each device has a dedicated point-to-point connection to the
central hub.
 If one device or cable fails, only that specific connection is
affected, and the rest of the network remains operational.
 It is straightforward to add or remove devices, making it scalable.
Ring Topology:
 In a ring topology, devices are connected in a closed loop,
forming a ring.
 Each device is connected to exactly two other devices, creating
a continuous circular pathway for data transmission.
 Data travels in one direction around the ring until it reaches the
intended recipient.
 Failure of any single device or connection can disrupt the entire
network.
Mesh Topology:
 In a mesh topology, every device is connected to every other device
in the network. It provides multiple redundant paths for data
transmission, ensuring high reliability and fault tolerance.
 Mesh topologies are commonly used in critical applications where
network uptime is crucial. However, the extensive cabling and
complex connections can be expensive and challenging to manage.

Hybrid Topology:
 A hybrid topology is a combination of two or more basic topologies
(e.g., star- bus or star-ring).
 It leverages the advantages of different topologies and can be
designed to suit specific networking needs.
 Hybrid topologies are commonly used in large networks or in
scenarios with diverse connectivity requirements.

Tree Topology:
Tree topology is a network design where devices are organized in a hierarchical structure, resembling a
tree with a root node at the top and branches of nodes extending downward.

70
The root node acts as the central hub, and devices are connected to it directly or through intermediary
devices like switches or hubs.

This creates a multi-level structure, with each level representing a different generation of devices. Tree
topology is commonly used in wide area networks (WANs) to interconnect different local area networks
(LANs) or subnets in a hierarchical manner. It is also found in some enterprise networks and
telecommunications networks.

Advantages of Tree Topology:


Scalability: The network can be easily expanded by adding more devices or branches.
Centralized Management: The root node allows for centralized control and easy network
management.
Fault Isolation: Issues in one branch do not affect the rest of the network, simplifying troubleshooting.
Point-to-Point Connections: Devices have dedicated connections, reduced data collisions and
improving performance.
Disadvantages of Tree Topology:
Dependency on Root Node: The network's functionality relies on the root node, and its failure can
disrupt the entire network.
Cost: Implementing tree topology can be expensive, especially for larger networks.
Complex Cabling: As the network grows, the cabling can become more complex and difficult to
manage.

Types of Networks:

The computer networks are divided into the following parts based on the network span and number of
systems connected.
1. PAN - Personal Area Network
2. LAN - Local Area Network
3. MAN - Metropolitan Area Network
4. WAN - Wide Area Network
PAN – Personal Area Network:
A personal area network (PAN) is designed for interconnection between devices typically located
71
within the range of 10 meters approx. These are used to connect personal use devices like
smartphones, laptops, tablets, wearable devices and other peripherals.
Bluetooth and Wi-Fi are the commonly used technologies for establishment of PANs. PANs find
applications in various scenarios, such as:
 Wireless Headsets: For establishing connections between computers/smart phones with
headsets/head phones.
 Personal health Devices: For pairing fitness related trackers/ smart phones for monitoring
health and workout timings.
 Home automation: For connecting home use and safety devices
to a central controller such as smart phone.
 File Transfer: For ensuring smooth and fast transfer of files
between laptops, tablets etc.
 Security: To enhance and implement security protocols like
encryption to ensure data privacy and prevent unauthorized
access to the connected devices.
 Ad-Hoc Networking: These are often used as Ad-Hoc networks for use as and when required.
These networks are established and disbanded as per the requirement. Also, the devices can
quickly connect to the network and disconnect whenever they are in or out of range.
LAN – Local Area Network
A local area network (LAN) is designed for implementation between devices that are located within a
limited geographical area generally within the range of approximately 1 – 10 KM. this network can be
setup using wired or wireless transmission medias, and can be controlled by an individual or an
organization. It is also known as Intranet as it is a network within an organization.
 These can use various topologies such as star, bus, ring, or mesh. The most commonly used
topology for LANs is the Star topology, where all the devices are connected to a central switch
or hub.
 LANs offer high data transfer rates as the network has a limited span enabling fast
communication and resource sharing.
 The network administrator can easily manage and monitor
devices in a LAN.
 The LANs are commonly used in offices, homes, and
educational institutions.
 LANs implement security measure such as Firewalls, access
controls, and encryption to protect data and unauthorized
access to the network at a much cheaper cost.
MAN – Metropolitan Area Network:
It is a network infrastructure that covers a larger geographical area than a Local Area Network (LAN) but
smaller than the Wide area Network (WAN). These use various connectivity technologies including
fiber-optic cables, microwave links and wireless technologies to interconnect devices and networks
within the area of a city and ranges between 5 – 100 KMs.
 MANs often use high speed technologies like fiber- optic
cables, microwave links to provide fast and reliable data
transmission between network nodes.
 These are often used by government agencies and large
educational institutions to interconnect LANs and share
resources like files, databases, and applications.
 They often use different Internet Service Providers
 (ISPs) for effective data communication thereby strengthening the backbone of the Internet.
 These can be either privately owned, cooperative, or government owned to provide services to

72
the public.
 These networks have grown rapidly in the past few years as the spans of cities have increased
rapidly.
 The network security plays a crucial role in the MANs and increases the cost incurred due to
wide area coverage.
 They play a significant role in interconnecting local networks within a city, enabling efficient
data exchange and facilitating communication among various entities in the metropolitan
region.
WAN – Wide Area Network:
It is a type of computer network that covers a vast geographical area spanning among cities, countries,
or even continents.
 These use various technologies like leased lines, fiber optic cables,
and satellite links.
 Since it is the expanded form of MAN, it is considered as the
backbone.

 These allow the efficient transfer of data, voice, and videos between different nodes thereby
enabling communication and resource sharing between devices at far away distances.
 These are designed with redundancy and backup links to ensure high fault tolerance thereby
minimizing disruptions and maintaining connectivity even if some network segment fails.
 Data Security becomes the key issue as it becomes essential to protect data from unauthorized
access and cyber threats. Thus encryption, firewalls and virtual
 private Networks (VPNs) play an important role in ensuring data security.
 These may have varying speeds and bandwidth depending upon the technology used and the
distance between network nodes.
Note:
Virtual Private Network: It is used to access the public network as a private network.
It ensures enhances security, and safety of data.
Difference between LAN, MAN, and WAN

73
NETWORK PROTOCOL:
A protocol means the rules that are applicable for a network. Protocols define standardized formats for
data packets, techniques for detecting and correcting errors etc.
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.
 When accessing any web page entering http:// in front of the address tells the browser to
communicate over HTTP.
 Clients (web browsers) send requests through request object of http to web servers for web
pages, resources etc

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.
PPP- Point-to-Point Protocol
(PPP) is protocol that is used to connect one computer system to another. Computers use PPP to
communicate over the telephone network or the Internet. A PPP connection exists when two systems
physically connect through a telephone line. You can use PPP to connect one system to another.
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.
• It is a program used for sending messages to other computer users based on e-mail addresses.
• It provides a mail exchange between users on the same or different computers, and it also
supports:
• It can send a single message to one or more recipients.
• Sending message can include text, voice, video or graphics.
• It can also send the messages on networks outside the internet.
• The main purpose of SMTP is used to set up communication rules between servers.
TCP/IP (Transmission Control Protocol/ Internet Protocol)
 It is a set of standardized rules that uses a client-server model of communication in which a user
or machine (a client) requests a service by a server in the network.
 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.
 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.
POP3
Post Office Protocol version 3 (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
HTTPS
The more secure and advanced version is HTTPS. It is used for secure communication over a computer
network.
HTTPS provides,
 Encryption: Encrypting the exchanged data to keep it secure from eavesdroppers.
 Data integrity: Data cannot be modified or corrupted during transfer.
 Authentication: Proves that your users communicate with the intended website.

74
Telnet
 The main task of the internet is to provide services to users. For example, users want to run
different application programs at the remote site and transfers a result to the local site. This
requires a client-server program such as FTP, SMTP. But this would not allow us to create a
specific program for each demand.
 The better solution is to provide a general client-server program that lets the user access any
application program on a remote computer. Therefore, a program that allows a user to log on to a
remote computer
VoIP
VoIP stands for Voice over Internet Protocol. It is also referred to as IP telephony, internet telephony, or
internet calling. It's an alternative to a public switched telephone network (PSTN)

INTRODUCTION TO WEB SERVICES

World Wide Web (WWW):


It is a global system of interconnected documents and resources that are accessible over the internet.
It operates on the basis of hypertext links which allows the users to navigate between different
documents and multimedia content.

Hypertext:
The web is built on the concept of hypertext where documents are linked to each other through
hyperlinks. These allow the users to navigate from one place to another.
URL:
Each web page and the resource on the web can be accessed using the unique address called as the URL
(Uniform Resource Locator).

Web Browser:
To access and view web pages on the internet (WWW), we need to have an application named as Web
Browser. There are many web browsers available on the internet like Google Chrome, Microsoft Edge,
and Mozilla Firefox etc.

Web Servers:
These are the computers that host websites and web applications. These respond to requests from
web browsers, and provide the requested web pages and resources back to the users.

Weblinks:
These are the links available within the web pages that allow the users to access the pages that contain
the topic related content.

HTML:
Hyper Text Markup Language (HTML) was developed with a view to structure and organize the static
web pages. These are the symbols and codes that allow the used to develop web pages that can run
over the internet. These define the layout, format, and linking of text, multimedia, and other elements
within a web page. It uses tags for presentation of content.

XML:
Extensible Markup Language (XML) is designed to carry and store data in a structured and platform-
independent format. These use the user-defined custom tags to represent specific data fields and
structures. These are self-descriptive and make it easier for different applications to understand and
interpret data.
75
Websites:
These are the collections of various web pages and data that are accessible for all, and are available on
the internet. Many types of restrictions such as screenshot protections, copying of data can be
implemented on the websites for data protection.

Web Hosting:
This refers to the service of providing storage space, server resources, and internet connectivity to
make websites and web applications accessible to users over the internet. It allows individuals,
businesses, and organizations to publish their websites on the World Wide Web, making them
available to visitors and users worldwide.
 Web hosting companies maintain powerful servers designed to store website files, databases,
and other contents required for website operations.
 These typically handle the maintenance tasks of the registered websites.
 These ensure proper backup and recovery of the lost data (if any) while accessing it, and cope
up with potential threats that can destroy data.

Domain Name Service (DNS):


It is a vital internet infrastructure that converts domain names into IP addresses, thereby enabling the
users to navigate the web using easily recognizable and memorable names instead of numerical IP
addresses.

Internet Protocol (IP) Address:


It is a unique serial number assigned to devices on a network, facilitating communication and data
exchange between them over the internet, and other IP based networks. These are of two types:
 IPv4:
These are the addresses that consist of 32-bit addressing scheme. Example:
192.168.0.24
 IPv6:
This uses 128 bit addressing scheme represented by eight groups of hexadecimal digits separated
by colons. Example: 2001:0db8:85a3:0f00:00a0:8a2e:0370:7334.

The potential growth of internet-connected devices led to exhaustion of available IPv4 addresses. To
cope up with this problem, the IPv6 addressing scheme was introduces that provides a significantly
large pool of IP addresses to accommodate the expansion of internet.

76
EXPANDED FORMS
ARPANET - Advance Research Project Agency Network
NIU - Network Interface Unit
LAN - Local Area Network
MAN - Metropolitan Area NetworkWAN= Wide Area NetworkISP
- Internet Service ProviderOSS= Open Source Software ISDN
- Integrated Service Digital Network
FLOSS - Free Libre Open Source Software
NIC - Network Interface Card
UTP - Unshielded Twisted Pair
STP - Shielded Twisted Pair
MODEM - Modulator Demodulator
RJ-45 - Registered Jack -45
XML - Extensible Markup Language
FTP - File Transfer Protocol
TCP - Transmission Control Protocol
SMTP - Simple Mail Transfer Protocol
POP3 - Post Office Protocol 3 (Version 3)
IMAP - Internet Message Access Protocol
IP - Internet Protocol
SLIP - Serial Line Internet Protocol
PPP - Point To Point Protocol
PDA - Personal Data Assistant
GSM - Global System For Mobile
SIM - Subscriber Identity Module
CDMA - Code Division Multiple Access
WLL - Wireless In Local Loop
WWW - World Wide Web
URL - Uniform Resource Locator
DHTML - Dynamic Hyper Text Markup Language
OSS - Open Source Software
GNU - GNU’s Not Unix
FSF - Free Software Foundation
OSI - Open Source Initiative
HTTP - Hyper Text Transfer Protocol
HTTPS - Hyper Text Transfer Protocol Secure
HTML - Hyper Text Markup Language
W3C - World Wide Web Consortium
ASP - Active Server Pages
JSP - Java Server Pages

77
Model Questions

Multiple Choice Questions

1. Which one of the following devices will you suggest for connecting all the computers within
each block of a building?
a. Switch/Hub b. Modem
c. Telephone d. Repeater
2. XYZ company is planning to link its head office situated in New Delhi with the offices in hilly
areas. Suggest a way to connect it economically:
a. Micro waves b. Coaxial cable
c. Fibre optic d. Radio waves
3. Which of the following is/are not communication media?
a. Microwaves b. Optical Fiber cable
c. Node d. Radio waves
4. The ........................... is over which the messages are sent.
a. Signal b. Channel
c. Protocol d. Sender
5. Which of the following is not a unit of data transfer rate?
a. Abps b. Bps
c. Kbps d. Gbps
6. The number of bits transmitted per second is called .
a. Bit rate b. Baud rate
c. Data rate d. Transfer rate
7. The messages sent over a network are divided into small pieces called .
a. Units b. Chunks
c. Packets d. Bits
8. A ............................. is established in circuit switching before actual communication.
a. Switch b. Link
c. Protocol d. Hub
9. The is the difference between upper and lower frequencies of a communication medium.
a. Bandwidth b. Data rate
c. Latency d. communication speed
10. The unit of Bandwidth is?
a. Khz b. Hz
c. Watt d. KW
11. For every device connected to a network, there will be a unique _ _.
a. Name b. ID
c. IP Address d. IC

12. Raw data is processed to get .


a. File b. Information
c. Communication d. Message
13. Which of the following is/are true regarding packet switching?
1. The packets of data are sent simultaneously through different paths.
2. The free communication channel is utilized properly.
78
3. Protocols are used for the reliable receipt of data at the receiver end.
4. Sequence numbers are assigned to the data packets.
a. Only 1 b. Both 1 & 4
c. Both 2 & 4 d. All of the above.
14. is applicable in the case of long voice data communication.
a. Protocols b. Circuit Switching
c. Packet Switching d. None of these.
15. Which of the following is/are true in the case of IP address?
1. IP address can be used to trace the actual physical location of a device in the network.
2. A printer connected to a network will also have an IP Address.
3. Two devices can have same IP Address.
4. The IP Address can be formed of any number.
a. Only 1 is true b. Only 1 & 2 are true
c. Options 1, 2 and 4 are true. d. All the options are true.
16. Selecting a communication path among multiple available paths is termed as:
a. Transmission b. Reception
c. Switching d. multiplexing
17. The other name for communication medium is:
a. Channel b. Source
c. Hub d. Switch
18.

The above procedure occurs in the case of .


a. Packet Switching b. Circuit Switching
c. Both a and b d. None of these.
19. 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
20. What is the acronym for LAN?
a. Local Area Network b. Local Access Network
c. Line And Networking d. Line-less Networking

21. 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
22. 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
79
c. WAN d. SAN
23. WAN covers a larger geographical area than MAN?
a. True b. False
24. A network that consists of both LANs and MANs is called a Wide area network?
a. True b. False
25. 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
26. 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
27. What is the acronym MAN stand for?
a. Magnetic Access Network b. Metropolitan Area Network
c. Multi-Area Network d.. Multi-Access net
28. 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
29. Types of Networks are Categories by their Geographical Area cover?
a. True b. False
30. Metropolitan Area Network Normally Require an Internet connection?
a. True b. False
31. 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
32. 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

33. 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
34. Which of these tech company owns Firefox web browser?
a) Lenovo b) IBM
c) Apple d) Mozilla
35. Which of the following browsers were/are available for the Macintosh?
a) Opera b) Safari
c) Netscape d) All of these
36. What is the name of the browser developed and released by Google?
a) Chrome b) Googly
c) Heetson d) Titanium
37. Which of the following is a Web Browser?
a) MS-office b) Notepad
c) Firefox d) Word 2007

80
38. Which of the following is not a web browser?
a) Chrome b) Microsoft Edge
c) Safari d) Ubuntu
39. URL stands for
(a) Uniform Research Limited (b) Uniform Resource Locator
(c) Uniform Resource Labs (d) Uniform Research Locator
40. LinkedIn is an example for ............... website.
(a) E-learning (b) E-commerce
(c) Video conferencing (d) Social networking
41. Which of the following is not a web service?
(a)Distance Learning (b) E-mailing
(c) Video conferencing (d) Social networking
42. Web browsers are also called as …………………
(a) Web Servers (b) Web Clients
(c) Web Hosting (d) Web Designing
43. W43orking of WWW based on .............................. architecture.
(a) Peer-To-Peer architecture (b) Client-Client architecture
(c) Client-Server architecture (d) Server-Server architecture
44. … .......................... 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
45. 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

46. … ..................... is a mark-up language that helps in developing web pages.


(a) HTTP (b) HTML
(c) XML (d) C++
47. … ..................... is a language used to transport data over internet.
(a) HTTP (b) HTML
(c) XML (d) C++
48. … ............................. is a set of rules for communication between two computers over a network.
(a) Modem (b) Protocol
(c) Switch (d) IP address
49. In web services, the communication takes place between
(a) Two electronic devices (b) Two human beings
(c) Two spiders (d) None of the above
50. Web services means services provided by
(a) Microsoft (b) Google
(c) BSNL (d) World Wide Web

81
VERY SHORT ANSWER TYPE QUESTIONS(1-MARK)

• Give examples for Wired media and Wireless media.


• Name the device which connects multiple nodes to form a network. It redirects thereceived
information only to the intended node(s).
• Identify odd one out of the following:
Optical Fiber/Coaxial Cable/ Bluetooth/Twisted Pair Cable. Give reason for your answer.
• Ms. Emily is planning to connect 20 computers in her computer lab to form a local areanetwork.
Suggest an intelligent network device to connect all the computers.
• Which communication channel is/are suitable in each of the following situations?
Transfer of data from one mobile to another.
Communication in a hilly area.
• Tagore Consultancy is planning to link its head office at Kolkata with the offices at Ernakulam.
Suggest an economic way to set up a connection between these offices. The company is ready to
compromise on the speed of the connectivity.
• Mr. Roy, General Manager of Infopark Solutions discovered that the communication between his
company’s main office and HR office is extremely slow and signals drop quite frequently. These
offices are 150 meters away from each other and connected by an Ethernet cable. Suggest him a
device which can be installed between the offices for smooth communication.
• Name the transmission media best suitable for connecting to hilly areas.
• How many pair of wires is there in twisted pair cable (Ethernet)?
• Name a device that forwards data packets along networks.
• What is the full form of WWW?
• What is the full form of Internet?
• Who invented the WWW in 1989?

• Special software’s that is used to view webpages are
• are used to store webpages, so whenever a request, it will serve the request.
• are programs /computers used to store information’s in the form of webpages.
• Web pages that are linked to each other via _
• _ protocol is used to transfer web pages over internet.
• Full form of HTTP?
• is a massive collection of digital pages to access information over the Internet
• Write any 2 differences between HTML & XML?
• is a real-time communication between two or more users via computer.
• helps us to learn anywhere using Internet.
• allows customers to conduct financial transactions on a secure Website.
• Internet can be used to get reservation of trains and air planes through
service.
• helps to create and maintain social relationship over web.
• Expand the following abbreviations:
HTTP
XML
HTTPS
HTML

82
VoIP
• Name any two common web browsers.
• Full form of Email is
• 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
• Match the following

Web Services Description


Video conferencing Without ever having to go booking office
E-Shopping Self-paced learning modules allow students to
work at their own speed
Each of the end user has a camera as well as
E-mail microphone to capture video and audio in real
time and it will be transmitted over internet
E-reservation Purchasing products through computers/mobile
devices
E-learning Messages normally reaches a recipients account
within seconds

• 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

SHORT ANSWER TYPE (THEORY WITH ANSWERS)

1 Your friend wishes to install a wireless network in his office. Explain him the difference between
guided and unguided media.
Ans Guided media uses cables to connect computers, whereas unguided media uses
waves
2 What are Protocols? Name the protocol used to transfer a file from one device to the other.
Ans 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)
3 Define communication channel.
Ans A communication channel is the medium through which data is moved from the source to
destination. The communication channel can be either wired or wireless. Wired communication
channel is also called guided medium while wireless communication channel is also called
83
unguided medium.
4 What do you mean by an IP Address? Give an example for IP Address.
Ans 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.
An example IP Address format is given below: 192.158.12.38
5 Differentiate between Circuit Switching and Packet Switching.
Ans In Circuit Switching a physical connection between the sender and the receiver is set up first.
Then, through that physical link, the complete message is communicated continuously. After
completion of the transmission, the physical connection is terminated. In Packet Switching, the
message is split into small units called packets. Then these packets are passed from source to
destination simultaneously through different routes in the network. As the flow of packets are
asynchronous, sequence numbers are assigned to
each packet to facilitate re-ordering of packets at the destination.
6 Define the following: a. Bandwidth b. Data rate
Ans Bandwidth: It is the range of frequencies that can be carried through a communication channel.
The bandwidth of a channel determines its capacity. It is the difference between the highest and
lowest frequencies that can be carried through the channel. The unit of Bandwidth is Hertz (Hz).

Data transfer rate: It is the amount of data moved through a communication channel per unit
time. The units of Data transfer rate are Bits per second (Bps), Kilobits per second (Kbps) ,
Megabits per second (Mbps) or Gigabits per second (Gbps).
7 Explain the components of data communication.
Ans The components of data communication are: Sender, Receiver, Message, Communication
Medium and Protocols.
Sender: The device which sends data through a network is called sender or source.
Receiver: The device which receives data through a network is called receiver or destination.
Message: The data that is communicated between the source and the destination is called
message.
Communication channel: The medium through which the data is carried from the source to
destination is called a communication medium.
Protocols: The set of rules followed while communicating data over a network are called
Protocols.
8 What are the advantages of Packet switching over Circuit switching.
Ans In Packet Switching the communication channel is utilized completely whenever it is free.
Where as in Circuit Switching, once the connection is assigned for a particular communication,
the entire channel cannot be used for other data transmissions even if the channel is free.
Data packets moves simultaneously through different paths in a Packet Switched network,
making the transmission quick and easy. But in the case of Circuit Switched network, there is a
delay in setting up a physical connection between the source and destination before
communicating the actual message.
Packet Switching is cost effective compared to Circuit Switching as there is no need to set up a
connection between the communicating parties every time before the actual communication.
9 Explain why Circuit Switching is not cost effective compared to Packet Switching?
Ans The Circuit Switching is not cost effective like Packet Switching because, in Circuit Switching,
every time there is a need to set up a connection between the sender and the receiver before
communicating the message.
10 Explain how an IP Address become helpful in investigating cyber-crimes.
Ans 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.
11 Why Protocols are needed in the case of Data Communication?

84
Ans 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
12 What is the difference between World Wide Web & Internet?
Ans 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.
13 What is a protocol, give some examples?
Ans 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)

14 What is the difference between E-mail and chat?


Ans 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.
15 What are cookies?
Ans 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.
16 What is the difference between domain name and IP address?
Ans 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).
17 Give one suitable example of each URL and domain name?
Ans URL: https://kvsangathan.nic.in/hq-gyan-kosh
Domain name: kvsangathan.nic.in
18 Differentiate between XML and HTML.
Ans 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.
19 Distinguish between website and web browser.
Ans 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.
20 Differentiate between the terms Domain Name and URL in context of web services. Also write
one example of each to illustrate the difference.
Ans
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.

85
Example: kvsangathan.nic.in Example: https://kvsangathan.nic.in/contact-us
21 Differentiate between communication using Optical Fiber and Ethernet Cable in context of wired
medium of communication technologies.
Ans 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

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 (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 transmissionbetween server and
browser with the help of encryption?
a) HTTP b) HTTPS c) TELNET d) ARPANET
6) Devanand, a student of Class XII, is not able to understand the difference betweenweb 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 toother
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 XML was not designed to _
(a) store the data (b) present the data
(c) carry the data (d) both a & c

86
17) 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
18) What kind of data gets stored in cookies and how is it useful?
19) What do the following top level domains signify?
a) .com b).org
20) “With XML you invent your own tags”, Explain this statement with the help of example.
21) Define Domain Name Resolution?
22) …………………. tags are case sensitive and ....................... tags are not casesensitive.
(a) HTML, XML (b) HTTP, XML
(c) XML, HTTP (d) XML,HTML
23) Which of the following is not a web browser ?
(a) Google Chrome (b) Internet Explorer
(c) Mozilla Firefox (d) Photoshop
24) Which protocol helps us to browse through web pages using internet browsers?
25) Name any one internet browser.
26) XML stands for
a) Xtra Markup Language
b) Extensible Markup Language
c) Extensible Marking Language
d) Extensive Marked Language
27) We can upload a file to a web server using a protocol called …………………..
(A) FPT (B) IP (C) TCP (D) FTP
28) .................... delivers the requested web page to web browser.
29) MyPace University is setting up its academic blocks at Naya Raipurand is planning to set up a
network. The University has 3 academicblocks 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:

87
Law Block 15
Technology Block 40
HR center 115
Business Block 25

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 wiredconnectivity.
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
88
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 specifytopology.
(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 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 YOURSELF: PART II

1. The ‘Grand Plaza ’ Mall has a computer network. The network is in one building. Namethis 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 neededwhich
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. Dinesh 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
89
Number of Computers
Accounts 25
Research Lab 100
Store 15
Packaging Unit 60

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

ii) Suggest the most suitable place (i.e. buildings) to house the server of thisorganization.

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.

90
ANSWER KEY

Multiple Choice Questions(MCQ)

1. a 2. d 3. c 4. b 5. a
6. a 7. c 8. b 9. a 10. b
11. c 12. b 13. d 14. b 15. c
16. c 17. a 18. b 19. c 20. a
21. a 22. b 23. a 24. a 25. d
26. d 27. b 28. a 29. a 30. a
31. d 32. c 33. b 34. d 35. b
36. a 37. c 38. d 39. b 40. d
41. a 42. b 43. c 44. b 45. d
46. b 47. c 48. b 49. a 50. d

Very Short Answer Type Questions(1-mark)

1. Wired media: Optical Fiber cable Wireless media: Microwaves, Radio waves
2. Switch
3. Odd one: Bluetooth(Reason: Bluetooth is a wireless/unguided communication
media while others are wired/guided communication media)
4. Switch
5. (i) Bluetooth (ii). Radio waves
6. Satellite
7. Repeater
8. Microwave / Radio wave
9. Two insulated copper wires
10. Router
11. World Wide Web
12. Interconnected Networks
13. Tim Berners-Lee
14. Web browsers
15. Web servers
16. Web servers
17. hyperlinks
18. HTTP- HyperText Transfer Protocol

91
19. HyperText Transfer Protocol
20. World Wide Web(WWW) or Web
21. Refer comparison table
22. Chat
23. E-learning
24. Internet banking
25. E-reservation
26. Social networking websites
27.
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
28. Google Chrome, Mozilla Firefox
29. Electronic mail
30. Ii.VoIP
31.
A Video P Each of the end user has a camera as well asmicrophone to capture video
conferencing 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

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

92
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.
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 multipleclients)
14. (b) (i) and (iv)
15. (c) Mark-up Languages

93
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 identifiableinformation
(such as your name, home address, email address, or telephone number). Cookies often
store your settings for a website, such as your preferred language orlocation. When you
return to the site, browser sends back the cookies that belong to thesite. 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 IPaddress
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
30 a. Most suitable place to install the server is HR center, as this center has maximumnumber of
computers.
b.

c. Switch
94
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, thebus 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, detectionof 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 isrequired.
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. Itacts as an interface between computer and the network.
(ii) A repeater is a device that amplifies a signal being transmitted on the network.

95
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/

96
DATABASE
A database is an organised collection of interrelated data that serves many applications.
Its is generally a computer record keeping system. In a database we can not only store the data but we
can also change the data as per the user requirement.
These databases are generally managed by special software called DBMS (Database Management
System)

Database Management System (DBMS):


It is software which is responsible for storing, manipulating, maintaining and utilizing the databases.

Database System:
A database along with the DBMS is referred to as database system

Various DBMS software’s available in the mark are:


Oracle, MySQL Server, MySQL, Sybase, SQLite, PostgreSQL, FoxPro, SAP , dBase

Need for DBMS:


1. Databases reduce redundancy i.e. it removes the duplication of data.
2. Database controls inconsistency i.e. when two copies of the same data do not agree to each
other it is called inconsistency. By controlling redundancy, the inconsistency is also controlled
3. Databases allows sharing of data
4. Database ensures data security by the process of authentication and does not allow unauthorized
access.
5. Database Maintains integrity
6. Database is maintained in a standard format which helps to interchange the data between two
systems.

Relational Database Model


In Relational Database Model the data is stored in the form of tables i.e. rows and columns.
In Relational Database Model a table is referred to as a Relation.

In Relation Database Model a column is referred to as an attribute


In relational database model a row is referred to as a tuple.

97
Eg.
Table: Student (Relation)
Attributes

Rollno Name Marks


Tuples
101 Manish 34

102 Mohit 37
103 Aryan 23

104 Ruhi 56

Various other terminologies used in relational data model


Domain: The pool of all the possible values that a column can have is referred to as a domain.
Degree of a Relation: Number of attributes/columns in a relation is referred to as degree of a
relation. For example if a table has 6 columns then the degree of a table will be 6

Cardinality of a Relation: Number of rows /tuples in a relation is referred to as the cardinality of a


relation.

KEYS:

In a relation each record should be unique i.e. no two records can be identical in a database. A key
attribute identifies the record and must have unique values

Keys are of four types:


1. Primary Key
2. Candidate Key
3. Alternate Key
4. Foreign Key

98
Primary Key:
A primary key uniquely identifies each row in a table. A primary key cannot have NULL value. In a table
we can only have one primary key. Eg. in the above table empno is the primary key.
Candidate Key:
All the attributes in a table which have the capability to become a primary key are referred to as a
candidate key.eg. in the above table empno and ename are the attributes which have the capability to
become the primary key so, empno and ename are the candidate keys
Alternate key:
One of the candidate key is made a primary key and all the other remaining candidate keys are called
alternate keys
Eg. if empno is the primary key then the remaining candidate key ename is the alternate key.
Foreign key:
A foreign key is a non key attribute whose values are derived from the primary key of another table.
It is basically used to set the relationship among two tables.
Eg.

99
SQL COMMANDS
DATA DEFINITION LANGUAGE

CREATE DATABASE<DATABASENAME>; To create a database in the system


SHOW DATABASES; To view the names of all databases in the
system
USE<DATABASENAME>; To open a particular database
DROP DATABASE<DATABASENAME>; To remove a database from the system
DESCRIBE TABLE<TABLENAME>; To view the structure of a table
SHOW TABLES; To view the names of tables in current
database
CREATE TABLE<Tablename> To create a new table in the current
( database:
attributename1 datatype(size) constraint, For example :
attributename2 datatype(size) constraint, CREATE TABLE EMP
. (
. EMPID INT PRIMARY KEY,
); ENAME CHAR(30) NOT NULL,
POST VARCHAR(15)
);
ALTER TABLE To modify the structure of a table
ALTER TABLE<TABLE NAME> ADD ATTRIBUTENAME For adding attributes
DATATYPE(SIZE);
ALTER TABLE<TABLENAME>DROP <ATTRIBUTENAME>; For deleting attribute
ALTER TABLE<TABLENAME>MODIFY For changing datatype, size etc. of an
attribute
DROP TABLE<TABLENAME> To remove a table from the databse

DML: DATA MANIPULATION LANGUAGE

INSERT INTO <TABLENAME> VALUES (VAL1,VAL2…); To add new record/row/tuple/ in the


table
DELETE FROM <TABLENAME> WHERE<CONDITION>; to remove tuples from a table
UPDATE <TABLENAME> To modify or change the data in the table
SET<ATTRIBUTENAME>=NEWVALUE
WHERE <CONDITION>;
SELECT <ATTRIBUTE LIST> To view / extract rows from a table
FROM <TABLENAME>
WHERE <CONDITION>;
MYSQL : MATH FUNCTIONS

POW(X,Y) - x raise to the power of y Select Pow(8,2); → 64


MOD(X,Y) - Remainder of X/Y Select MOD(30/12) → 6
ROUND(N,D) - Rounds number N upto given D no. of digits Select Round(2123.7898,2); → 2123.79
SQRT(X) – Returns square root of X Select SQRT(100): → 10

MYSQL : STRING FUNCTIONS

100
LENGTH(STR) : Select LENGTH(‘SPACE’)
Find Number of characters in given string. &5
CONCAT(STR1,STR2,STR3….) : Select CONCAT('Wel', 'come');
Joins the given strings one after the other. & 'Welcome'
UPPER(STR)/UCASE(STR): Select UPPER('Kendriya')
Converts lower case alphabets of given string alphabets to & 'KENDRIYA'
Upper case. Other charters remain as it is. Select UPPER('orange') → 'ORANGE'
LOWER(STR)/LCASE(STR) : Select LOWER('Kendriya')
Converts Upper case alphabets of given string alphabets to → 'kendriya'
lower case. Other charters remain as it is. Select LOWER('ORANGE')
→ 'orange'
LTRIM(STR): Select LTRIM(‘ I am learning ‘);
Removes Spaces on left side of given string. & ‘I am learning ‘
RTRIM(STR) : Select RTRIM(‘ I am back ‘);
Removes Spaces on Right side of given string &‘ I am back‘
TRIM(STR) : Select TRIM(‘ ROSE IS RED ‘)
Removes both leading (left) and Trailing (right ) Spaces & ‘ROSE IS RED ‘
from given string.
LEFT(STR,N) : Select LEFT('GREAT WORK',4)
extract N characters from left side of given String & 'GREA'
RIGHT(STR,N) : Select RIGHT('PYTHON',4)
extract N characters from right side of given String & 'THON'
INSTR(STR,SUBTRING) : Select INSTR("apple", "p");
returns the position of the first occurrence of a string in &2
another string.
SUBSTR(STR, position, no. of characters) or MID(STR, Select MID('Kendriya',4,2)
position, no. of characters) & 'dr'

101
Multiple Choice Questions
1 Fill in the blank:
is a non-key attribute, whose values are derived from the primary key of some other
table.
(A) Primary Key (B) Candidate Key (C) Foreign Key (D) Alternate Key
2 An Attribute in a relations a foreign key if it is the key in any other relation.
(A) Candidate Key (B) Foreign Key (C) Primary Key (D) Unique Key
3 An attribute in a relation is a foreign key if it is the key in any other relation.
(A) Candidate Key (B)Foreign Key (C) Primary Key (D)Unique Key
4 is an attribute, whose values are Unique and not null.
(A) Primary Key (B)Foreign Key (C)Candidate Key (D)Alternate Key
5 Select the correct statement, with reference to RDBMS:
a) NULL can be a value in a Primary Key column
b) ' ' (Empty string) can be a value in a Primary Key column
c) A table with a Primary Key column cannot have an alternate key.
d) A table with a Primary Key column must have an alternate key.

6. Layna creates a table STOCK to maintain computer stock in vidyalaya. After creation of the table, she
has entered data of 8 items in the table.

Based on the data given above answer the following questions:


(i) Identify the most appropriate column, which can be considered as Primary key.
(ii) What is the degree and cardinality of the given table.
(iii) If three columns are added and 5 rows are deleted from the table stock, what will be the new
degree and cardinality of the above table?
7. What is the difference between primary, candidate and alternate key? Explain with the help of an
example.
8. Name any two RDBMS software.
9. Rahul is confused between tuple and attributes help him to define Tuple and Attribute with
appropriate example.
10. What is the difference between the cardinality and degree of a relation?

102
STRUCTURED QUERY LANGUAGE (SQL)
Structured query language (SQL) is a programming language for storing and processing information in a
relational database. A relational database stores information in tabular form, with rows and columns
representing different data attributes and the various relationships between the data values.
By using SQL commands, one can search for any data in the database and perform other functions like
creating tables, adding records, modifying data, removing rows, dropping tables etc.
Relational Data Model
In this model data is organized into tables. These tables are called relations. Rows of table are known as
tuples and columns are known as attribute.
Domain:
It is a pool of values from which the actual values appearing. For example if there 40 students having
rollno 1 to 40 and we assigning work to these students then domain for rollno is 1 to 40
Tuple: Tuples are row of a table.
Attribute: Attributes are column of relation.
Degree: Total number of attributes (Column) in a table are known as Degree.
Cardinality:
Total number of tuples (Row) in a table are known as Cardinality. Heading row is not included while
calculating cardinality of a table
Candidate Key:
A Candidate Key is the one that is capable of becoming Primary key i.e., a column that has unique value
for each row in the relation and that can not be NULL.
For example if there is a table student having columns (Rollno , AdmNo, Name , fees ,city and DOB) . In
this table Rollno and AdmNo both columns have all the properties to become primary key of table. That
is why Rollno and AdmNo are known as Candidate key.
Primary Key:
It is set of one or more columns that can uniquely identify tuples with in the relation. It cannot be null.
For example in student table RollNo is selected as Primary key.
Alternate Key:
A candidate key that is not primary key is called alternate key. Example is AdmNo because it is candidate
key but not selected as primary key.
Foreign Key:
A non-key attribute of a table , which is primary key in another table. The values of foreign key are
derived from the primary key of base table. For example we are having a table Library having columns
BookNo, BName, RollNo)
Here Bookno is Primary key
RollNo is Foreign key in Library table as it is primary key in student table.

103
SQL Commands

SQL commands are instructions. It is used to communicate with the database. It is also used to perform
specific tasks, functions, and queries of data.
SQL can perform various tasks like create a table, add data to tables, drop the table, modify the table, set
permission for users.
Types of SQL Commands. There are four types of SQL commands: DDL, DML, DCL, TCL

DDL :- Create , Drop, Alter , Describe

DML-Insert, Update, Delete , Select

DCL- Grant , Revoke

TCL- Commit , Rollback

DDL or Data Definition Language

DDL or Data Definition Language actually consists of the SQL commands that can be used to define the
database schema. It simply deals with descriptions of the database schema and is used to create and
modify the structure of database objects in the database. DDL is a set of SQL commands used to create,
modify, and delete database structures 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.

DESC: This is used to DESCRIBE the structure of table.

DML (Data Manipulation Language):

The SQL commands that deals with the manipulation of data present in the database belong to DML or
Data Manipulation Language and this includes most of the SQL statements. It is the component of the SQL
statement that controls access to data and to the database. Basically, DCL statements are grouped with
DML statements.

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.
SELECT: It is used to display records on screen.

104
DATA TYPES

Data types are means to identify the type of data and associated operations for handling it.
MySQL data types are divided into following categories:

Data type Description

CHAR(size) A FIXED length string its size can be from 0 to 255. Default is 1

VARCHAR(size) A VARIABLE length string, its size can be can be from 0 to 65535

INT(size)/ Integer Number without decimal point. Example int(11) or integer

FLOAT(size, d) / A floating point number. The total number of digits is specified in size. The
Decimal number of digits after the decimal point is specified in the d parameter.
Example float(10,2) . Example 3455738.50

A date. Format: YYYY-MM-DD.


DATE
Example DOB date

value should be given like ‘2024/06/25’

DATABASE COMMANDS

1. VIEW EXISTING DATABASE


To view existing database names, the command is:
SHOW DATABASES;
2. CREATING DATABASE IN MYSQL
For creating the database in MySQL, we write the following command:
CREATE DATABASE <databasename>; e.g.In order to create a database Student, command is:
CREATE DATABASE Student;
3. ACCESSING A DATABASE
For accessing already existing database,we write:
USE<databasename>;
e.g.to access a database named Student, we write command as:
USE Student;

4. DELETING DATABASE
105
For deleting any existing database,the command is:
DROP DATABASE <databasename>;
e.g.to delete a database, say student, we write command as:
DROP DATABASE Student;

5. VIEWING TABLE IN DATABASE


In order to view tables present in currently accessed database, command is:
SHOW TABLES;
DDL COMMANDS :-

CREATING TABLES IN MYSQL


Syntax of CREATE TABLE command is:

CREATE TABLE <table-name>(<colname> datatype,<colname> datatype,…);


E.g. In order to create table EMPLOYEE given below:
ECODE ENAME GENDER GRADE GROSS

Create table employee (ecode integer, ename varchar(20),gender char(1),grade char(2),gross integer);
ALTER TABLE
ALTER TABLE command is used to change the structure of the existing table. It can be used to add or drop
new columns or modify the existing columns of table.
Eg. 1. Alter table Employee Add email char(20);
2. ALTER TABLE Employee MODIFY (ename varchar(60));
2. Alter table employee drop email;

DROP TABLE:
DROP TABLE command allows to remove a table from database. Once the DROP command is issued, the
table will no longer be available in the database.
Eg. DROP TABLE employee;
DESC TABLE:
DESC TABLE command display the structure of table on screen.
Eg. DESC employee;

DML Commands

106
INSERTING DATA INTO TABLE:
Syntax:
Insert into <tablename> values(<v1>,<v2>,…);
Or
Insert into <tablename>(<column list> )values(<values list>);
Eg: insert into employee values(1001,‘Atul’,‘M’,‘E4’,50000);
Or
Insert into employee(ecode,ename) values (1002,’Meena’);
The left out columns will be filled with null values.
DELETE Command

This command removes rows from a table.


Syntax: DELETE FROM <tablename> [WHERE <cond>];
Eg: To remove all the contents of items table, the query is:
DELETE from items;
Eg: To remove the tuples from employee that have gross less than 20000 is :
DELETE from employee WHERE gross<20000;

UPDATE Command
Update Command allows to change some or all the values in an existing rows. Update command specifies
the rows to be changed using the WHERE clause and the new data using the SET keyword.
Eg. UPDATE employee SET gross= 25000;
The above query sets the gross of all records as 25000.
UPDATE employee SET gross=40000, grade=’A’ WHERE ecode=1001;
The above query changes the gross and grade values for the record with ecode 1001.
SELECT COMMAND:
It helps to display the records as per our requirement.
Different forms of select command:
1. Select * from employee;
It displays all rows and columns from the table.
2. SELECT ECODE, ENAME FROM EMPLOYEE;
It displays selected columns from the table.

3. FOR DISPLAYING PARTICULAR ROWS.


Syntax: select * from <tablename> where <cond>; Eg. Select * from employee where gender=’M’;

107
4. ELIMINATING REDUNDANT DATA

The distinct keyword is used to eliminate duplicate records from the table. Eg. Select distinct (gender)
from employee;

DISTINCT(GENDER

5. USING COLUMN ALIASES


The columns that we select in a query can be given a different name, i.e.column alias name for output
purpose.
Syntax: SELECT <columnname>AS column alias ,<columnname>AS column alias
…..FROM<tablename>;
Eg.select ecode as “EMP_Code” from employee;

CONDITION BASED ON A RANGE


The BETWEEN operator defines a range of values that the column values must fall into make the
condition true. The range include both lower value and upper value.
e.g.To display ECODE,ENAME and GRADE of those employees whose salary is between 40000 and
50000,command is:

SELECT ECODE , ENAME ,GRADE FROM EMPLOYEE WHERE GROSS BETWEEN 40000 AND 50000;
NOTE: For displaying records not in the specified range, we have to use not between operators.

CONDITION BASED ON A LIST

The in operator is used to display records based on a list of values.


Eg. To display details of employees who have scored A,B and C grades.
Select * from employee where grade in (‘A’,’B’,’C’);
Note: For displaying records that do not match in the list, we have to use not in operator.
CONDITION BASED ON PATTERN MATCHES

LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard
characters: % and _ (underscore)
1. Percent ( % )– The % character matches any substring.
2. Underscore ( _ )– The _ character matches any single character.

e.g.To display names of employee whose name starts with R in EMPLOYEE table, the command is:
select ename from employee where ename like “R%”;
e.g. To display details of employee whose second character in name is:
108
select * from employee where ename like ‘_e%’;
SEARCHING FOR NULL

The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause. E.g. to list
employee details whose salary contain NULL, we use the command:
Select * from employee where gross is null;

Note: For listing employees who earn salary, then it is:

Select * from employee where gross is not null;

Relational Operators

 To compare two values, a relational operator is used. The result of the comparison is true or false.
Relational Operators recognized by SQL: =, >, <, <=, >=, <> (not equal or !=)
Eg. Select * from employee where ecode <> 1001;
Above query will not display those employee details whose ecode column value is 1001.
Logical Operators- (OR, AND, NOT)

1. To list the employee details having grades E2 or E3.


Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);
2. To list all the employees’ details having grades as ‘E4’ but with gross < 9000.
Select ecode, ename, grade, gross from employee where grade=‘E4’ and gross< 9000;
3. To list all the employees’ details whose grades are other than ‘G1’.
Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);
Sorting Results- ORDER BY clause
Results of SQL query can be sorted in a specific order using ORDER BY clause.
The ORDER BY clause allows sorting of query results by one or more columns. The sorting can be done
either in ascending or descending order.
Eg. Select * from emp order by ename;
Above query arranges the records in alphabetical order of ename value. By default order by clause
arranges in ascending order.
 Select * from employee order by ename desc;
Above query gives output in descending order of ename.

 Select * from employee ORDER BY ename ASC;


 Above query gives output in ascending order of ename.

SQL AGGREGATE FUNCTIONS:

109
FUNCTIONS: In MYSQL function is a special type of predefined command set that perform some
operation andreturn a single value. The value that are provided to functions are called parameters or
arguments.
Functions can be divided into two categories.
1. Single row function :- This type of function can apply on each row of table.Example are
(a ) Lower/Lcase: This function convert a string into lower case.Example :
Select Lower(name) from student;

2. Group Row Function : These function can work on group of rows and give you a single result.
(1) AVG ( ) – This function computes the average of given data.

Example : Select avg(fees) from student ;

Avg – to compute average value


Min – to find minimum value
Max – to find maximum value Sum – to find total value

Count – to count non-null values in a column


Count( *) – to count total number of rows in a table including null values.
All the aggregate functions ignore null values except count(*).

Examples:
Select avg(gross) from employee;

Select min(gross) from employee where deptno= 10;


Select count(*) from emp where gross> 10000;
Select count (DISTINCT gender) from employee;
GROUP BY Clause
GROUP BY clause is used in SELECT statements to display the table contents based on similar values in a
column into groups.

Eg: To calculate the number of employees in each grade, the query is:
SELECT grade, count(*) from employee group by grade;
Placing conditions on Groups HAVING Clause
 The HAVING clause places conditions on groups in contrast to WHERE clause that places conditions on
individual rows.
 WHERE conditions cannot include aggregate functions but HAVING conditions can do so.

Eg: SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’ ;
INTEGRITY CONSTRAINTS

110
A constraint is a condition or check applicable on a field or set of fields. Common types of constraints
include:

S.No Constraints Description

1 NOT NULL Ensures that a column cannot have NULL value

2 DEFAULT Provides a default value for a column when none is Specified

3 UNIQUE Ensures that all values in a column are different

4 PRIMARY KEY Used to uniquely identify a row in the table

5 FOREIGN KEY Used to ensure referential integrity of the data

ADDING CONSTRAINT TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table by using it in following
manner:
Eg: alter table employee add primary key(ecode);
REMOVING CONSTRAINTS FROM A TABLE
Eg: alter table employee drop primary key;

SETTING PRIMARY AND FOREIGN KEY CONSTRAINT:


Eg: CREATE TABLE STUDENT(ROLL_NO integer PRIMARY KEY ,NAME VARCHAR(30),CLASSVARCHAR(3));

CREATE TABLE SCORE(ROLL_NO integer ,MARKS integer, FOREIGN KEY(ROLL_NO) REFERENCES


STUDENT(ROLL_NO));
SQL JOINS
SQL Joins are essential to display data from more than one table. SQL JOIN clause is used to combine rows
from two or more tables, based on a common field between them.
SQL provides various types of joins:
1. Cartesian Product or Cross Join
2. Equi-Join
3. Natural Join.
Cartesian Product (Cross Join)
Cartesian product of two tables is obtained by pairing up each row of one table with each row of the
other table.
 The number of columns in the Cartesian product is the sum of the number of columns in both the
tables.
 The number of rows in the Cartesian product is the product of rows of the tables.

Example:
111
If A table has 3 Rows and 4 columns and B table has 6 rows and 7 columns then write No of rows and
columns in C table which is Cartesian product of Table A and B
Answer is Rows = 3 X6= 18
Columns = 4+7=11
Equi-Join
A join which is obtained by putting a condition of equality on cross join is called an 'equi join'.
We can extract meaningful information from the Cartesian product by placing some conditions in the
statement.
The join in which columns are compared for equality is called equi-join.
In this type of join we put * in the select list therefore the common column will appear twice in the
output.
Example: Consider the 2 tables emp and dept.

On performing equi-join, the result is as follows:

Note: We see that deptno column appears twice in output.


Natural Join

112
 The join in which only one of the identical columns exists is called natural join.
 It is similar to equi-join except that duplicate columns are eliminated in natural join that would
otherwise appear in equi-join.
Example:

Note: We see that deptno column appears only once in output.

MULTIPLE CHOICE QUESTIONS (MCQS)

Q1. Which clause is used for Pattern Matching -


(a) between (b) in (c) like (d) Compare
Q2. The default date format in MySQL is:

(a) DD/MM/YYYY (b) YYYY/MM/DD c) MM-DD-YYYY (d) YYYY-MM-DD


Q3. Which is not a way to represent comment in MySQL?
(a) /* */ (b) -- (c) # (d) //
Q4. The command is used to access database in MySQL is-

(a) Open <databasename>; (b) USE <databasename>;


(c) Access <databasename>; (d) (a)&(b) both
Q.5. Which is a valid CREATE TABLE statement?
(a) Create table emp add(id integer(3)); (b) Create table emp(id integers(3));
(c) Create table emp modified(id integer(3)); (d) Create table emp(id integer(3));

Q.6. How can you insert a new row into the “STORE” table.
(a) INSERT ROW(1,‟RAMSINGH‟)INTO STORE; (b) INSERT VALUES(1,‟RAMSINGH‟)INTO STORE;
(c) INSERT INTO(1,‟RAMSINGH‟)STORE; (d) INSERT INTO STORE VALUES(1,‟RAMSINGH‟);
Q.7. which keyword is used to retain duplicate value in select command
(a) distict (b) show (c) all (d) like
Q.8 Conditionally retrieval of rows from a table with SELECT, which clause is used?
(a) Where (b) Having (c) Group By (d) Order by
113
Q.9. The key word eliminates duplicate rows from the result of a SELECT statement.

(a) All (b) Unique (c) Distinct (d) IN


Q10. Which operator defines a range of values that the column values must fall in?
(a) In (b) Like (c) Between (d) Is
Q11. To specify a list of values… ............... Operator is used.
(a) In (b) Like (c) Between (d) Is
Q12. We use operator with select for condition based on pattern matching.

(a) In (b) Like (c) Between (d) Is

Q13. To see all the databases which command is used?

(a)Show database; (b) Show databases; (c) Show database(); (d) Show_all database;

Q14.To display the detail of employee having ‘e’ in their name in descending order of salary. The correct
SQL statement is:
(a) SELECT*FROM emp WHERE ename LIKE “e%” ORDER BY SAL;

(b) SELECT*FROM emp ORDER BY SAL DESC WHERE ename LIKE “%e%”;
(c) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY DESC SAL;
(d) SELECT*FROM emp WHERE ename LIKE “%e%” ORDER BY SAL DESC;

Q. 15. In which form MYSQL query results are displayed?

(a) LIST (b)TUPLE (c) ROWS AND COLUMNS (d) LIST AND TUPLES BOTH

ANSWERS
Q.No. Answers Q.No. Answers
1 c 8 a
2 d 9 c
3 d 10 c
4 b 11 a
5 d 12 b
6 d 13 b
14 d
7 c
15 c

VERY SHORT ANSWER QUESTIONS (VSA)


114
(1 Mark each)
Q1. Answer the following questions:
I. Differentiate between DDL and DML?
II. What is a constraint?
III. What are single row functions ?
IV. Compare CHAR and VARCHAR data types.
V. What are the differences between DELETE and DROP commands of SQL?
VI. What do you understand by MySQL Client?
VII. Differentiate between WHERE and HAVING clause.
VIII. A table "Animals" in a database has 3 columns and 10 records. What is the degree and cardinality
of this table?
IX. What is the difference between commit and rollback command.
X. Which keyword is used to remove redundant data from a relation?
ANSWERS:
(i) Data Definition Language (DDL): This is a category of SQL commands. All the commands which are used
to create, destroy, or restructure databases and tables come under this category. Examples of DDL
commands are - CREATE, DROP, ALTER.
Data Manipulation Language (DML): This is a category of SQL commands. All the commands which are
used to manipulate data within tables come under this category. Examples of DML commands are -
INSERT, UPDATE, DELETE.
(ii) A constraint is a condition or check application on a field or set of fields.
Example: NOT NULL (ensure that column con not have null value), CHECK (make sure that all value
satisfy certain criteria), UNIQUE (ensure that all values in a column are different) etc.
(iii) Single Row Function work with a single row at a time. A single row function returns a result for every
row of a quired table
Examples of Single row functions are Sqrt(), Concat(), Lcase(), Upper(), Day(), etc.
(iv) The CHAR data-type stores fixed length strings such that strings having length smaller than the field size
are padded on the right with spaces before being stored. The VARCHAR on the other hand supports
variable length strings and therefore stores strings smaller than the field size without modification.
(v) DELETE is DML command while DROP is a DDL command. Delete is used to delete rows from a table while
DROP is used to remove the entire table from the database.
(vi) MySQL Clients are programs that connect to MySQL Server and issue queries in predefined format.
(vii) WHERE clause is used to select particular rows that satisfy the condition where having clause is used
in connection with the aggregate function GROUP BY clause. FOR EXAMPLE-
select * from student where marks >80;
Select * from student group by stream having marks>90;
(viii) Degree 3 and Cardinality=10
(ix) COMMIT command permanently saves the changes made during the transaction execution. ROLLBACK
command undoes the changes made during transaction execution.
(x) DISTINCT

115
SHORT ANSWER QUESTIONS
(2 Marks Each)
Q1. Differentiate between Candidate Key and Primary Key in the context of Relational Database Model.
Ans. A table may have more than one or a combination of attribute(s)that identifies a tuple uniquely. All
such attribute(s) are known as Candidate Keys.
Out of all the Candidate keys, the most appropriate one, which is used for unique identification of the
Tuples, is called the Primary Key.
Q2. Sreenath created the following table STUDENT in his database.
Table : STUDENT

Rollno Name CLASS Mark

1 Ritika 12 40

2 Angad 12 35
3 Kaveri 11 42

4 Lalitha 12 21

5 Daniel 11 44

6 Rabindra 11 39

7 Rabia 11 28

He wants to now count number of students in each CLASS where the number of students is more than 3.
He has executed the following query.
SELECT MAX(MARKS) FROM STUDENT WHERE COUNT(*)>3 GROUP BY CLASS;
But, he got an error. Identify the error and rewrite the query.
Ans. To filter more condition with group by clause HAVING clause is used in place of WHERE clause.
Correct query is
SELECT MAX(MARKS) FROM STUDENT GROUP BY CLASS HAVING COUNT(*)>3;
Q.3. Difference between Where and Having Clause
Answer : WHERE Vs HAVING: WHERE is used to put a condition on individual row of a table whereas
HAVING is used to put condition on individual group formed by GROUP BY clause in a SELECTstatement.
Q.4. Difference between alter command and update command
Ans: 1. Alter is a DDL command while update is a DML command
2 Alter command is used to change the structure of table while update is used to change in records
Q.5. Difference between drop command and drop clause of Alter table .
Ans:- Drop command is used to delete the entire table along with its structure while drop clause is used
with alter table command to drop a column or constraints
Q.6. Difference between Unique and Primary Key

Ans. Primary Key: In a table there can be one primary key with one column or one combination of
column. It cannot be Null.
116
Unique: In a table there can be Unique constraints can be applied to any number of columns . It
can have Null values.

Q.7. Define Commit and Rollback Commands


Answer : COMMIT-This statement is used to end a transaction and make all changes permanent. Until
atransaction is committed, other users cannot see the changes made to the database.
ROLLBACK- The ROLLBACK statement is used to end a transaction and undo the work done by
user.
Q.8. Difference between Count(*) and Count(name) Functions.
Answer : COUNT(*) will count all rows in the table. It also include rows having NULL value for the
column.
COUNT(NAME) will count only those rows where value of Name is given. If for any row Name
is NULL/ empty then it will not count it.

Q9. Mr. Roger is using a table LIBRARY. It has the following columns:
BCode, BName, Price, author.
He wants to display maximum price Author wise. He wrote the following command:
SELECT Author, Max(Price) FROM LIBRARY;

But he did not get desired result. Rewrite the above query with necessary change to help him get the
desired output and explain the reason.

Ans. SELECT Author, Max(Price) FROM LIBRARY GROUP BY AUTHOR;

Group By clause is used to group the rows together that contain the same values in a specified
column.so to display maximum price of each author , the table must be grouped author wise using
group by clause.

Q10. Differentiate ORDER BY and GROUP BY with an example.


Ans. Order By: Order by keyword sort the result-set either in ascending or in descending order. This
clause sorts the result-set in ascending order by default. In order to sort the result-set in descending
order DESC keyword is used.
Group By: Group by statement is used to group the rows that have the same value. It is often used
with aggregate functions for example: AVG(), MAX(), COUNT(), MIN() etc.

117
LONG ANSWER QUESTIONS (6 MARKS)

Q.1. Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to(viii), which are basedon the
tables.
TRAINER

TID TNAME CITY HIREDATE SALARY


101 SUNAINA MUMBAI 1998-10-15 90000
102 ANAMIKA DELHI 1994-12-24 80000
103 DEEPTI CHANDIGARG 2001-12-21 82000
104 MEENAKSHI DELHI 2002-12-25 78000
105 RICHA MUMBAI 1996-01-12 95000
106 MANIPRABHA CHENNAI 2001-12-12 69000

COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018-07-02 101
C202 ADCA 15000 2018-07-15 103
C203 DCA 10000 2018-10-01 102
C204 DDTP 9000 2018-09-15 104
C205 DHN 20000 2018-08-01 101
C206 O LEVEL 18000 2018-07-25 105

(i) Display the Trainer Name, City & Salary in descending order of their Hiredate.
(ii) To display the TNAME and CITY of Trainer who joined the Institute in the
month of December 2001.
(iii) To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and COURSE
of all those courses whose FEES is less than or equal to 10000.
(iv) To display number of Trainers from each city.
(v) SELECT TID, TNAME, FROM TRAINER WHERE CITY NOT IN(‘DELHI’, ‘MUMBAI’);
(vi) SELECT DISTINCT TID FROM COURSE;
(vii) SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID HAVING COUNT(*)>1;
(viii) SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE STARTDATE< ‘2018-09-15’;

ANSWER:

(i) SELECT TNAME, CITY, SALARY FROM TRAINER ORDER BY HIREDATE;


(ii) SELECT TNAME, CITY FROM TRAINER WHERE HIREDATE BETWEEN ‘2001-12-01’AND ‘2001-12-31’;
(iii) SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER, COURSE WHERE
TRAINER.TID=COURSE.TID AND FEES<=10000;
(iv) SELECT CITY, COUNT(*) FROM TRAINER GROUP BY CITY;

v) TID TNAME
103 DEEPTI
106 MANIPRABHA

118
vi) DISTINCT TID
101
103
102
104
105
vii) TID COUNT(*) MIN(FEES)
101 2 12000
Viii) COUNT(*) SUM(FEES)
4 65000
Q2. Consider the following tables GAMES and PLAYER. Write SQL commands for the statements to (iv)
and give outputs for SQL queries (v) to (viii).
Table: GAMES

GCode GameName Number PrizeMoney ScheduleDate


101 Carom Board 2 5000 23-Jan-2004
102 Badminton 2 12000 12-Dec-2003
103 Table Tennis 4 8000 14-Feb-2004
105 Chess 2 9000 01-Jan-2004
108 Lawn Tennis 4 25000 19-Mar-2004
Table: PLAYER
PCode Name Gcode
1 Nabi Ahmad 101
2 Ravi Sahai 108
3 Jatin 101
4 Nazneen 103
I. To display the name of all Games with their Gcodes.
II. To display details of those games which are having PrizeMoney more than 7000.
III. To display the content of the GAMES table in ascending order of ScheduleDate.
IV. To display sum of PrizeMoney for each of the Number of participation groupings (as shown in
column Number 2 or 4)
V. SELECT COUNT(DISTINCT Number) FROM GAMES;
VI. SELECT MAX(ScheduleDate),MIN(ScheduleDate) FROM GAMES;
VII. SELECT SUM(PrizeMoney) FROM GAMES;
VIII. SELECT DISTINCT Gcode FROM PLAYER;
ANSWER
I. SELECT GameName,Gcode FROM GAMES;
II. SELECT * FROM GAMES WHERE PrizeMoney>7000;
III. SELECT * FROM GAMES ORDER BY ScheduleDate;
IV. SELECT SUM(PrizeMoney),Number FROM GAMES GROUP BY Number;
V. 2
119
VI. 19-Mar-2004 12-Dec-2003
VII. 59000
VIII. 101
103
108

Q3. Consider the following tables FACULTY and COURSES. Write SQL commands for the statements (i) to
(iv) and give outputs for SQL queries (v) to (vi).

FACULTY

F_ID Fname Lname Hire_date Salary

102 Amit Mishra 12-10-1998 12000

103 Nitin Vyas 24-12-1994 8000

104 Rakshit Soni 18-5-2001 14000

105 Rashmi Malhotra 11-9-2004 11000

106 Sulekha Srivastava 5-6-2006 10000

COURSES

C_ID F_ID Cname Fees

C21 102 Grid Computing 40000

C22 106 System Design 16000

C23 104 Computer Security 8000

C24 106 Human Biology 15000

C25 102 Computer Network 20000

C26 105 Visual Basic 6000

I. To display details of those Faculties whose salary is greater than 12000.


II. To display the details of courses whose fees is in the range of 15000 to 50000 (both values
included).
III. To increase the fees of all courses by 500 of “System Design” Course.
IV. To display details of those courses which are taught by ‘Sulekha’ in descending order of courses?
V. Select COUNT(DISTINCT F_ID) from COURSES;
VI. Select Fname,Cname from FACULTY,COURSE where COURSE.F_ID=FACULTY.F.ID;

120
ANSWER
I. Select * from faculty where salary > 12000;
II. Select * from Courses.where fees between 15000 and 50000;
III. Update courses set fees = fees + 500 where Cname = “System Design”;
IV. Select * from faculty fac,courses cour where fac.f_id = cour.f_id and fac.fname = 'Sulekha' order by
cname desc;
V. 4
VI.

Amit Grid Computing

Rakshit Computer Security

Rashmi Visual Basic

Sulekha Human Biology

Q-4 Write SQL Command for (a) to (e) and output of (f)
TABLE : GRADUATE

S.NO NAME STIPEND SUBJECT AVERAGE DIV


1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMP Sc 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CHEMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMP Sc 62 I
10 VIKAS 400 MATHS 57 II
a) List the names of those students who have obtained DIV I sorted by NAME.
b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend received in a year
assuming that the STIPEND is paid every month.
c) To count the number of students who are either PHYSICS or COMPUTER SC graduates.
d) To insert a new row in the GRADUATE table: 11,”KAJOL”, 300, “computer sc”, 75, 1
e) Add a new column GRADE of character type.
f) Give the output of following sql statement based on table GRADUATE:
I. Select MIN(AVERAGE) from GRADUATE where SUBJECT=”PHYSICS”;
II. Select SUM(STIPEND) from GRADUATE WHERE div=2;
III. Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
IV. Select COUNT(distinct SUBJECT) from GRADUATE;

121
ANSWER
a) SELECT NAME from GRADUATE where DIV = ‘I’ order by NAME;
b) SELECT NAME,STIPEND,SUBJECT, STIPEND*12 from GRADUATE;
c) SELECT SUBJECT,COUNT(*) from GRADUATE group by SUBJECT having
SUBJECT=’PHYISCS’ or SUBJECT=’COMPUTER SC’;
d) INSERT INTO GRADUATE values(11,’KAJOL’,300,’COMPUTER SC’,75,1);
e) ALTER TABLE GRADUATE ADD(GRADE CHAR(2));
f) (i) 63
ii. 800
iii. 475
iv. 4
Q.5. Write SQL queries for (i) to (iv) and find outputs for SQL queries (v) to (viii), which are based on the
tables.
Table : VEHICLE
CODE VTYPE PERKM
101 VOLVO BUS 160
102 AC DELUXE BUS 150
103 ORDINARY BUS 90
105 SUV 40
104 CAR 20
Note : PERKM is Freight Charges per kilometer , VTYPE is Vehicle Type
Table : TRAVEL
NO NAME TDATE KM CODE NOP
101 Janish Kin 2015-11-13 200 101 32
103 Vedika Sahai 2016-04-21 100 103 45
105 Tarun Ram 2016-03-23 350 102 42
102 John Fen 2016-02-13 90 102 40
107 Ahmed Khan 2015-01-10 75 104 2
104 Raveena 2016-05-28 80 105 4
• NO is Traveller Number
• KM is Kilometer travelled
• NOP is number of travellers travelled in vehicle
• TDATE is Travel Date
(i) To display NO, NAME, TDATE from the table TRAVEL in descending order of NO.
(ii) To display the NAME of all the travellers from the table TRAVEL who are travelling by vehicle
withcode 101 or 102.
(iii) To display the NO and NAME of those travellers from the table TRAVEL who travelled
between ‘2015-12-31’ and ‘2015-04-01’.
(iv) To display all the details from table TRAVEL for the travellers, who have travelled distance
more than 100 KM in ascending order of NOP.
(v) Modify the definition of column VTYPE. Increase its size to 20.
(vi) SELECT COUNT (*), CODE FROM TRAVEL GROUP BY CODE HAVING COUNT(*)>1;
(vii) SELECT DISTINCT CODE FROM TRAVEL;
(viii) SELECT A.CODE,NAME,VTYPE FROM TRAVEL A,VEHICLE B WHERE A.CODE=B.CODE ANDKM<90;
122
ANSWER
(i) SELECT NO, NAME, TDATE FROM TRAVEL ORDER BY NO DESC;
(ii) SELECT NAME FROM TRAVEL WHERE CODE=‘101’ OR CODE=’102’; or
SELECT NAME FROM TRAVEL WHERE CODE IN (‘101’,’102’)
(iii) SELECT NO, NAME from TRAVEL WHERE TDATE >= ‘2015−04−01’ AND TDATE <= ‘2015−12−31’;
OR
SELECT NO, NAME from TRAVEL WHERE TDATE BETWEEN ‘2015-04-01’ AND ‘2015-12-31’;
(iv) SELECT * FROM TRAVEL WHERE KM > 100 ORDER BY NOP;
(v) ALTER TABLE VEHICLE MODIFY VTYPE VARCHAR(20);

(vi) COUNT(*) CODE


2 101
2 102
(vii) DISTINCT CODE
101
102
103
104
105
(viii) CODE NAME TYPE
104 Ahmed Khan CAR
105 Raveena SUV

123
INTERFACE PYTHON WITH SQL DATABASE
Database connectivity
Database connectivity refers to connection and communication between an application and a database
system. The steps are

(i) We use pip install mysql.connector:This command we use to install library of MySQL with python.
(ii) import mysql.connector: This statement run on python to access the module of MySQL. if we don’t
get any error means this module working properly.
(iii) mydb=mysql.connector (host=”localhost”,user=”root”,passwd=”tiger”, database = ”school”)
To make the connection with MySQL database using connect() function where user, password and
database are as per our system which we assign during installing of MySQL. Mydb is connection object.
(iv)cursor = mydb.cursor() -a database cursor is useful control structure for row by row
processing of records
(v) cursor.execute(“select * from stud”) : It will execute the sql query and store the retrieved
records.
(vi) data = cursor.fetchall() : Extract data from result set using fetch() functions.
fetchall() :It will return all the records retrieved in tuple form.
fetchone() :It will return one record from the result set.
fetchmany(n) :It will return number of records as per value of n and by-default only one
record.
(vii) count = coursor.rowcount
It is the property of cursor object that return number of rows retrieved.

# TO CREATE A TABLE IN MYSQL USING PYTHON INTERFACE


import mysql.connector
mydb = mysql.connector.connect(host="localhost",user="root", passwd="system", database="student")
mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE FEES (ROLLNO INT,NAME VARCHAR(20),AMOUNT INT);")
# TO SHOW THE TABLES IN MYSQL USING PYTHON INTERFACE
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system ", database="student")
mycursor=mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
124
print(x)
#TO DESCRIBE TABLE STRUCTURE USING PYTHON INTERFACE
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system",database="student")
mycursor=mydb.cursor()
mycursor.execute("DESC STUDENT")
for x in mycursor:
print(x)
# TO EXECUTE SELECT QUERY USING A PYTHON INTERFACE
import mysql.connector
conn = mysql.connector.connect (host = "localhost",user = "root",passwd = "12345", database="student")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()

# TO EXECUTE SELECT QUERY WITH WHERE CLAUSE USING A PYTHON INTERFACE


import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="student")
c=conn.cursor()
c.execute("select * from student where marks>90")
r=c.fetchall()
count=c.rowcount
print("total no of rows:",count)
for row in r:
print(row)
#TO INSERT A RECORD (ROLLNO,NAME,AND MARKS) IN MYSQL TABLE student USING
#PYTHON INTERFACE

import mysql.connector
mydb= mysql.connector.connect(host="localhost",user="root",passwd="system",database="student")
mycursor=mydb.cursor()
r=int(input("enter the rollno"))
n=input("enter name")
m=int(input("enter marks"))
mycursor.execute("INSERT INTO student(rollno,name,marks) VALUES({},'{}',{})".format(r,n,m))
mydb.commit()
print(mycursor.rowcount,"RECORD INSERTED")

# TO UPDATE A DATA IN A TABLE USING PYTHON INTERFACE


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

# TO DELETE A RECORD FROM THE TABLE USING PYTHON INTERFACE


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

# TO DROP AN ENTIRE TABLE FROM MYSQL DATABASE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system", database="student")
mycursor=mydb.cursor()
mycursor.execute("DROP TABLE STUDENT")

# TO ADD A COLUMN IN THE EXISTING TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system", database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT ADD AGE INT”)
mydb.commit()

#TO DROP A COLUMN FROM THE TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system", database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE DROP AGE ”)
mydb.commit()

# TO ALTER THE DATATYPE OF A COLUMN IN A TABLE USING PYTHON INTERFACE


import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system", database="student")
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE STUDENT MODIFY GRADE CHAR(3)")
 commit(): After executing insert or update query we must commit our transaction using commit
method of connection object.
Eg: mydb.commit()
 rollback(): mydb.rollback() reverts the changes made by the current transaction.
 rowcount: This attribute returns the number of rows that were affected by an execute()
126
PARAMETERIZED QUERIES

Sometimes we need to access values as per the user’s input. The query result is based on the
values user has passed. So for that we have this option parameterized queries. There are two
ways to use parameterized queries:
1. with % formatting pattern
2. with {}.format pattern
With % formatting pattern

This pattern takes the general form – f % v, where f is a format and v is the value. Consider the
following code:
import mysql.connector as msql
import time
mydb=msql.connect(host='localhost',user='root',passwd='MySQL@123',database='School')
cur=mydb.cursor()

#display records more than 80%


cur.execute("select * from students where marks >%s" %(80,))
d=cur.fetchall()
for r in d :
print(r)
#display records having B1 grade

cur.execute( "select * from students where grade='%s'" %('B1',) )


d=cur.fetchall()
for r in d :
print(r)
With {}.format pattern

In this pattern you can write {} where the value is placed followed by .format(values).
Consider the following code:

import mysql.connector as msql


import time
mydb=msql.connect(host='localhost', user='root', passwd='kvs@123',database='School')
cur=mydb.cursor()
cur.execute ( "select * from students where marks >{}" .format(80) )
d=cur.fetchall()
for r in d :
print(r)
cur.execute("select * from students where grade='{}'".format('B1'))
d=cur.fetchall()
for r in d :
print(r)

127
Close the connection
Since the database can keep limited number of connections at a time, we must close the connection
using
cursorobject.close()
Eg: mycursor.close()
con.close()
( VERY SHORT ANSWER QUESTIONS- 1 MARK)
Q1. Which command is use to install MySQL library in python?
Ans: pip install MySQL. Connector with path of python
Q2. Which method we use to establish the connection?
Ans: connect() method with connection object.
Q3. Which statement we use to access the MySQL module?
Ans: import mysql.connector
Q4. What is the Database Connector?
Ans. A database connector is a software that connects an application to any database.
Q5. Which function is used to check the successful connection?
Ans .is_connected() method

SHORT ANSWER QUESTIONS (2 MARKS)


1. What are the steps for creating database connectivity applications?
Ans. To create database connectivity, follow the given steps:

Step 1: Start Python


Step 2: Import mysql.connector
Step 3: Open a connection to the database
Step 4: Create a cursor instance
Step 5: Execute a query
Step 6: Extract data from result set
Step 7. Clean up the environment

2. What is a connection? What is its role?


Ans. A connection (represented by the connection object) is the session between the application
program and database. To do anything with database, one must have a connection object.
3. What is a resultset?
Ans. A result set refers to a logical set of records that are fetched from the database by executing a query
and made available to the application program.
4. What is a database cursor?
128
Ans. A database cursor is a special control structure that facilitates row by row processing of records in the
result set, i.e., the set of records retrieved as per the query.
5. How to retrieve data from a table?

Ans. There are multiple ways to retrieve data:


i. fetchall( ) – fetches all the remaining rows of a query result, current pointer position forwards

ii. fetchone( ) – fetches the next row as a sequence; returns None when no more data
iii. fetchmany(n) :It will return number of records as per value of n and by-default only one record.

LONG ANSWER QUESTIONS (3 MARKS)


1. Write a Python code to connect to a database
Ans.
import mysql.connector
Mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,database=”project”)
print(mycon)
2. How to create a database in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor( )
cursor.execute(“create database education”)
3. Write the Python code to display the present databases in MySQL
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“show databases”)
for i in cursor:
print(i)
4. How to create a table in MySQL through Python ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”)
cursor=mycon.cursor()
cursor.execute(“create table student(admn_no int primary key, sname varchar(30), gender char(2),
DOB date, stream varchar(15), marks float”)
5. Write the Python code to insert data into student table of database kvs in MYSQL .
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”,
database=’kvs’)
cursor=mycon.cursor()
ano=int(input(“Enter admission no: “))
n=input(“Enter name: “)
g=input(“Enter gender:”)
129
dob=input(“Enter DOB: “)
s=input(“Enter stream: “)
m=float(input(“Enter marks:”))
query= “insert into student values( {}, ‘,-’ , ‘,-’ , ’,-’ , ’,-’ , {} )”.format(ano,n,g,dob,s,m)
cursor.execute(query)
mycon.commit( )
6. How to fetch data in Python from a student table of education database in MySQL ?
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”)
cursor=mycon.cursor()
cursor.execute(“select * from student”)
for row in cursor:
print(row)
7. Write the Python code to update a record in the student table of education database.
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”)
cursor=mycon.cursor()
cursor.execute(“update student set marks=67 where admn_no=3456”)
mycon.commit( )
8. Write the Python code to delete a record from the student table of education database
Ans.
import mysql.connector
mycon=mysql.connector.connect(host=”localhost”,user=”root”,passwd=”tiger”, database=”education”)
cursor=mycon.cursor()
cursor.execute(“delete from student where admn_no=3455”)
mycon.commit( )
9. Mr.Harsh want to interface python with mysql and write some code help him to write the code
import .connector #Line1
mydb=mysql.connector. (host=”localhost”,user=”root”,passwd=”tiger”,database=”school”)
#Line2
cursor=mydb. () #Line3
cursor. (“select * from stud”) #Line4
data=cursor. () # Line 5 To retrieved all records
count=cursor. #Line6 To count total rows
Ans: Line1:-mysql, Line2:-connect, Line3:cursor ,
Line4: execute, Line5: fetchall, Line6: rowcount
10. What is a cursor? Explain how to initiate the same.
ANS A cursor is an object which helps to execute the query and fetch the records from the database.
import mysql.connector
myconn = mysql.connector.connect (host='localhost',user='root',password='root',database='XIICS' )
mycursor = myconn.cursor()
mycursor.execute("MySQL Command")
myconn.close()
11. What are the difference between fetchone(),fetchmany(),fetchall()? Hint- Above given
130
WORKSHEET INTERFACE PYTHON WITH MYSQL (Multiple Choice Questions-1Mark)

1 Identify the name of connector to establish bridge between Python and MySQL
a. mysql.connection
b. connector
c. mysql.connect
d. mysql.connector
Ans d.mysql.connector

2 Which function of connection is used to check whether connection to mysql is


successfully done or not?
Import mysql.connector as msq
con = msq.connect( #Connection String ) # Assuming all parameter required as
passed
if :
print(“Connected!”)
else:
print(“Error!Not Connected”)
a. con.connected()
b. con.isconnected()
c. con.is_connected()
d. con.is_connect()
Ans c. con.is_connected()

3 Which of the following component act as a container to hold all the data returned
from the query and from there we can fetch data one at a time?
a. ResultSet
b. Cursor
c. Container
d. Table
Ans b. Cursor
4 Identify the correct statement to create cursor:
Import mysql.connector as msq
con = msq.connect( #Connection String ) # Assuming all parameter required
as passed mycursor =
a. con.cursor()
b. con.create_cursor()
c. con.open_cursor()
d. con.get_cursor()
Ans a) con.cursor()

5 What is the difference in fetchall() and fetchone()?

Ans fetchall() function is used to fetch all the records from the cursor in the form of tuple.
fetchone() is used to fetch one record at a time. Subsequent fetchone() will fetch
next records. If no more records to fetch it return None.

131
6 Which attribute of cursor is used to get number of records stored in a cursor
(Assuming cursor name is mycursor)?
a. mycursor.count
b. mycursor.row_count
c. mycursor.records
d. mycursor.rowcount
Ans d. mycursor.rowcount

7 Which of the Symbols are used for passing parameterized query for execution to
cursor?
a. %
b. {}
c. $
d. Bothaandb
Ans d. Both a and b

8 Which function is used to fetch n number of records from cursor?


a. fetch()
b. fetchone()
c. fetchmany()
d. fetchall()
Ans c. fetchmany()

9 Which cursor function is used to send query to connection?


a. query()
b. execute()
c. run()
d. send()
Ans b.execute()

10 Consider the following Python code is written to access the record of CODE passed
to function:
Complete the missing statements:

def Search(eno):
#Assumebasic setup import, connection and cursor is created
query="select * from emp where empno= ".format(eno)
mycursor.execute(query)
results = mycursor.
print(results)
a. {} and fetchone()
b. fetchone() and {}
c. %s and fetchone()
d. %eno and fetchone()
Ans a. {} and fetchone()

132
UNSLOVED QUESTIONS
(Multiple Choice Questions)
Worksheet 1
1. Which of the following is not a legal method for fetching records from database.
a)fetchone() b)fetchtwo() c)fetchall() d)fetchmany()
2. To fetch one record from resultset you may use<curor> ........... method.
a) fetch() b)fetchone() c)fetchtuple d)none of these.
3. To reflect the changes made in the database permanently you need to run……..
a) done() b)reflect() c)commit() d)final
4. To run an sql query from within python you may use cursor -------------- method.
a) query() b)execute() c)commit() d)final()
5. A database.............. controls the connection to an actual database , established in program.
a) database object b)connection object c)fetch object d)query object
ANSWER KEY FOR WORKSHEET1 (MCQ)
1. b)fetchtwo() 2. b)fetchone() 3. c)commit() 4. b)execute() 5. b)connection object

WORKSHEET 2
Q1.The following table represents information on sales representatives of ABC company with the following
data.
Sales man name
Code
Address
commission
salary.
Write Python code to create the above table.
Q2. Write Python mysql connectivity program to retrieve all the data from a table student.
Q3. Consider the following python code for updating the records.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system",database="student")
mycursor=mydb.cursor()
mycursor.execute("UPDATE STUDENT SET MARKS=95 WHERE MARKS=50")
print(mycursor.rowcount,"RECORD UPDATED")
Code is running but the record in actual database is not updating, what could be the possible reason?
Q4. Write a python connectivity program to retrieve data, one record at a time from EMP table for
employees with id<10.
Q5. Write python connectivity program to delete the employee record whose name is read from the
keyboard at execution time.

ANSWER KEY FOR WORKSHEET 2


1. mycursor=mydb.cursor()
mycursor.execute("CREATE TABLE SALESMAN (NAME VARCHAR(20), CODE INT ,
ADDRESS VARCHAR(20), COMMISSION DEC, SALARY FLOAT);")

2. import mysql.connector
133
conn=mysql.connector.connect(host="localhost",user="root",passwd="syste
m",database="DB")
c=conn.cursor()
c.execute("select * from student")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
conn.close()

3. con.commit() function is missing in the python code.

4. import mysql.connector
conn=mysql.connector.connect(host="localhost",user="root",passwd="system",database="com")
c=conn.cursor()
c.execute("select * from emp where id>10")
r=c.fetchone()
while r is not None:
print(r)
r=c.fetchone()
conn.close()

5. import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="system",database="DB")
mycursor=mydb.cursor()
s= input(“enter the name”)
mycursor.execute("delete from emp where name =’,-’)”.format(s)
mydb.commit( )

SOLVED SAMPLE PAPER -1


COMPUTER SCIENCES (083)
TIME: 3 HOURS M.M.70

134
General Instructions:

1. Please check this question paper contains 35 questions.


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

Q. No. SECTION A Marks

1. State True or False: 1


“None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither same as False nor 0 (zero).”

2. In a table in MYSQL database, an attribute ABC of datatype int with constraint NOT NULL 1
and another attribute XYZ of datatype varchar(10) with constrain UNIQUE. Which attribute
will allow duplicate data values during insertion of records?
a. ABC b. XYZ c. both ABC and XYZ d. None of these

3. What will be the output of the following statement: 1


print(pow(2,3)//8*(1+2)+3**2**2)
a. 0 b. 84.0 c. 84 d. 0.0

4. Select the correct output of the code: 1


str1=" PM SHRI "
str2=" KV is My ViDyalaya"
str3=str1.strip()+str2.replace("D", "d").lstrip()
print(str3.partition("My"))
a. ['PM SHRIKV is ', 'My', ' ViDyalaya'] b. ('PM SHRIKV is ', 'My', ' Vidyalaya')
c. ['PM SHRIKV is ', 'My', ' Vidyalaya'] d. ('PM SHRIKV is ', 'My', ' ViDyalaya')

5. In MYSQL database, if a table, STUDENT with attributes (admno, name, address, phone, 1
scode) and another table, REGS with attributes (scode, sub1, sub2, sub3, sub4, sub5, sub6,
sub7, regfee). Which of the following attribute can be used for join operation through
NATURAL JOIN clause?
a. name b. admno c. regfee d. scode

6. Purushottam is having an internet connection between his office and server room through an 1
Ethernet cable (i.e. twisted pair). But the network speed is very poor and need to
amplify/boost the signal. Which of the following device is required as a booster to amplify the
signal?
a. Gateway b. router c. modem d. repeater

7. Which of the following python statement will delete all the items in the dictionary named 1
INDEX and make it empty?
135
a. INDEX.popitem() b. INDEX.pop() c. INDEX.clear() d. del INDEX
8. Consider the statements given below and then choose the correct output from the given 1
options:
x = 'PM Shri KV'
str1=x[::-1]
for y in str1:
print(y,end='')
x.lower()
a.KV PM Shri b. PM Shri KV c. vk irhs mp d.VK irhS MP

9. Which of the following statement(s) would give an error during execution of the following 1
code?
tuple1 = (10,20,30,40,50,60)
list1 =list(tuple1) # Statement -1
new_list = [] # Statement -2
for i in list1:
if i%3==0:
new_list.append(i) # Statement -3
new_list.append(tuple1)
print(new_list[3]) # Statement -4
a. Statement-1 b. Statement -2 c. Statement- 3 d. Statement-4

10. What possible outputs(s) will be obtained when the following code is executed? 1
import random
List = ['CTC', 'BBSR', 'KDML', 'PURI']
for y in range (4):
x = random.randint (1,3)
print (List[x], end = '#')
Options are:
a) KDML#PURI#BBSR#PURI# b) KDML#KDML#PURI#PURI#
c) BBSR#KDML#BBSR#KDML# d) All of these 3 options are possible

11. A Router is a network device that forwards data packets along networks. A 1
is networking device that connects computers in a network by using
packet switching to receive, and forward data to the destination.
a. Hub b. Switch c. Repeater d. Modem

12. Consider the statements given below and then choose the correct output from the given 1
options:

136
def fun2():
global x
print(x, end=":")
x=500
print(x, end=":")
x=x+1
x=5 # global var
print(x, end=":")
fun2()
print(x,end=":") # 501
a. 5:5:500:501: b. 501:500:5:5: c. 5:5:501:500: d. 500:501:5:5:

13. try: 1
n=int(eval(input("Enter any value: ")))
if n<=0:-
raise Exception("Zero/Negative ")
else:
print(" Positive Number")
# Blank Line
print("Zero Entered/ Negative Number")
finally:
print("End of try ...... except with finally clause ")
Fill the blank line from the options given below.
a. catch b. else: c. exception: d. except:

14. Which of the following statements is TRUE about keys in a relational database? 1
a. The number of tuples/rows in a relation is called the Degree of the relation.
b. The number of attribute/columns in a relation is called the Cardinality of the relation.
c. Primary key allows Unique and Null values only.
d. Domain is a set of values from which an attribute can take a value in each row. Usually, a
data type is used to specify domain for an attribute.
15. is a set of rules that need to be followed by the communicating parties in 1
order to have successful and reliable data communication.

16. Which of the following File Open modes opens the file in append and read mode. If the file 1
doesn‟t exist, then it will create a new file.
a. “a+” b. “r+” c. “a+r” d. “r+a”

Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice

137
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

17. Assertion (A):- A Python sequence is an ordered collection of items, where each item is 1
indexed by an integer.
Reasoning (R):- The Strings, Lists and Tuples are not sequence data types available in
Python.

18. Assertion (A):- A function may or may not return a value when called. The return statement 1
returns the values from the function.
Reasoning (R):- The return statement does the following: • returns the control to the calling
function. • return value(s) or None.

SECTION B

19. (i) Expand the following terms: SMTP , PPP 1+1=2


(ii) Give one difference between Web browser and Web Server.
OR
(i) Define network device Gateway with respect to computer networks.
(ii) How is ARPANET different from NSFNET?

20. The given Python code to print all Prime numbers in an interval (range) inclusively. The 2
given code accepts 02 number (low & high) as arguments for the function Prime_Series()
and return the list of prime numbers between those two numbers inclusively. Observe the
following code carefully and rewrite it after removing all syntax and logical errors. Underline
all the corrections made.
def Prime_Series(low, high)
primes = []
for i in range(low, high + 1):
flag = 0
if i < 2:
continue
if i == 2:
primes.append(2)
continue
for x in range(2, i):
if i % x == 0:
flag = 1
continue

138
if flag == 0:
primes.append(i)
return primes
low=int(input("Lower range value: "))
high=int(input("High range value: ")
print(Prime_Series())

21. Write a function seq_to_dict(ls, tp) in Python that takes one list and one tuple as two 2
arguments. The function will return a dictionary with an update of key-value pairs with keys
from a list and values from a tuple.For example, Consider the following:
List ls=[1,2,3,4] Tuple tp=("Pranay", "Shuvam", "Snehant","Swasat"))
The returned dictionary will be: {1: 'Pranay', 2: 'Shuvam', 3: 'Snehant', 4: 'Swasat'}
OR
Write a function dict_seq(dict) in Python that takes a dictionary (keys as numbers and values
as strings) as an argument and returns a list and a tuple. The list will have keys from the
dictionary, and the tuple will have values from the dictionary, but the values from the
dictionary should be converted to upper case if those are in lower case and uppercase if
those are in lowercase.
For example, if dict= {1: 'PRANAY', 2: 'shuvam', 3: 'snehant', 4: 'SWASAT'}
The returned List will be: [1,2,3,4] and Tuple: ("pranay", "SHUVAM", "SNEHANT",
"swasat")

22. Find the output of the following python code: 2


def even_odd(tup):
res = [ ]
for k in range(len(tup)):
if tup[k] % 2 == 0:
res.append(tup[0-k-1])
if k % 2 == 0:
res.append(tup[0- k-1])
print(res)
return None
even_odd ((9,10,11,13,13,14))
23. Write the Python statement for each of the following tasks using BUILT-IN functions/methods 1+1=2
only:
(i) To counts and return how many times a value 98 is occurred in a tuple TP.
(ii) To replace all the occurrences of the old string “THE” with the new string “the” in the string
named LINE.
OR
An arithmetic expression is required to calculate the area of the circle as (Area=πr2) with r
as the radius of 8cm. Write the Python command to import the required module and use the
built-in function or object to find the area of the circle.

139
24. Mr. Pranaya has just created a table named “DEPARTMENT” containing columns Deptno, 2
Dname, Location, and Phone. After creating the table, he realized that he needed to
remove the Phone column from the table. Help him to write a SQL command to remove the
column Phone from “DEPARTMENT” table. Thereafter, write the command to modify the
location of Deptno-101 as “ Odisha” in the table:
OR
Mr. Swasat is working as a database administrator in Micron Semiconductor MNC. He
wants to create a database named “MICROINDIA”. After creating the database, he will
create a table named MICRONSW with the following descriptions:

Field Name Type with (size) Constraints

ENO INTEGER ( 4) PRIMARY KEY

ENAME VARCHAR (15) NOT NULL

JOB CHARACTER UNIQUE


(10)
SALARY FLOAT(10,2) DEFAULT VALUE 5000

25. Predict the output of the Python code Given below: 2


def Sum(N1,N2):
if N1>N2:
return N1-N2
else:
return N2-N1
lst= [20,25,24,34,35]
for C in range (3,0,-1):
A=lst[C]
B=lst[C-1]
print(Sum(A,B),end='#')
else:
print("\nend of the program".title())

SECTION C

26. Predict the output of the Python code Given below: 3


def fun_para(x=5,y=10,z=1005):
z=x/2
res=y//x+z
return res
a,b,c=20,10,1509
print(fun_para(),fun_para(b),sep='#')
res=fun_para(10,20,6015)
print(res, "@")

140
print(fun_para(z=999,y=b,x=5), end="#@")

27. Consider the table GAMES given below and write the output of the SQL queries that follow. 1*3=3
TABLE: GAMES
GCODE GNAME STADIUM P_NO P_MONEY DATE

1001 Relay Star Annex 16 10000 2001-01-23

1002 High Jump Super Power 12 12000 2003-02-14

1003 Shot Put Star Annex 11 8000 2002-07-07

1008 Discuss Throw Star Annex 12 9000 2003-03-19

1005 Long Jump Super Power 10 11000 2002-12-20

(i) SELECT MAX(P_MONEY), MIN(P_MONEY) FROM GAMES;


(ii) SELECT GCODE, GNAME FROM GAMES WHERE PNO IN (16,12,11) AND
DOJ>‟2001-01-23‟;
(iii) SELECT DISTINCT STADIUM FROM GAMES WHERE GNAME NOT LIKE “H%d”;

28. Write a function, WordCount() in Python to read a text file, “story.txt”, and display those 3
words in it that begin with consonants and end with vowels. Also, the function will count
those words and return how many such numbers are in the same text file.
OR
Write a function, LineCount(), in Python to count and return the number of lines in “letter.txt”
that have a numeric value. Also, the function will display those lines in the same text file.

29. Consider the table FURNITURE given below:. 1*3=3

FID NAME TYPE COST DISCOUNT

F001 DOUBLE BED WOODEN 45000 10

F002 DINING TABLE WOODEN 51000 5

F003 SINGLE BED WOODEN 22000 NULL

F004 CHAIR WOODEN 12000 3

F005 TABLE WOODEN 15000 12

F006 DOUBLE BED IRON 18000 5

F007 SINGLE BED IRON 10000 NULL

F008 DINING TABLE IRON 26000 10

Based on the given table, write SQL queries for the following:
(i) Modify the record with the furniture name „CHAIR‟ to „ARAM CHAIR‟ and its price to 10%
more.
(ii) Display TYPE and the number of items of each type with a price greater than 10000 and

141
DISCOUNT is not NULL.
(iii) Delete all the records with NAME that begin with the character „S‟ and end with „D‟ and
Type is „IRON‟;

30. A dictionary, StudRec, contains the records of students in the following pattern: 3
{admno: [m1, m2, m3, m4, m5]}, i.e., Admission No. (admno) as the key and 5 subject
marks in the list as the value.
Each of these records is nested together to form a nested dictionary. Write the following
user-defined functions in the Python code to perform the specified operations on the stack
named BRIGHT.
(i) Push_Bright(StudRec): it takes the nested dictionary as an argument and pushes a list
of dictionary objects or elements containing data as {admno: total (sum of 5 subject
marks)} into the stack named BRIGHT of those students with a total mark >350.
(ii) Pop_Bright(): It pops the dictionary objects from the stack and displays them. Also, the
function should display “Stack is Empty” when there are no elements in the stack.

For Example: if the nested dictionary StudRec contains the following data:
StudRec={101:[80,90,80,70,90], 102:[50,60,45,50,40], 103:[90,90,99,98,90]}
Thes Stack BRIGHT Should contain: [{101: 410}, {103: 467}]
The Output Should be: {103: 467}
{101: 410}
If the stack BRIGHT is empty then display: Stack is Empty

SECTION D

31. Table Name: TRADERS 4

TCODE TNAME CITY

T01 RELIANCE DIGITAL MUMBAI

T02 TATA DIGITAL BHUBANESWAR

T03 BIRLA DIGITAL NEW DELHI

Table name: STOCK

SCODE SNAME QTY PRICE BRAND TCODE

1001 COMPUTER 90 45000 DELL T01

1006 LCD PROJECTOR 40 42000 NEC T02

1004 IPAD 100 55000 APPLE T01

1003 DIGITAL CAMERA 160 15000 SAMSUNG T02

142
1005 LAPTOP 600 35000 HP T03

Write SQL queries for the following:

(i) Display the SNAME, QTY, PRICE, TCODE, and TNAME of all the stocks in the STOCK
and TRADERS tables.

(ii) Display the details of all the stocks with a price >= 35000 and <=50000 (inclusive).

(iii) Display the SCODE, SNAME, QTY*PRICE as the “TOTAL PRICE” of BRAND “NEC” or
“HP” in ascending order of QTY*PRICE.
(iv) Display TCODE, TNAME, CITY and total QTY in STOCK and TRADERS in each
TCODE.

32. Mr. Snehant is a software engineer working at TCS. He has been assigned to develop code 4
for stock management; he has to create a CSV file named stock.csv to store the stock
details of different products.The structure of stock.csv is : [stockno, sname, price, qty],
where stockno is the stock serial number (int), sname is the stock name (string), price is
stock price (float) and qty is quantity of stock(int).

Mr. Snehant wants to maintain the stock data properly, for which he wants to write the
following user-defined functions:

AcceptStock() – to accept a record from the user and append it to the file stock.csv. The
column headings should also be added on top of the csv file. The number of records to be
entered until the user chooses „Y‟ / „Yes‟.

StockReport() – to read and display the stockno, stock name, price, qty and value of each
stock as price*qty. As a Python expert, help him complete the task.

SECTION E

143
33. The USA-based company, Micron, has selected Tata Projects to build the semiconductor 1*5=5
assembly and test facility in Sanand Town, near Ahmedabad in Gujurat. It is planning to set
up its different units or campuses in Sanand Town and its head office campus in New Delhi.

Shortest distance between various locations of Sanand Town blocks and Head Office
at New Delhi:

Training Campus Research Campus 3 KM

Business Campus warehousing 4.5 KM

Manufacturing Research Campus 1.5 KM


Campus

Warehousing Training Campus 9.5 KM

Research Campus Business Campus 3.5 KM

Warehousing Campus Research Campus 2.6 KM

Research Campus New Delhi Head Office Campus 962KM

Number of computers installed at various locations are as follows:

Warehousing Campus 20 computers

Research Campus 200 computers

Business Campus 10 computers

Training Campus 25 computers

Manufacturing Campus 15 Computers

Ahmedabad Admin Campus 15 Computers

As a network consultant, you have to suggest the best network related solution for their
issues/problems raised :
(i) Suggest the most appropriate location of the SERVER to get the best and effective
connectivity. Justify your answer.
(ii) Suggest the best wired medium and draw the cable layout (location to location) to
efficiently connect various locations
(iii) Which hardware device will you suggest to connect all the computers within each
location?
(iv) Suggest a system (hardware/software) to prevent unauthorized access to or from the
network.
(v) Which type of network out of the following is formed by connecting the computers of
New Delhi Head Office and Sanand Town Units? a) LAN b) MAN c) WAN d) PAN
34. (i) What are the similarities and difference between a+ and w file modes in Python. 2+3=5

(ii) (ii) A binary file “product.dat” has structure [PNO, PNAME, BRAND_NAME, PRICE] to
maintain and manipulate Product details.

144
*Write a user defined function CreateFile() to input data for a record and add to “product.dat”
file. The number of records to be entered until the user chooses „Y‟ / „Yes‟.
*Write a function CountData(BRAND_NAME) in Python which accepts the brand name as
parameter and count and return number of products by the given brand are stored in the
binary file “product.dat”.
OR
(i) What is the difference between seek() and tell()?
(ii) A binary file “STUD.DAT” has structure (admission_number, Name, total_mark) with
student details.

 Write a user defined function WriteFile() to create a file input data for a record and
write to “stud.dat” file. The number of records to be entered until the user chooses „Y‟
/ „Yes‟.
 Write a function ReadFile() in Python that would read the contents of the file
“STUD.DAT” and display the details of those students whose total mark is less than
or equal to 250 under the printed heading "REMEDIAL STUDENT LIST “. Also
display and the number of students scoring above 250 marks as Bright Student.
35. (i) What is the difference between degree and cardinality with respect to RDBMS. Give one 1+4=5
example to support your answer.

(ii) Mr. Shuvam wants to write a program in Python to Display the following record in the
table named EMP in MYSQL database EMPLOYEE with attributes:

 EMPNO (Employee Number ) - integer  ENAME (Employee Name) - string size(30)

 SAL (Salary) - float (10,2)  DEPTNO(Department Number) - integer


Note: The following to establish connectivity between Python and MySQL:

 Username - root  Password – admin  Host – localhost


The values of fields rno, name, DOB and fee has to be accepted from the user. Help
Shuvam to write the program in Python.
OR
(i) What is the difference between Primary and Foreign key?
(ii) Mr. Pranay wants to write a program in Python to update the particular record by
accepting its Department Number value in the table named DEPT in MYSQL database
EMPLOYEE with attributes:

 DEPTNO (Department Number) – integer  DNAME (Department Name) – string size(15)


 LOC(Location of the Department) – string size(15)

Note: The following to establish connectivity between Python and MySQL:

 Username - root  Password – admin  Host – localhost


The values of fields rno, name, DOB and fee has to be accepted from the user. Help Kabir
to write the program in Python.

145
SOLVED SAMPLE PAPER -1
SOLUTIONS
COMPUTER SCIENCES (083): MARKING SCHEME
TIME: 3 HOURS M.M.70
COMMON QUESTION FORMAT
Note: [Please do the step markings on a priority basis, wherever applicable, except for MCQ
questions.]
Q. No. SECTION A Marks

1. Ans: True 1

2. Ans: a. ABC 1

3. Ans: c.84 1

4. 1
Ans: b. ('PM SHRIKV is ', 'My', ' Vidyalaya')

5. ans: d. scode 1

6. ans: repeater 1

7. ans: c. INDEX.clear() 1

8. ans: d.VK irhS MP 1

9. Ans: d. Statement-4 1

10. Ans: d) All of these 3 options are possible 1

11. Ans: b. Switch 1

12. Ans: a. 5:5:500:501: 1

13. Ans: d. Except: 1

14. Ans: d. Domain is a set of …. 1

15. Ans: Protocol 1

16. ans: a. “a+” 1

17. Ans: (c) A is True but R is False 1

18. Ans: (a) Both A and R are true and R is the correct explanation for A 1

SECTION B

19. Ans: 1+1=2


(i) PPP - Point to Point Protocol, SMTP - Simple Mail Transfer Protocol
(ii) Websites are stored on web servers, web browser is the client which
makes a request to the server.

146
OR
Ans:
(i) Gateway serves as the entry and exit point of a network, as all data coming in or
going out of a network must first pass through the gateway in order to use routing
paths. It's a device that connects dissimilar networks.

(ii) ARPANET (Advanced Research Project Agency Network): It is a project


sponsored by U. S. Department of Defense to connect the academic and research
institutions located at different places for scientific collaborations.

NSFNET (National Science Foundation): It is a wide area network started by the NSF
(National Science Foundation) that handled a bulk of early Internet traffic or high-
capacity network and strictly used for academic and engineering research.

20. def Prime_Series(low, high) 2


primes = []
for i in range(low, high + 1):
flag = 0
if i < 2:
continue
if i = 2:
primes.append(2)
continue
for x in range(2, i):
if i % x == 0:
flag = 1
break # correction 1
if flag == 0:
primes.append(x)
return primes
low=int(input("Lower range value: "))
high=int(input("High range value: ")
print(Prime_Series(low, high)) # correction 2

Ans:
Corrections are made bold
21. Ans: 2
def seq_to_dict(ls, tp):
dc={}
for k in range(0,len(ls),1):
dc.update({ls[k]:tp[k]})
return dc

print(seq_to_dict([1,2,3,4],("Pranay", "Shuvam", "Snehant","Swasat")) )

147
OR
def dict_seq(dict):
ls=[]
tp=[]
ls=list(dict.keys())
val=dict.values()
for k in val:
if k.isupper():
tp.append(k.lower())
else:
tp.append(k.upper())
return ls,tuple(tp)

print(dict_seq({1: 'PRANAY', 2: 'shuvam', 3: 'snehant', 4: 'SWASAT'}) )


OR – Alternate Code
def dict_seq(dict):
ls=list(dict.keys())
for k in ls:
if dict[k].isupper():
dict[k]=dict[k].lower()
else:
dict[k]=dict[k].upper()
tp=tuple(dict.values())
return ls,tp
print(dict_seq({1: 'PRANAY', 2: 'shuvam', 3: 'snehant', 4: 'SWASAT'}) )

22. Ans: [14, 13, 13, 10, 9] 2

23. Ans: 1+1=2


(i) TP. count(98) (ii) LINE.replace("THE", "the")
OR
import math
Area=math.pi*math.pow(r,2) #Area=math.pi*r*r # Area=math.pi*r**2
""" OR """

148
from math import pi
Area=pi*pow(r,2) # Area=pi*r*r # Area=pi*r**2

24. Ans: 2
mysql> ALTER TABLE DEPARTMENT DROP PHONE;
mysql> UPDATE DEPARTMENT SET LOCATION = "ODISHA" WHERE DEPTNO=101;

OR
Ans:
mysql> CREATE DATABASE MICROINDIA;
mysql> CREATE TABLE MICRONSW( ENO INT(4) PRIMARY KEY, ENAME
VARCHAR(15) NOT NULL, JOB CHAR(10) UNIQUE, SALARY FLOAT(10,2) DEFAULT
5000);

25. Ans: 2
10#1#5#
End Of The Program

SECTION C

26. Ans: 3
4.5#6.0
7.0 @
4.5#@

27. ANS: 1*3=3


(i) MAX(P_MONEY) MIN(P_MONEY)
12000 8000
(ii) GCODE, GNAME
1002 High Jump
1003 Shot Put
(iii) STADIUM
Star Annex
Super Power

28. Ans: 3
def WordCount():
fob=open("d:\\story.txt", "r")
data = fob.read()
ct=0

149
words=data.split()
for w in words:
if w[0].lower() not in 'aeiou' and w[-1].lower() in 'aeiou':
print(w)
ct+=1
return ct
OR
def LineCount():
fob=open("d:\\letter.txt", "r")
data = fob.readlines()
ct=0
for line in data:
for k in line:
if k.isdigit():
print(line)
ct+=1
break
return ct
print(LineCount())

29. Ans: 1*3=3


(i) UPDATE FURNITURE SET NAME = 'ARAM CHAIR' , COST=COST*1.01 WHERE
NAME='CHAIR';
(ii) SELECT TYPE, COUNT(*) FROM FURNITURE WHERE DISCOUNT IS NOT NULL
AND COST>10000 GROUP BY TYPE;
(iii) DELETE FROM FURNITURE WHERE NAME LIKE 'S%D ' AND TYPE = 'IRON ';

30. Ans: 3
def Push_Bright(StudRec):
admno=StudRec.keys()
tot=0
for k in admno:
tot=sum(StudRec[k])
if tot>350:
BRIGHT.append({k:tot})
print(BRIGHT)
return

def Pop_Bright():

150
if BRIGHT==[]:
print("Stack is Empty")
for k in range(len(BRIGHT)-1, -1, -1):
print(BRIGHT.pop())
"""
else:
print("Stack is Empty")
"""
Return

# main
StudRec={101:[80,90,80,70,90], 102:[50,60,45,50,40], 103:[90,90,99,98,90]}
BRIGHT=[]
Push_Bright(StudRec)
Pop_Bright()
SECTION D

31. Ans: 4
(i) SELECT SNAME, QTY, PRICE, STOCK.TCODE, TNAME FROM STOCK NATURAL
JOIN TRADERS ;
(or any alternative query)
(ii) SELECT * FROM STOCK WHERE PRICE BETWEEN 35000 AND 50000;
(iii) SELECT SCODE, SNAME, QTY*PRICE as „TOTAL PRICE‟ FROM STOCK
WHERE BRAND=‟NEC‟ OR BRAND=‟HP‟ ORDER BY QTY*PRICE ASC;
(iv) SELECT STOCK.TCODE, TNAME, CITY, SUM(QTY) FROM STOCK JOIN TRADERS
ON STOCK.TCODE=TRADERS.TCODE GROUP BY TCODE;

32. Ans: 4
import csv
def AcceptStock():
fob=open("stock.csv",'a',newline='')
wob=csv.writer(fob)
headings=["Stock No.", "Name of the Stock", "Stock Price", "Quantity"]
wob.writerow(headings)
ch='y'
while ch.upper()=='Y':
stockno=int(input("Enter the Stock No. "))
sname=input("Enter the stock name: ")
price=float(input("Enter the stock price: "))
qty=int(input("Enter the stock quantity: "))
data=[stockno,sname,price,qty]
wob.writerow(data)
ch=input("Have you any more records to enter(y/n): ")
fob.close()
return
def StockReport():
fob=open('stock.csv','r')
rob=csv.reader(fob,delimiter=',')
data=list(rob)
# print(data[0]) # to be used as header

151
print("STOCK REPORT ")
print("*"*80)
for rec in data[1::]: # rec[0] is be the header
print("Stock No: ", rec[0])
print("Stock Name: ", rec[1])
print("Stock Price: ", rec[2])
print("Stock Quantity: ", rec[3])
print("Stock Total Price: ", float(rec[2])*int(rec[3]))
print("*"*80)
fob.close()
def AcceptStock():
StockReport()
SECTION E

33. Ans: 1*5=5


Ans: (i) Research Campus because maximum number of computers will gate faster access
to the Server.
(ii) Optical Fiber is best and faster wired medium for Sanand Town Campus. But Microwave
for Research Campus to New Delhi Head Office.

Research Campus Sanand Town Units


New Delhi
Head Office 962KM 3.5KM 1.5KM

Business Campus 3KM Manufacturing Campus

2.6KM
Warehousing Training Campus

(iii) Switch /Hub


(iv) Firewall
(v) WAN

34. Ans: 2+3=5


(i) Similarities:
In a+ and w mode If the file doesn’t exist, then a new file will be created.
Differences:
a+: Opens the file in append and read mode. And Previous contents will be there.
w-Opens the file in write mode. But here all the contents will be overwritten.
(ii)
import pickle
def CreateFile():
fobj=open("product.dat","ab")
ch='y'
while ch.upper()=='Y':
pno=int(input("Enter Product Number : "))
pname=input("Enter Product Name :")
brand_name = input('Enter Product Brand Name: ')
152
Price = int(input("Enter Price of the Product : "))
rec=[pno,pname,brand_name,Price]
pickle.dump(rec,fobj)
print("\n Have you any more record to enter: ", end='')
ch=input()
fobj.close()

def CountData(brand_name):
fobj=open("product.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if brand_name==rec[2]:
num = num + 1
except:
fobj.close()
return num

CreateFile()
print(CountData("LG"))

OR
(i)
seek(): 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])
* 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 fil
tell(): This function returns an integer that specifies the current position of the file
object in the file. That is the byte position from the beginning of the file till the
current position of the file object. The syntax of using tell() is: file_object.tell()

(ii)
import pickle
def WriteFile():
fobj=open("stud.dat","wb")
ch='y'
while ch.upper()=='Y':
admission_number=int(input("Enter Admission Number : "))

153
name=input("Enter Student Name :")
total_mark = int(input("Enter total mark : "))
rec=[admission_number, name, total_mark]
pickle.dump(rec,fobj)
print("\n Have you any more record to enter: ", end='')
ch=input()
fobj.close()

def ReadFile():
fobj=open("stud.dat","rb")
bright = 0
print("**************** REMEDIAL STUDENT LIST **************")
print("Admission No\tName of the Student\tTotal_mark")
try:
while True:
rec=pickle.load(fobj)
if rec[2]<=250:
print("\t",rec[0],"\t",rec[1], "\t\t", rec[2])
else:
bright = bright + 1
except:
fobj.close()
return bright
WriteFile()
print("No. of Bright students: ",ReadFile())

35. Ans: 1+4=5


(i) DEGREE: The number of attributes in a relation is called the Degree of the relation.
For example, relation GUARDIAN with four attributes is a relation of degree 4.
CARDINALITY: The number of tuples in a relation is called the Cardinality of the
relation. For example, the cardinality of relation GUARDIAN is 5 as there are 5 tuples
in the table.

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

154
database="EMPLOYEE")
mycursor=mycon.cursor()
print("\nBEFORE DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
eno=int(input("Enter the empno which record you want to delete: "))
qr="DELETE FROM EMP WHERE empno={}".format(eno)
mycursor.execute(qr)
mycon.commit() # To save above DML tansactions to the databases otherwise will
not save permanently
print("\nAFTER DELETION CONTENT OF EMP TABLE FOLLOWS: ")
mycursor.execute("SELECT * FROM EMP")
for k in mycursor:
print(k)
mycon.close()

OR
(i) Primary Key: One or more than one attribute chosen by the database designer to
uniquely identify the tuples in a relation is called the primary key of that relation.

Foreign key: It is used to represent the relationship between two relations. A foreign
key is an attribute whose value is derived from the primary key of another relation.
(ii)
import mysql.connector
mycon=mysql.connector.connect(host="localhost", user="root",passwd="admin",
database="EMPLOYEE")
mycursor=mycon.cursor()
dno=int(input("Enter the DEPT. NO which record you want to update: "))
qr="SELECT * FROM DEPT WHERE deptno={}".format(dno)
mycursor.execute(qr)
rec=mycursor.fetchall()
print("\n Old Record is follows: ")
for k in rec:

155
print(k)
print("\nENTER DETAILS TO UPDATE RECORD:\n")
print("Entered DEPTNO No:",dno)
dname=input("Enter Department Name:")
loc=input("Enter Location of the Department:")
qr="UPDATE dept SET dname='{}', loc='{}' WHERE deptno={}".format(dname, loc,
dno)
print(qr)
mycursor.execute(qr)
mycon.commit()
print("\nNEW RECORD AFTER UPDATE OF TABLE: ")
mycursor.execute("SELECT * FROM DEPT")
for k in mycursor:
print(k)
mycon.close()

UNSOLVED SAMPLE PAPER-1


156
CLASS: XII M.M:70
SUBJECT: COMPUTER SCIENCE (083) TIME: 3 HOURS

SECTION-A
1 State True or False: 1
A tuple T1 is declared as TP1 = (“AB”,”CD”,”EF”,”GH”)
if a statement T1*2+=”XY” is written then it changes value of 3rd element of T1 as
“XY”.
2 What will be the output of the following statement: 1
print(4**2-2**1**3//5*2+2)
3 Select the correct output of the code: 1
kv=”PM Shree KV Rewari”
print(kv.lower[0]+kv[1:-1]+kv[-1].upper()
4 Which of the following statements create a dictionary? 1
a) d = {}
b) d = ,“john”:40, “peter”:45-
c) d = ,40:”john”, 45:”peter”-
d) All of the mentioned
5 Given the lists VOWELS=*“A”,”E”,”I”,”O”,”U”+ , write the output of following 1
statement
print(VOWELS[-2:4])
6 Which of the following statement will generate error: 1
a) print("10"+20)
b) print(“10+20”)
c) print(10+20)
d) None of the above
7 What will be the output of the following python code? 1
t=(10)
t1=t*2

157
print(t1)
a) (10,10) b) (10) c) (100) d) (10),(10)
8 What will be the output of the following Python code? 1
marks = 50
def Result(marks):
print('marks are', marks)
marks= 75
print('Changed marks are', marks)
Result(marks)
print('Now marks are', marks)
a) marks are 50
Changed marks are 75
Now marks are 50
b) marks are 50
Changed marks are 50
Now marks are 50
c) marks are 50
Changed marks are 75
Now marks are 75
d) marks are 50
Changed marks are 50
Now marks are 50
9 State whether the following statement is True or False: 1
The else part of try is executed when no exception occurs.
10 Which is the incorrect outcome executed from the following code? 1
import random
x=3
158
N = random.randint (1, x)
for i in range (N):
print (i, "#", i + 1, end=””)
a) 0#11#22#3
b) 0#11#2
c) 0#11#22#33#4
d) 0#1
11 What is the best data type definition for MySQL when a field is alphanumeric and 1
has a fixed length?
a) VARCHAR b) CHAR c) INT d) DECIMAL
12 A table DATA in mysql has 6 records with 4 fields (attributes) of each record. 3 1
records are now deleted and 8 new records are added in DATA. In the end one
more field is added. What will be cardinality and degree of DATA?
13 Which key helps us to establish the relationship between two tables? 1

a) Candidate key

b) Foreign key

c) Primary key

d) Unique key

14 Which protocol is used for the transfer of hypertext content over the web? 1
(a) HTML
(b) HTTP
(c) TCP/IP
(d) FTP
15 Extend the term NSFNET. 1
16 Which of the following service is not using Packet Switching. 1
a) Sending an email
b) Downloading a video from youtube

159
c) Using Public Switched Telephone Network
d) Playing an online game
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 4
(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):- Text files are processed very fast in comparison to binary files. 1
Reasoning (R):-Binary files contain data in true binary format ( machine code )
18 Assertion (A) - If the arguments in the function call statement match the number 1
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 the positional argument(s).
SECTION-B
19 Rewrite the following code in Python after removing all syntax error(s). Underline 2
each correction done in the code.
x=int(“Enter value for x:”))
for y in range[0,11]:
if x==y:
print x+y
else:
Print(x-y)
20 Write the output of the following code : 2
def Output(S1,S2):
if (S1+S2)%2==0:
return S1+S2

160
else:
return S1-S2
LT= [10,15,20,12]
A=3
for I in LT:
print(Output(I,LT[A]),'#', end=' ')
A=A-1
21 Write a Python function that accepts a string and counts the number of upper and 2
lower case letters in a dictionary .
Sample String : 'Cricket World Cup 2023 in India'
Expected Output :
,“LOWER”:4,”UPPER”:18-
OR
Write a Python function that takes a list and returns a new list with distinct
elements from the first list.
Sample List : [1,2,3,3,3,3,4,2,5]
Unique List : [1, 2, 3, 4, 5]
22 Write the Python statement for each of the following tasks using BUILT-IN 2
functions/methods only:
(i) To sort a numeric List object L1 in descending order.
(ii) To delete marks of Sumit from a dictionary Marks where names are keys and
marks are values.
23 Find and write the output of the following python code: 2
def DEFAULT(P ,Q=100):
P=P+Q
Q=P-Q
print(P,"#",Q)
return (P)
R=300

161
S=200
R=DEFAULT(R,S)
S=DEFAULT(S)
Or
Find and write the output of the following Python code:
T= ["20", "0", "30", "40"]
Counter=3
Total= 0
for I in [7,5,4,6]:
newT=T[Counter]
Total= float (newT) + I
print(Total)
Counter=Counter-1
24 Hanshika has created a table “FRUITS”. Help her to do the following by writing 2
correct MySQL commans/queries:
(a) She wants to make the column “FruitName” should not contain duplicate
entry.
(b) She wants to delete all records where price of fruit is more than 100.
25 (a) Write one difference between circuit switching and packet switching. 2
(b) Write the name of the device which is used to connect two dissimilar
networks.
OR

(a) Write one difference between SMTP and POP.


(b) Write an example of a URL.
SECTION-C
26 Predict the output of the Python code given below: 3

162
s = 'Computer@Science'
n = len(s)
m = ''
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m + s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m + s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m + '$$’
print(m)
27 Write a function in Python to read a text file, Result.txt and displays those lines 3
which contains at least 5 words.
OR
Write a function in Python COUNTING() which will count “The” words from a text
file “Book.txt”
28 (a) Write a function PUSH(D) that accepts a dictionary. Push only those Keys to a 3
stack that have values more than 80 number. For example if dictionary contains
D=,“ARUN”:85,”VARUN”:65,”TARUN”:95,”MANYA”:75-
then PUSH() function must print stack as *“ARUN” ,“TARUN”+
(b) Write a function POP() that will remove elements one by one. Print “Can not
delete” if stack is empty.
29 Consider the table TRANSACTION given below: 3

TABLE : TRANSACTION
AN AMOUN
TRNO TYPE DOT
O T

163
T001 101 2500 Withdraw 2017-12-21
T002 103 3000 Deposit 2017-06-01
T003 102 2000 Withdraw 2017-05-12
T004 103 1000 Deposit 2017-10-22
T005 101 12000 Deposit 2017-11-06
Based on the given table, write SQL queries for the following:
a) Change the amount as 1500 of all those transactions where amount is less than
or equal to 2000.
b) Display all details of transactions which happened before 01-12-2007.
c) Display sum of amount of those having ANO as 103.
30 Give output for following SQL queries as per given tables- 3
Table : ITEM
I_ID ItemName Manufacturer Price

PC01 Personal Computer ABC 35000

LC05 Laptop ABC 55000

PC03 Personal Computer XYZ 32000

PC06 Personal Computer COMP 37000

LC03 Laptop PQR 57000

(i) SELECT ItemName, MAX(Price),Count(*)


FROM ITEM GROUPBY ItemName;
(ii) SELECT ItemName, Price*100
FROM ITEM WHERE ItemName LIKE ”%ona%”
(iii) SELECT I_ID
FROM ITEM ORDER BY Price ASC;

SECTION-D
31 Consider the tables GARMENT and FABRIC given below: 4
Table : GARMENT
GCODE Description Price FCODE READYDATE

164
10023 PENCIL SKIRT 1150 F03 19-DEC-08
10001 FORMAL SHIRT 1250 F01 12-JAN-08
10012 INFORMAL SHIRT 1550 F02 06-JUN-08
10024 BABY TOP 750 F03 07-APR-07
10090 TULIP SKIRT 850 F02 31-MAR-07
10019 EVENING GOWN 850 F03 06-JUN-08
10009 INFORMAL PANT 1500 F02 20-OCT-08
10017 FORMAL PANT 1350 F01 09-MAR-08
10020 FROCK 850 F04 09-SEP-07
10089 SLACKS 750 F03 31-OCT-08
Table :FABRIC
FCODE TYPE
F04 POLYSTER
F02 COTTON
F03 SILK
F01 TERELENE
Write SQL queries for the following:
(I) Display Garment Description, Price and Type of fabric from above tables.
(II) Display maximum price of SILK garments.
(III) Display Description , Price of all garments where description 2nd character is
“N” and Price is greater than 1525.
(IV) Insert the following record in table FABRIC.
(F05,”LINEN”)
32 Deepak is a Python programmer working for election commission For the coming 4
election he has created a csv file “Election.csv”.
The structure of Election.csv is : [Party_Id, Party_Name, Candidate_Name,
TotalVote]
Where Party_Id is Party ID (integer)

165
Party_name is Party Name (string)
Candidate_Name is name of candidate(string)
TotalVote is total vote received by the candidate
For efficiently maintaining data of the event, Deepak wants to write the following
user defined functions:
Input() – to accept a record from the user and add it to the file Election.csv.
The column headings should also be added on top of the csv file.
Winner() – to read TotalVotes of each record and display the record which has got
maximum number of votes.
As a Python expert, help him complete the task.
SECTION-E
33 CITY CABLE NETWORK has set up its new centre at HYDERABAD for its office and
web based activities. It has four buildings as shown in the diagram below:

A B

C D

Block A 25
Block B 50
Block C 125
Block D 10
Center to center distances Number of Computers
Black A to Block B 50 m
Block B to Block C 150 m
Block C to Block D 25 m
Block A to Block D 170 m
Block B to Block D 125 m
Block A to Block C 90 m
(i) Which type of network is this 1
a)LAN b)PAN c)WAN d)TAN
(ii) Suggest a cable layout of connections between the blocks. 1
(iii) Suggest the most suitable place (i.e. block) to house the server of this organisation 1
with a suitable reason.
(iv) Suggest the placement of the following devices with justification 1
▪ Repeater
166
▪ Hub/Switch
(v) The organization is planning to link its front office situated in a far city in a hilly 1
region where cable connection is not feasible, suggest a way to connect it with
reasonably high speed?
34 (i) What is a file? Why file is needed? 2
(ii) Consider a file, SCHOOL.DAT, containing records of the following structure: 3
[SschoolName, TotalStudents, TotalStaff]
Write a function, TRANSFER(), that reads contents from the file SCHOOL.DAT and
copies only those records where TotalStudents are more than 1000 to the other
file BIGSCHOOLS,DAT. The function should return the total number of records
copied to the file BIGSCHOOL.DAT.
OR
(i) What is file mode. Write python statement to open a binary file so that more
records can be added .
(ii) A Binary file, BOOKS.DAT has the following structure:
{BOOKNO,BOOKNAME,AUTHERNAME,BOOKPRICE]
Where BOOKNO is book number, BOOKNAME is name of the book ,
AUTHERNAME is name of auther and BOOKPRICE is price of book.
Write a user defined function, UPDATE(BOOKNAME), that accepts BOOKNAME as
parameter and updates the price of all the records of BOOKNAME as 500 from the
binary file BOOKS.DAT.
35 (i) Write a sql query to display all records of table SHOP where field Item_brand 1
has no values (blank)
(ii) Hriman wants to write a program in Python to delete the record input by user ( 4
roll no ) in the table named BALVATIKA in MYSQL database, KVS : Each record
contains the following fields:
∙ rno(Roll number )- integer
∙ name(Name) - string
∙ DOB (Date of birth) – Date
∙ Fee – decimal

167
Note the following to establish connectivity between Python and MySQL:
∙ Username - root
∙ Password – KVR@321
∙ Host - localhost
the value of field rno, has to be accepted from the user. Help Hriman to write the
program in Python.
OR
(i) What is the role of primary key. Explain with one example.
(ii) Raman has created table named NATIONALSPORTS in MYSQL database, SPORTS
:
Each record contains the following fields:
∙ GameID(Game number )- integer
∙ Gamename(Name of game) - string
∙ DOG(Date of Game) – Date
∙ Venue(Venue of game) – decimal
Note the following to establish connectivity between Python and MySQL:
∙ Username - root
∙ Password – KVR@321
∙ Host - localhost
Raman , now wants to display all records of venue “Hyderabad”. Help him to write
the python program.
(ii) Hriman wants to write a program in Python to delete the record input by user (
roll no ) in the table named BALVATIKA in MYSQL database, KVS : Each record
contains the following fields:
∙ rno(Roll number )- integer
∙ name(Name) - string
∙ DOB (Date of birth) – Date
∙ Fee – decimal

168
Note the following to establish connectivity between Python and MySQL:
∙ Username - root
∙ Password – KVR@321
∙ Host - localhost
the value of field rno, has to be accepted from the user. Help Hriman to write the
program in Python.

UNSOLVED SAMPLE PAPER-2


CLASS : XII TIME : 03 HOURS

169
SUBJECT : COMPUTER SCIENCE (083) MAXIMUM MARKS : 70

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

SECTION A

Q1 What will be the evaluation of python expression – 2*2**3**2+2 1


a) 130 b) 1026 c) 258 d) 68

Q2 Which of the following is not a valid identifier in python? 1


a) Def b) false c) True d) print

Q3 Given a string s = „Happy Diwali‟, what will be the value of string slice s[::- 1
2]? a) iai pa b) HpyDwl c) lwDypH d) iaiypH

Q4 Which among the following is/are mutable data types in python? 1


a) list b) tuple c) string d) boolean

Q5 Which python statement will delete all elements of a dictionary named 1


d? a) d.delete(all) b) d.delete( ) c) d.clear( ) d) d.empty( )

Q6 The return type of the print() function is: 1


a) string b) integer c) list d) None

Q7 Consider a tuple t = (10, 15, [20, 25], 30, 35). Identify the statement that will result in an 1
error. a) print(t[2]) b) t[2][0] = 200 c) t[3] = 300 d) print(len(t))

170
Q8 Which of the following symbols is not an operator in python? 1
a) // b) * c) ~ d) $

Q9 Which of the following transmission media does not use electric signals to carry data? a) 1
Twisted Pair Cable b) Optical Fiber c) Co-axial cable d) None of the above

Q10 Which of the following connector is used for Ethernet cables in a LAN? 1
a) RJ11 b) RJ45 c) ETH0 d) F Connector

Q11 Which two of the following queries are not valid in MySQL? 1
a) select gender, count(*) form students having age >15;
b) select gender, count(*) from students where age>15 group by gender; c)
select gender, sum(age) from students group by gender having sum(age)>25;
d) select gender, max(age) from students group by gender order by max(age);

Q12 Which of the following is not a DDL command in SQL? 1


a) ALTER b) UPDATE c) DROP d) CREATE

Q13 If a MySQL table named A has 5 columns and 6 rows and another table B has 3 columns and 1
4 rows, then what will be the degree and cardinality of the cartesian product of A and B? a)
15, 24 b) 8, 10 c) 8, 24 d) 5,24

Q14 Which of the following is the unit used to measure data transfer rate of a computer 1
network? a) mps b) bps c) Hertz (Hz) d) None of these

Q15 Which of the following keyword is used along with try block to handle 1
exceptions. a) catch b) handle c) follow d) except

Q16 Which of the following are not correct ways of opening a text file in 1
python? a) F = open(„story.txt‟, „read‟)

b) with open(„story.txt‟) as F:
c) F = open(„story.txt‟, „a+‟)
d) Open(F) = „story.txt‟

171
Q17 and 18 are ASSERTION AND REASONING based questions. Mark the correct choice
as a) Both A and R are true and R is the correct explanation for A

b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

Q17 Answer with (a) to (d) given above. 1


Assertion (A): A function definition can have zero parameters/formal arguments.
Reasoning (R): Parenthesis are not mandatory to call a function with zero
arguments.

18 Answer with (a) to (d) given above. 1


Assertion (A): Number of arguments passed to a function may not match the number of
parameters in the function definition.

Reasoning (R): Function parameters can have default values.

SECTION B

Q19 a) Expand the following abbreviations: 2

i) VoIP ii) XML

b) Name one protocol that can be used to access a computer remotely.


OR
Compare twisted pair cable and fiber optic cable based on – speed, cost, electromagnetic
interference and distance.

Q20 Sameer has written a python program to count the occurrences of elements of a list using a 2
dictionary. But the code has some syntax and logical errors. Re-write the code after
removing all such errors and underline your corrections.
L = [1,2,1,1,2,1,2,3,5,4,1,2,5,4,4,5]
D = {}
foreach x in L:
if x in D:
D[x]=+1

172
Else:
D(x)=1

Q21 Write a function modifyList(L,n) in Python, which accepts a list L of numbers and n is a 2
numeric value. Function should:

• Add 5 to all the values divisible by n


• Subtract 5 from all values not divisible by n
• Display the modified list

Example:
If L= [ 10,11,13,15,20,2] and n=5 then the function should print
[15,6,8,20,25,-3] OR

Write a user defined function palindrome(s) – which takes a string 's' as argument and returns
True if it is a palindrome and False if it is not.

(A palindrome is a word, phrase, or sequence that reads the same backwards as


forwards – example: madam)

22 Predict the output of following python code: 2


S = “BHARAT”
D = {}
for i in range(len(S)):
if i%2==0:
D[S[i]] = i+1
else:
D[S[i]] = i-1
for k,v in D.items():
print(k,v,sep=”#”)

173
Q23 Consider a List L = [10,20,30,[40,50,60],70,80] 2
Write a single line python statement (using List methods only) to:
i. Insert an element 55 as the second last element of the inner list, so that L becomes
[10,20,30,[40,50,55,60],70,80]

ii. Delete the inner list so the L becomes [10,20,30,70,80]

Q24 Consider a MySQL table named “Students” with columns – RollNo, Name, 1x
2
Marks. Write SQL commands to:
=2
(i) Add a new column named „Phone‟ to store the phone number of the students.
(ii) Set RollNo as the primary key of the table.

OR
Consider a MySQL table named “Books” with columns – BookID, BookName, Pages,
Price, Rating. The rating column has data type INT.

Write SQL commands to:


(i) Change the data type of rating column to allow for floating point values (1.0 to 5.0)
(ii) Delete the pages column from the database.

Q25 Write the output of the following python code. 2


def runme(x=1, y=2):
x = x+y
y+=1
print(x, „$‟, y)
return x,y
a,b = runme()
print(a, „#‟, b)
runme(a,b)

SECTION C

174
Q26 Write the output of the following python code. 3
def change(msg):
n = len(msg)
new_msg = „‟
for i in range(0,n):
if not msg[i].isalpha():
new_msg = new_msg + „@‟
else:
if msg[i].isupper():
new_msg = new_msg + msg[i]*2
else:
new_msg = new_msg + msg[i]
return new_msg
new_msg = change(“15 New Men”)
print(new_msg)

Q27 Consider the table given below and write the output of SQL queries (i) to 1
x
(iii). TABLE: PLAYERS
3
P_ID Name Game Gender DoB Salary =3
101 Virat Kohli Cricket M 1990-12-08 12500
102 PV Sindhu Badminton F 1993-01-12 9000
103 Rahul Sharma Cricket M 1988-01-05 10000
104 Saina Nehwal Badminton F 1990-12-25 8500
105 Pankaj Advani Snooker M 1985-06-16 10000
106 Harmanpreet Cricket F 1994-10-10 12500
107 Sardar Singh Hockey M 1982-11-09 9000
108 V Anand Chess M 1982-11-01 12000

i. Select Name, Salary from players where Game not in („cricket‟, „chess‟); ii.
Select sum(Salary) from players where Name like „%i‟;

iii. Select count(distinct Game) from players;

175
Q28 Neha has a very large text file named „log_report.txt‟ which contains more than 50,000 log 3
entries for logins on a local ssh server. Following is a truncated view of the file
log_report.txt. 2022-10-14:22:40:39 Login failed > from 192.168.11.16

2022-10-14:22:20:19 Login success > from 192.168.11.220


2022-10-14:10:14:40 Login success > from 192.168.0.66
2022-10-13:11:19:17 Login failed > from 192.168.0.45
2022-10-14:22:40:39 Login success > from 192.168.11.156


Neha has asked you to help her count the number of failed login attempts. Write a function
countFailedAttempts( ) in python to count the number of lines containing the word „failed‟
in the text file „log_report.txt‟.

OR
Rajat is working on a language statistics project. He has to analyze the writings of a famous
English novelist. He has downloaded a text file named „russel.txt‟ containing major writings
of the author. He is stuck at the problem of counting the number of words starting with „th‟
or „Th‟. Being a computer science student, help Rajat by writing a function countWords( )
in python to count the number of words starting with „Th‟ or „th‟ in the text file „russel.txt‟.

176
29 Consider the table Employees Given below and write SQL queries (i) to (iii) based on it. 3

Table: Employees
emp_id name dob gender salary
101 Simar 1994-01-15 F 26000
102 Alok 1995-10-18 M 17000
103 Hasan 1996-08-21 M 25000
104 Kriti 1993-01-12 F 35000
105 Gulab 1994-02-20 M NULL
106 Jaya 1993-12-01 F 16500

i. To increase the salary of all Female employees by 10%.


ii. To display the name and gender of employees for whom salary is NULL.
iii. To delete the records of all employees born before 01 January 1995.

Q30 Consider a Nested List „Inventory’ in which all the elements are lists of the format – 3
[ItemID, ItemName, Price, Quantity]. Write the following user defined functions in python
to perform the task specified on the stack named „items‟ which is initially an empty list.

• Push_item(Inventory) – It takes nested list Inventory as argument and pushes records of


those items onto stack which have quantity > 100.

• Pop_items() –It repeatedly pops the top element of stack and displays it. Appropriate
message should be displayed when there are no more elements left in the stack.

177
For example, if
Inventory = [[101, „Pen‟, 10, 120],
[102, „Pencil‟, 10, 100],
[103, „Eraser‟, 5, 90],
[104, „Notebook‟, 20, 52],
[105, „Marker‟, 30, 130],
[106, „Sharpener‟, 5, 110],]
After execution of Push_Items(Inventory), Stack should contain:
[[101, „Pen‟, 10, 120], [105, „Marker‟, 30, 130], [106, „Sharpener‟, 5, 110]] ◻
Top The output after Pop_Items() should be:

[106, „Sharpener‟, 5, 110]


[105, „Marker‟, 30, 130]
[101, „Pen‟, 10, 120]
Stack Empty

SECTION D

31 Write the output of SQL queries (i) to (iv) based on the relations Employees and 4
Departments given below:

Table: Employees
emp_id name dob gender salary dept_id
101 Simar 1994-01-15 F 26000 1
102 Alok 1995-10-18 M 17000 2
103 Hasan 1996-08-21 M 25000 1
104 Kriti 1993-01-12 F 35000 1
105 Gulab 1994-02-20 M 15000 3
106 Jaya 1993-12-01 F 16500 4

178
Table: Departments

dept_id dept_name dept_location


1 HR GF-005
2 Sales GF-006
3 Analysis SF-204
4 Training FF-102
i. Display the Average Salary for Male and Female Employees.
ii. Display the Employee Name and Department Name for all employees in descending
order of their salary.

iii. Display the maximum salary of employees born after 31 December 1995. iv. Display
the department id and number of employees for all departments having more than 1
employee.

Q32 Vijay has created a csv file „FOOTBALL.CSV‟ to store player name, matches and goals 4
scored. Write a program in python that defines and calls following user defined functions. i.
addPlayer(name, matches, goals) : Three parameters – name of the player, matches played
and goals scored are passed to the function. The function should create a list object and
append it to the csv file.

ii. highestAverage( ): The function should read the csv file and display the name of
the player with the highest average goals (goals/matches).

SECTION E

179
Q33 Stalwart Solutions Pvt Ltd. is setting up its campus in Noida. The company campus will have 1
x
four blocks – Shivaji (S), Tagore (T), Ashoka (A) and Raman (R). The company has
5
consulted you for networking at the campus. Suggest the best possible solutions for their
=5
questions (a) to (e) based on the information given below.

Computers Blocks Distance in meters


Shivaji (S) 75
Shivaji to Tagore 25
Tagore (T) 125
Shivaji to Ashoka 150
Ashoka(A) 25
Shivaji to Raman 125
Raman (R) 20
Tagore to Ashoka 75
Tagore to Raman 90

a) Suggest the most appropriate block to house the FTP server. Justify your answer.

b) Which Hardware/Software can be installed prevent unauthorized access to FTP server?


c) Suggest the best economical wired transmission medium and draw the cable layout
diagram to connect the four blocks.
d) The company doesn‟t want to use any wired media for connecting the computers
within the Raman block. Which device can be used to provide wireless access, given
that all the machines in this block are wi-fi enabled.

e) The company wishes to minimize the broadcast traffic in the LAN established.
Keeping this in mind, which device will you suggest to connect the computers inside
every block – hub or switch? Why?

180
Q34 (i) What is the difference between text files and binary files? 2+
3
(ii) Shweta had stored all her passwords in one binary file named „PASSWORDS.DAT‟. The
=5
passwords were stored in following format:

[app_name, username, password]


Write a function search(app) that accepts title as a parameter and displays the username and
password for that particular app.

OR

(i) What happens when we try to open a file that does not exist in rb, ab, rb+ and wb+
modes? (ii) Consider a file named „STUDENTS.DAT‟, containing records in following
format: [ADM_NO, NAME, CLASS, SECTION]

Write a function, filterStudents(clas, sec), which takes class and section as parameters and
copies the records matching with that class and section to a new file named
„FILTERED.DAT‟.

Q35 (i) What are the characteristics of a Primary key in RDBMS. Which attribute can act as a 1
+
primary key for a table storing details of all students of a school?
4
=5
(ii) Heerakh wants to write a program in python to add some records into the CRICKET
Table of SPORTS Database. The MySQL server is running on LOCALHOST and the login
credentials are as following:

Username – heerakh
Password – happy The columns of the CRICKET table are described below:
pid (Player ID) – integer
pname (Player Name) – string
innings (Innings Played) – integer
runs (Runs Scored) – integer
wickets (Wickets taken) – integer

181
Help her write a program, which will accept the player details from user and insert a new row
into the table.

OR

(i) What do you mean by term domain in context of RDBMS? What will be the domain for
an attribute called „age‟ of voters of a village?

(ii) Keshav wants to write a program in python to display some records from the CRICKET
Table of SPORTS Database. The MySQL server is running on LOCALHOST and the login
credentials are as following:

Username – keshav
Password – karma

The columns of the CRICKET table are described below:


pid (Player ID) – integer
pname (Player Name) – string
innings (Innings Played) – integer
runs (Runs Scored) – integer
wickets (Wickets taken) – integer

Help him write a program, which will display the name (only name) of all players who have
player 100 or more innings.

o——| End of Paper |——o

182
UNSOLVED SAMPLE PAPER-3
CLASS : XII TIME : 03 HOURS
SUBJECT : COMPUTER SCIENCE (083) MAXIMUM MARKS : 70

General instructions:
1. Please check this question paper contains 35 questions.
2. The paper is divided into 4 Sections- A, B, C, D and E.
3. Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
4. Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
5. Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
6. Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
7. Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
8. All programming questions are to be answered using Python Language only.
Ques. Question Marks
No.
SECTION A
1 State True or False: 1
“Python is a case sensitive language i.e. upper and lower cases are treated differently.”

2 In a table in MYSQL database, an attribute Aof datatype char(20)has the value 1


“Rehaan”. The attribute B of datatype varchar(20) has value “Fatima”. How many
characters are occupied by attribute A and attribute B?
a. 20,6 b. 6,20
c. 9,6 d. 6,9

3 What will be the output of the following statement: 1


print(5-2**2**2+99//11)
a. -20 b. -2.0
c. -2 d. Error
4 Select the correct output of the code: 1
for i in "QUITE":
print(i.lower(), end="#")
a. q#u#i#t#e# b. ['quite#‟] c. ['quite'] # d. [„q‟]#[„u‟]#[„i‟]#[„t‟]#[„e‟]#

183
5 In MYSQL database, if a table, Workshas degree 3 and cardinality 3, andanother table, 1
Jobs has degree 3 and cardinality 3, what will be the degree and cardinality of the
Cartesian product of Worksand Jobs?
a. 9,9 b. 6,6
c. 9,6 d. 6,9

6 A set of rules that governs data communication in computer networks is called … 1


a. Standard b. protocol c. Stack d. none of these

7 Given the followingdictionaries 1

dict_exam={"Exam":"AISSCE", "Year":2023} dict_result={"Total":500,


"Pass_Marks":165}

Which statement will merge the contents of both dictionaries?


a. dict_exam.update(dict_result)
b. dict_exam + dict_result
c. dict_exam.add(dict_result)
d. dict_exam.merge(dict_result)
8 Consider the statements given below and then choose the correct outputfrom the 1
given options:
pride="#Azadi Ka Amrut@75"
print(pride[-2:2:-2])
Options

a. 7TRAa d
b. 7tRAa d
c. 7TrAa d
d. 7trAa d
9 Which of the following statement(s) would give an error after executing the 1
Following code?
S="Welcome to class XII" # Statement 1
print(S) # Statement 2
S="Thank you" # Statement 3
S[0]= '@' # Statement 4
S=S+ "Thank you" # Statement 5

a. Statement 3 b. Statement 4
c. Statement 5 d. Statement 4 and 5

184
10 What will be the output of the following code? 1

a. Delhi#Mumbai#Chennai#Kolkata# b. Mumbai#Chennai#Kolkata#Mumbai#

c. Mumbai# Mumbai #Mumbai # Delhi# d. Mumbai# Mumbai #Chennai # Mumbai

11 Fill in the blank: 1


The modem at the received computer end acts as a .
a. Model
b. Modulator
c. Demodulator
d. Convertor

12 Consider the code given below: 1

Which of the following statements should be given in the blank for#Missing Statement,
if the output produced is 110?
Options:

a. global a
b. global b=100
c. global b
d. global a=100

185
13 State whether True or False : 1
When you connect your mobile phone with your laptop, the network formed is called as
LAN.
14 Fill in the blank: 1

is a candidate key which is not selected as a primary key.


a. Primary Key b. Foreign Key c. Candidate Key d. Alternate Key

15 Fill in the blank: 1

is the transfer of small pieces of data across various networks.

16 The correct syntax of seek()is: 1


a. file_object.seek(offset [, reference_point])
b. seek(offset [, reference_point])
c. seek(offset, file_object)
d. seek.file_object(offset)
Q17 and 18 are ASSERTION AND REASONING based questions. Markthe 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):- Dictionaries are mutables.. 1
Reasoning (R):- The contents of the dictionary can be changed after it has been created

18 Assertion (A):- If the arguments in a function call statement match the number 1
and order of arguments as defined in the function definition, such argumentsare called
positional arguments.
Reasoning (R):- During a function call, the argument list first contains default
argument(s) followed by positional argument(s).
SECTION B
19 Expand the following terms related to Computer Networks: 1+1=2

(i) a. SMTP b. POP

(ii) Out of the following, which is the fastest wired and wireless medium of
transmission?
Infrared, coaxial cable, optical fiber, microwave, Ethernet cable
OR

(i) Differentiate between web server and web browser.


(ii) Give one advantages and two disadvantages of star topology.

186
20 The code given below accepts a number as an argument and returns the reverse number. 2
Observe the following code carefully and rewrite it after removing all syntax and logical
errors. Underline all the corrections made.

Def oddtoeven(L)
For i in range(len(L)):
if(L[i]%2 !=0):
L[i] = L[i]*2
print(L)
21 Write a function count (city) in Python, that takes the dictionary, PLACES as an 2
argument and displays the names (in lowercase) of the places whose names are less than
7 characters.
For example, Consider the following dictionary

City ={1:"Delhi",2:"London",3:"Kolkata",4:"NewYork",5:"Moscow"}
The output should be: “Delhi”, ”London”, ”Moscow”
OR
Write a function, Words_Length(STRING), that takes a string as an argument and
returns a list containing length of each word of a string.For example, if the string is
"this too shall pass", the tuple will have (4, 3, 5,4)
22 Predict the output of the following code: 2

23 Predict the output of the Python code given below: 1+1=2

OR
187
Predict the output of the Python code given below:

24 Ms. Shweta has just created a table named “Employee” containing columns Empno, 2
Ename,Department and Salary.

After creating the table, she realized that she has forgotten to apply primary key
constraint in Empno column. Help her in writing an SQL command toadd a primary
key constraint to Empno column to the table Employee.
OR
Angel has created table School with column sid,Student_name,DOB,Fee,City. Later
she realized that she has forgotten to apply primary key in sid, also she wants to
change the column name from sid to student_id. Help her to change the column
name to student_id from sid and also apply primary key in it.
25 Predict the output of the following code: 2

188
SECTION C
26 Predict the output of the Python code given below: 3

27 Consider the table MEMBER given below and write the output of the SQLqueries that 1*3=3
follow.

MID MNAME AG GENDE GAME PAY DOAPP


E R
5246 AMRITA 35 FEMALE CHESS 900 2006- 03-27
4687 SHYAM 37 MALE CRICKET 1300 2004- 04-15
1245 MEENA 23 FEMALE VOLLEYBAL 1000 2007- 06-18
L
1622 AMRIT 28 MALE KARATE 1000 2007- 09-05
1256 AMINA 36 FEMALE CHESS 1100 2003- 08-15
1720 MANJU 33 FEMALE KARATE 1250 2004- 04-10
2321 VIRAT 35 MALE CRICKET 1050 2005- 04-30

(i) SELECT COUNT(DISTINCT GAME) FROM MEMBER;


(ii) SELECT MNAME, GAME FROM MEMBER WHERE
DOAPP<"2007-01-01" AND CNAME LIKE "AM%";
(iii) SELECT MNAME, AGE, PAY FROM CLUB WHEREGENDER =
"FEMALE" AND PAY BETWEEN 1000 AND 1200;
28 Write a function in Python to read a text file, Story.txtand displays those lines which 3
begin with the word „Once‟.
OR
Write a method COUNTLINES () in Python to read lines from text file „FILE.TXT‟ and
display the lines which are starting with any vowel.

189
29 Consider the table HRMgiven below: 1*3=3
Table: HRM

ID Name Designation Salary Incentive


P01 Mohit Manager 99000 5800

P02 Rakesh Clerk 70000 2600

P03 Suresh Superviser 48000 NULL


P04 Sahil Clerk 61000 2900

P05 Rubeena Superviser 50000 3100

Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of all employees who are not getting any
incentive.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all
employees. The column heading „Total Salary‟ should alsobe displayed.
(iii) Delete the record of Supervisors who have salary less than
50000

30 A list contains following record of a customer: 3


[Patient_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack
named status:
(i) Push_element() - To Push an object containing name and Phone number of
patients who live in Delhi to the stack
(ii) (ii) Pop_element() - To Pop the objects from the stack and display them. Also,
display “Stack Empty” when there are no elements in the stack.
For example: If the lists of customer details are:
[“Kabir”, “99999999999”,”Goa”]
[“Neha”, “8888888888”,”Delhi”]
[“Mehul”,”77777777777”,”Delhi”]
[“Asimita”, “1010101010”,”Goa”]
The stack should contain
[“Neha”, “8888888888”]
[“Mehul”,”77777777777”]

The output should be:


[“Neha”, “8888888888”]
[“Mehul”,”77777777777”]
Stack Empty

190
SECTION D
31 Consider the Item and company Table 1*4=4
Table : Item
Icode IName Price Rating Cid
I01 Mobile 12000 5 A01
I02 TV 20000 4 A02
I03 OVEN 5000 7 A03
I04 EARPHONE 5000 8 A04
I05 WATCH 10000 6 A05
I06 CAMERA 11000 6 A06

Table : Company

CId Cname
A01 Apple
A02 Samsung
A03 Philips
A04 Xiomi
A05 Vivo
A06 Oppo
Write SQL queries :
i. Display item name and company name from the tables Item and Company
ii. Display the structure of table Item.
iii. Display the maximum rating for each company.
iv. Display the item name, price and rating in ascending order of rating.

32 Vihaan is a Python programmer working in a school. For the Annual Sports Event, 4
he has created a csv file named Sports.csv, to store theresults of students in different
sports events. The structure of Sports.csv is :
[Player_Id, Player_Name, Game, Result]
Where
Player_Idis Player ID (integer)
Player_nameis Player Name (string)
Game is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Winner', 'Defeated'or 'NO
result'
For efficiently maintaining data of the event, Vihaan wants to write thefollowing user
defined functions:
input() – to input a record from the user and add it to the file Sports.csv. The column
headings should also be added on top of thecsv file.
Winner_Count()– to count the number of player who have won any event.
As a Python expert, help him complete the task.

191
SECTION E
33 NMS Training Institute is planning to set up its Centre in Bhubaneswar with four 1*5=5
specialized blocks for Medicine, Management, Law courses along with an Admission
block in separate buildings. The physical distances between these blocks and the
number of computers to be installed in these blocks are given below. You as a network
expert have to answer the queries raised by their board of directors as given in (i) to
(iv).

Shortest distances between various locations in meters:

Admin Block to Management Block 50

Admin Block to Medicine Block 30

Admin Block to Law Block 65

Management Block to Medicine Block 40

Management Block to Law Block 125

Law Block to Medicine Block 35

Number of Computers installed at various locations are as follows:

Admin Block 250

Management Block 100

Medicine Block 45

Law Block 95

(i). Suggest the most suitable location to install the main server of this institution to get
efficient connectivity.
(ii). Suggest by drawing the best cable layout for effective network connectivity of the
blocks having server with all the other blocks.
(iii). Suggest the device to be installed in each of these buildings for connecting
192
computers installed within the building.

(iv) Suggest the most suitable wired medium for efficiently connecting each computer
installed in every building out of the following network cables:

 Coaxial Cable
 Ethernet Cable
 Single Pair
 Telephone Cable.
(v) Suggest a device/software to be installed to take care of data security.

34 (i) Differentiate between w and a file modes in Python. 2+3=5

(ii) Consider a file, Movie.DAT, containing records of the following structure:


[MovieName, Banner, YearofRelease]
Write a function, CaptureData(), that reads contents from the file Movie.DAT and
copies the records with Banner as “YashRaj” to the file named Yashrajfilms.DAT.
The function should return thetotal number of records copied to the file
Yashrajfilms.DAT.
OR
(Option for part (ii) only)
A Binary file, CINEMA.DAThas the following structure:
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPEis Movie Type
Write a user defined function, find Type(mtype), that accepts mtype
as parameter and displays all the records from the binary file
CINEMA.DAT, that have the value of Movie Type as mtype.

193
35 (i) What do you mean by tuple in relation data model.
(ii) Rehaan wants to write a program in Python to insert the 1+4=5
followingrecord in the table named EMP in MYSQL database,
Company:
a. eno(Empno )- integer
b. ename(Name) - string
c. DOB (Date of birth) – Date
d. Salary – float
Note the following to establish connectivity between Python andMySQL:
e. Username - root
f. Password – password
g. Host - localhost
The values of fields eno, name, DOBand salary has to be accepted from the user. Help
Rehaan to write the program in Python.
OR

(i) Give one difference between Primary key and Unique.


(ii) Gurmehar has created Product in MYSQL database,
Product:
a. Pno(Product Number )- integer
b. Pname(Product Name) - string
c. DOM (Date of Manufacture) – Date
d. Price – float
Note the following to establish connectivity between Python andMySQL:
e. Username - root
f. Password – password
g. Host – localhost
Gurmehar, now want to display the records of the product whose price is more than
10000. Help Gurmehar to write the program in
python

***END***

194

You might also like