Quik RevisionCS Class12
Quik RevisionCS Class12
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.
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)
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.
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!"
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
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).
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
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.
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();
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)])
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
• 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=”# “)
20
str1 = “Waha”
print(str1[:3] + “Bhyi” + str1[-3:])
a. Wah Bhyi Wah b. Wah Bhyi aha c. WahBhyiWah d. WahBhyiWaha
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.
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
[“ ” ”<function’s docstring>” “ “]
<statements> [<statements>]
……………………..
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.
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()
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.
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:-
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:-
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.
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)
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
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-
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=’@’)
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
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
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
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
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.
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
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
OPEN THE FILE------> PROCESSING THE FILE ------ >CLOSE THE FILE
OPENING FILES
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
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
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()
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
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)
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)
print(line.strip())
44
Ans 2 The output will be
Hello,world!
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 .
ii) File.write(“abc”)
Ans5Line1
Line3
Line 6
Line 4
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:
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.
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: -
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>)
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.
48
f1=open("my_bin1.bin","rb")
D2=pickle.load(f1)
print(D2)
f.close()
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
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
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
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.
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
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
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:
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 : ")
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:
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
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() :
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)
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.
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.
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)
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.
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.
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.
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.
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
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)
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.
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
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
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
81
VERY SHORT ANSWER TYPE QUESTIONS(1-MARK)
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
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)
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
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)
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.
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
1. The ‘Grand Plaza ’ Mall has a computer network. The network is in one building. Namethis type
of network( out of LAN/MAN/WAN).
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
ii) Suggest the most suitable place (i.e. buildings) to house the server of thisorganization.
a) Repeater b) Hub/Switch
6. Write one example each of URL and IP address.
90
ANSWER KEY
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
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
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.
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.
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 System:
A database along with the DBMS is referred to as database system
97
Eg.
Table: Student (Relation)
Attributes
102 Mohit 37
103 Aryan 23
104 Ruhi 56
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
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
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.
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 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.
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.
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:
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
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
DATABASE COMMANDS
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;
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
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.
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
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.
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;
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)
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.
Examples:
Select avg(gross) from employee;
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:
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.
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:
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)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;
(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
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
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.
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.
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.
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
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:
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
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
COURSES
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.
Q-4 Write SQL Command for (a) to (e) and output of (f)
TABLE : 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);
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.
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")
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()
In this pattern you can write {} where the value is placed followed by .format(values).
Consider the following code:
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
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.
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
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()
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
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.
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()
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( )
134
General Instructions:
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
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
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")
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:
SECTION C
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
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.
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
142
1005 LAPTOP 600 35000 HP T03
(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:
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:
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
9. Ans: d. Statement-4 1
18. Ans: (a) Both A and R are true and R is the correct explanation for A 1
SECTION B
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.
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.
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
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)
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#@
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())
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
2.6KM
Warehousing Training Campus
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())
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()
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
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
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.
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
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
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);
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
SECTION B
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:
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.
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]
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.
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‟;
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
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
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.
• 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:
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
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.
a) Suggest the most appropriate block to house the FTP server. Justify your answer.
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:
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
Help him write a program, which will display the name (only name) of all players who have
player 100 or more innings.
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.”
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
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#
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
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
(ii) Out of the following, which is the fastest wired and wireless medium of
transmission?
Infrared, coaxial cable, optical fiber, microwave, Ethernet cable
OR
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
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.
189
29 Consider the table HRMgiven below: 1*3=3
Table: HRM
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
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).
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.
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
***END***
194