12th CS
12th CS
Class 12
COMPUTER
SCIENCE
DIRECTORATE OF EDUCATION
Govt. of NCT, Delhi
2024-25
List of Group Leader and Subject- Experts for
Preparation/ Review of Support Material
Class – XII ( 2024-25)
Subject: Computer Science
D
conversion of a variable is done
words and have special
explicitly by using some built-in
ata
meaning for interpreter.
T
functions. ● Identifiers are the names
yp
De
given to variables, objects,
es
fin
e
classes or functions.
● Literals are the data items
Basic that have a fixed value.
● break terminates the loop it thon ● Operators are the symbols
in Py
lies within. PYTHON s used that perform specific
● continue forces the next Jump Statements Term operation on the variables.
2
BASICS
iteration to take place,by ● Variables are not storage
skipping further statements Opera containers in Python. They
for that specific value. nt
tions hold the memory location
Sta teme where the value is stored.
ional
C ondit
Lo
op
s
● Concatenation (+ symbol is
Conditional Statement: if-else,
if-elif-else, if-elif-...else used)
● while loop is known as
Syntax: conditional loop that will ● Replication (* symbol is used)
if : run till the condition is true.
<statement> ● Membership operator (in, not
● for loop is a counting loop
elif : that repeats a specific in)
<statement> number of times.
else: ● Comparison Operators (==,!=,
< statement> <=, >=)
CHAPTER- 1 PYTHON REVISION TOUR
ABOUT PYTHON:
1. Python is a high-level programming language developed by Guido Van
Rossum. The language was released in February 1991 and got its name
from a BBC comedy series “Monty Python’s Flying Circus”.
2. It is an interpreted and platform-independent language i.e. the same
code can run on any operating system.
3. It can be used to follow both procedural and object-oriented approaches
to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.
● Token / Lexical Unit: The smallest individual unit in a Python program is known as Token or Lexical
Unit. A token has a specific meaning for a Python interpreter. Examples of tokens are Keywords,
Identifiers, Literals, Operators and Punctuators.
● Keywords: Keywords are reserved words and have special meanings for Python Interpreters. Each
keyword can be used only for the purpose to which it has been assigned. Examples: and, while,
del, with, True, None, False, return, try, etc.
● Identifiers: These are the names given to variables, objects, classes, functions, etc. There are
some predefined rules for forming identifiers that should be followed, or else the program will
raise Syntax errors.
● 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 ‘None’ to indicate the absence of value.
● 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:
3
NOTE: When we compare two variables pointing to the same value, then both Equality (==) and
identity (is) will return True. But when the same value is assigned to different objects, then the
== operator will return True and ‘is’ operator will return False.
● Punctuators: These are the symbols that are used to organize sentence structure in programming
languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () , .
● 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.
● 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.
● Dynamic Typing: It means that it will be decided
at the run time which type of value the variable
will store. It is also called implicit conversion.
For example,
Here, we need not 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 based on the value
of a and b.
● 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
4
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.
The above data types are classified into two basic categories: Mutable data types and Immutable data
types. Mutable data types are those data types whose value can be changed without creating a new
object. It means mutable data types hold a specific memory location and changes are made directly to
that memory location. Immutable data types are those data types whose values cannot be changed
after they are created. It means that if we make any change in the immutable data object then it will be
assigned a new memory location.
1. In Numeric data types, Integers allow storing whole numbers only which can be positive or
negative. Floating point numbers are used for storing numbers having fractional parts like
temperature, area etc. In Python, Floating point numbers represent double precision i.e. 15-digit
precision. Complex numbers are stored in python in the form of A + Bj where A is the real part
and B is the imaginary part of complex numbers.
2. A dictionary is an unordered set of comma-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 the values of the keys can be changed.
5
3. Boolean allows to store 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
STRING:
● In Python, a string is a sequence having Unicode characters and is immutable. Any value
written/assigned in “ “ or ‘ ‘ is considered as a string in python.
● Each character is at a particular place called Index having a starting value of 0 if traversing
forward. Indexing can also be done in a backward direction starting from the last
element/character of the string where the starting value will be -1 in the backward direction.
● Joining operation in a string can be done between two strings only. We cannot join a number
and a string using ‘+’. Concatenation operation in a string can be done between a string and
a number only using ‘*’.
● Slicing is defined as extracting a part of a string from the main string using unique index
positions starting from 0. In slicing we can specify start, stop and step values to extract a
substring from the given string.
LIST:
● Lists can hold multiple elements of the same or different data types.
● Lists are mutable, which means the values can be updated without assigning a new memory
location. It is denoted by square brackets [].
● We can add (join) a list with another list only and not with int, float, or string type. Joining of
2 or more can be done using ‘+’. We can concatenate a list with an integer only. Concatenation
(Replication) can be done in a list using ‘*’.
TUPLE:
● Tuples can also hold multiple elements of the same or different data types like lists but tuples
are immutable. These are denoted by round brackets ().
● If multiple values are assigned to a single variable then by default the type of variable will be
tuple.
● Tuples can be traversed in the same way as Strings using a ‘for’ loop.
6
● Slicing, Concatenation (Replication) and Joining operations can also be performed on Tuples
in the same way as Strings.
len (string) It returns the number of characters in any string including spaces. e.g. if s =
‘hello’, then len(s) will result in 5.
capitalize() It is used to convert the first letter of sentences into capital letters. e.g. s =
‘python’, then s.capitalize() will result in ‘Python’.
title() It is used to convert the first letter of every word in a string into capital letters.
e.g. s = ‘hello python’, then s.title() will result in ‘Hello Python’.
upper() It is used to convert the entire string into capital case letters. e.g. s = ‘python’,
then s.upper() will result in ‘PYTHON’.
lower() It is used to convert entire strings into small case letters. e.g. s = ‘PYTHON’, then
s.lower() will result in ‘python’.
count(substring, It is used to find the number of occurrences of a substring in a string. We can also
[start], [end]) specify the starting and ending index to specify a range for searching substring.
e.g. s = ‘he is playing’, then s.count(‘i’) will result in 2.
This function returns the starting index position of the substring in the given
find(substring, string. Like count(), we can specify the range for searching using the starting and
[start],[end]) ending index. It returns -1 if the substring is not found. e.g. s = ‘hello python’,
then s.find(‘p’) will return 6 and s.index(‘z’) will return -1
index(substring) It returns the starting index position of the substring. If the substring is not found
then it will return an error “Substring not found”. e.g. s = ‘hello python’, then
s.index(‘p’) will return 6 and s.index(‘z’) will return ValueError:‘Substring not
found’.
isalnum() It is used to check if all the elements in the string are alphanumeric or not. It
returns either True or False. e.g. s = ‘abc1’, then s.isalnum() will return True.
islower() It returns True if all the elements in the string are in lower case, otherwise returns
False. e.g. if s = ‘python’, then s.islower() will return True.
isupper() It returns True if all the elements in the string are in upper case, otherwise
returns False. e.g. if s = ‘PYTHON’, then s.isupper() will return True.
isspace() It returns True if all the elements in the string are spaces, otherwise returns False.
e.g. if s = ’ ‘, then s.isspace() will return True.
7
isalpha() It returns True if all the elements in the string are alphabets, otherwise returns
False. e.g. if s = ‘python’, then s.isalpha() will return True.
isdigit() It returns True if all the elements in the string are digits, otherwise returns False.
e.g. if s = ‘1234’, then s.isdigit() will return True.
split([sep]) This function is used to split the string based on the delimiter /separator value
which is space by default. It returns a list of n elements where the value of n is
based on delimiter. The delimiter is not included in the output. e.g. if s = ‘hello
python world’, then s.split() will return [‘hello’,’ python’, ’world’]
partition(sep) It divides the string into three parts: head, separator and tail, based on the sep
value which acts as a delimiter in this function. It will always return a tuple of 3
elements. The delimiter/separator will be included as the 2nd element of the
tuple in the output. e.g. if s = ‘hello world python’, then s.partition(‘py’) will
return (‘hello world ‘, ’py’, ‘thon’)
replace(old, new) It is used to replace an old substring inside the string with a new value.
e.g. if s = ‘Good morning’ then s.replace(‘mor’, ’eve’) will return ‘Good evening’.
strip([chars]) It returns a copy of a string after removing leading and trailing white spaces by
default. We can also provide chars value if we want to remove characters instead
of spaces. If chars are given then all possible
combinations of given characters will be checked and removed. e.g. s = ‘good
morning good’, then s.strip(‘dg oo’) will return mornin
lstrip([chars]) It returns a copy of the string after removing leading white spaces. If the chars
value is given then characters will be removed. e.g. s = ‘good morning good’,
then s.lstrip(‘dgoo’) will return ‘ morning good’
rstrip([chars]) It returns a copy of a string after removing trailing white spaces. If the chars value
is given then characters will be removed. e.g. s = ‘good morning good’, then
s.rstrip(‘dgoo’) will return ‘good morning’
LIST FUNCTIONS:
index() Used to get the index of the first matched item from the list. It returns the index
value of an item to search. If the item is not found, it will return ValueError: n is
not in the list. e.g. x = [10,20,30,40], then x.index(20) will be 1.
append()
Used to add items to the end of the list. It will add the new item but not return
any value. e.g. x = [10,20,30], then x.append(40) will be [10,20,30,40].
8
extend() Used for adding multiple items. With extend we can add multiple elements but
only in the form of a list to any list. Even if we want to add a single element it will
be passed as an element of a list. e.g. x = [10,20,30] then x.extend([40,50]) will
be [10,20,30,40,50]
insert() Used to add elements to a list at a position of our choice i.e. we can add new
elements anywhere in the list. e.g. x = [10,20,30] then
x.insert([2,40]) will be [10,20,40,30].
pop() Used to remove an item from a list. It raises an exception if the list is already
empty. By default, the last item will be deleted from the list. If an index is
provided then the given indexed value will be deleted. e.g. x = [10,20,30,40,50]
then x.pop() will be 50.
remove() Used to remove an element when the index is not known and we want to delete
it by providing the element value itself. It will remove the first occurrence of a
given item from the list and return an error if there is no such item in the list. It
will not return any value. e.g. x = [1,2,3,4,5] then x.remove(4) will be [1,2,3,5].
clear() Use to remove all the items of a list at once and the list will become empty. e.g. x
= [10,20,30] then x.clear() will be [ ].
Del
del statement is used to delete the structure of an existing list. e.g. x = [10,20,30]
then del x will delete the structure of x and will return nothing. While trying to
access x we will get NameError.
count() Used to count the number of occurrences of the item we passed as argument. If
an item does not exist in the list, it returns Zero. e.g. x = [1,2,3,4,2,1,3,4,4] then
x.count(4) will return 3.
reverse() Used to reverse the items of a list. It made the changes in the original list and did
not return anything. e.g. x = [1,2,3,4] then x.reverse() will be [4,3,2,1]
sort()
Used to sort the items of a list. It made the changes in the original list and sort
the items in increasing order by default. We can specify the reverse argument as
True to sort in decreasing order. e.g. x =
[1,5,2,3,7,4] then x.sort() will be [1,2,3,4,5,7].
sorted() Used to sort the items of a sequence data type and returns a list after sorting in
increasing order by default. We can specify the reverse argument as True to sort
in decreasing order. e.g. x = [1,5,2,3,7,4] then sorted(x) will return a sorted list
as[1,2,3,4,5,7]
9
TUPLE FUNCTIONS:
len() Returns the number of elements in a tuple. e.g. x = (1,2,3,4,5,6) then len(x) will
be 6.
max() Returns the element having a maximum value in the tuple. e.g.
x = (100,30,250,40,110) then max(x) will be 250.
min() Returns the element having minimum value e.g. x = (100,30,250,40,110) then
min(x) will be 30.
index() Returns index value of given element in the tuple. If the item doesn’t exist, it will
raise a ValueError exception. e.g. x = (10,20,30,40) then x.index(30) will be 2.
count() It returns the number of occurrences of the item passed as an argument. If not
found, it returns Zero. e.g. x = (10,20,30,10,10,20) then x.count(20) will be 2.
sorted() Used to sort the items of a sequence data type and returns a list after sorting in
increasing order by default. We can specify the reverse argument as True to sort
in decreasing order. e.g. x = (100,30,250,40,110) then sorted(x) will return a
sorted list as [30,40,100,110,250].
Dictionary Functions:
clear() Used to remove all items from the dictionary. e.g. d = {1:‘Delhi’, 2:‘Mumbai’, 3:
‘Kolkata’, 4: ‘Chennai’} then d.clear() will clear all the elements of d and d will
be empty {}.
get() Used to access the value of a given key, if the key is not found it raises an
exception. e.g. d = {1: ‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’} then
d.get(4) will return ‘Chennai’.
items()
Used to return all the items of a dictionary in the form of tuples.e.g. d = {1:
‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’} then d.items() will return [(1,
Delhi),(2, Mumbai),(3, Kolkata),(4, Chennai)]
keys() Used to return all the keys in the dictionary as a sequence of keys. e.g. d = {1:
‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’} then d.keys() will return
[(1,2,3,4)]
10
values() Used to return all the values in the dictionary as a sequence of values.
e.g. d = {1: ‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’} then d.values() will
return [(‘Delhi, ’Mumbai, ’Kolkata, ’Chennai’)]
update()
Merges the key: value pair from the new dictionary into the original dictionary.
The key: value pairs will be added to the original dictionary, if any key already
exists, the new value will be updated for that key. e.g. d
= {1: ‘Delhi’, 2: ‘Mumbai’} and d1 = {3: ‘Kolkata’, 4: ‘Chennai’} then
d.update(d1) will return {1: ‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’}
fromkeys() Returns a new dictionary with the given set of elements as the keys of the
dictionary. e.g. x = (1,2,3,4) , y = ‘Delhi’ then d = dict.from keys(x,y) will result in
{1: 'Delhi', 2: 'Delhi', 3: 'Delhi', 4: 'Delhi'}
popitem() Used to remove the last added dictionary item (key: value pair) e.g. d = {1:
‘Delhi’, 2: ‘Mumbai’, 3: ‘Kolkata’, 4: ‘Chennai’} then d.popitem() will return
d.popitem() will return (4, ’Chennai)
sorted() Used to sort the key: value pair of dictionary in either ascending or descending
order based on the keys. e.g. d = {3: ‘Kolkata’,1: ‘Delhi’, 2: ‘Mumbai’, 4:
‘Chennai’} then sorted(d) will return [1,2,3,4]
Statements in Python:
Instructions given to computers to perform any task are called statements. Python, we have 3 types of
statements:
● EMPTY STATEMENTS: When a statement is required as per syntax but we don’t want to
execute anything or do not want to take any action we use the pass keyword.
Whenever a pass is encountered, the Python interpreter will do nothing and control will
move to the next statement in the flow of control.
● SIMPLE STATEMENT: All the single executable statements in Python are Simple Statements.
● COMPOUND STATEMENTS: A group of statements executed as a unit are called compound
statements. Compound statements have a Header which begins with a keyword and ends
with a colon (:). There can be at least one or more statements in the body of the compound
statement, all indented at the same level.
11
Conditional statements in Python:
When the execution of any statement depends on some condition then such statements are considered
as Conditional Statements. In Python, we use the if keyword for Conditional statements.
● It must contain a valid condition
which evaluates to either True or
False. The condition must be
followed by Colon (:), it is mandatory.
The statement inside ‘if’ must be at
the same indentation level.
● if statement can be of many forms:
● if without a false statement
● if with else
● if with elif
● Nested if
12
● break keyword is used to take control out of the loop for any given condition. When break is
encountered in a loop the flow of control jumps to the very next statement after the loop.
● continue keyword is used to skip the execution of remaining statements inside the loop and
takes control to the next iteration.
a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is –Fun
13
6 Which of the following is a valid keyword in Python?
a) false
b) return
c) non_local
d) none
14
13 The return type of the input() function is
a) string
b) Integer
c) list
d) tuple
14 Which of the following operators cannot be used with string data type?
a) +
b) In
c) *
d) /
15 Consider a tuple tup1 = (10, 15, 25, 30). Identify the statement that will result in an error.
a) print(tup1[2])
b) tup1[2] = 20
c) print(min(tup1))
d) print(len(tup1))
15
20 What will be the output of the following statement:
print(3-2**2**3+99/11)
a) 244
b) 244.0
c) -244.0
d) Error
a) 12345678
b) 123456789
c) 2345678
d) 23456789
16
26 Identify the output of the following Python statements.
a) 31
b) 33
c) 36
d) 39
27
a) 2
b) 3
c) 4
d) 20
17
31 Identify the valid declaration of L:
L = [‘Mon’, ‘23’, ‘hello’, ’60.5’]
a) dictionary
b) string
c) tuple
d) list
32 Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90).
What will be the output of print (tup1 [3:7:2])?
a) (40,50,60,70,80)
b) (40,50,60,70)
c) [40,60]
d) (40,60)
33 If the following code is executed, what will be the output of the following code?
34 Which of the following statement(s) would give an error during the execution of the
following code?
a) Statement 1
b) Statement 2
c) Statement 3
d) Statement 4
35 Consider the statements given below and then choose the correct output from the given
options:
a) ndsr
b) ceieP0
c) ceieP
d) yndsr
18
print (Listofnames [-1:-4:-1])
a) (1,2,[3.14,2],3)
b) (1,2,[1,3.14],3)
c) (1,2,[1,2],3.14)
Error Message
Which of the following statements is/are not Python keywords?
a) False
b) Math
39
c) WHILE
d) break
40
What will be the result of following the Python code?
19
42 Which of the following statement(s) would give an error after executing the following
code?
a) Statement 2
b) Statement 4
c) Statement 3
d) Statements 2 and 4
a) False
b) True
c) Error
d) None
44 Write a statement in Python to declare a dictionary whose keys are 1, 2, and 3 and whose
values are Monday, Tuesday and Wednesday respectively.
45
Assertion(A): List is an immutable data type
Reasoning(R): When an attempt is made to update the value of an immutable variable,
the old variable is destroyed and a new variable is created by the same
name in memory
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
20
46 Assertion (A): Python Standard Library consists of various modules.
Reasoning(R): A function in a module is used to simplify the code and avoid repetition.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A c) A is
True but R is False
d) A is false but R is True
2
Rewrite the following code after removing all syntax error(s):
21
5
Write the Python statement for each of the following tasks using BUILT-IN
functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop/period or not.
6 A list named studentAge stores the age of students in a class. Write the Python command
to import the required module and display (using the built-in function) the most common
age value from the given list.
7
Find the output of the following code:
8
Predict the output of the Python code given below:
22
Lab Exercises
3
Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a
numeric value by which all elements of the list are shifted to the left. Sample Input Data
of the list
Arr= [ 10,20,30,40,12,11],
n=2 Output:
Arr = [30,40,12,11,10,20]
23
Topics to be covered
● Introduction
● Types of Functions
● Create User User-defined Function
● Arguments And Parameters
● Default Parameters
● Positional Parameters
● Function Returning Values
● Flow of Execution
● Scope of Variable
24
25
Function
Reusable block of code that performs a specific task. For example: len(), print(), min(), max(), sorted
() , type() etc.
Types of Functions
Calling a function:
Calling the function performs the specified actions with the indicated parameters
● Arguments: Information can be passed into functions as arguments. Arguments are specified
after the function name, inside the parentheses. You can add as many arguments as you
want, just separate them with a comma.
● Actual Parameters (Arguments) are values supplied to the function when it is invoked/called
26
● Formal Parameters are variables specified in function definitions to receive values from
arguments passed during function calls.
Example 1:
Output:
In the above example, a user-defined function “function1” has been defined that receives one
argument. Once the function is defined, it can be called any number of times with different
arguments.
Formal argument: x
Actual argument:
Example 2: Write a function ADD(A, B) that receives two integer arguments and prints their sum.
Output:
return keyword:
In Python, the `return` keyword is used in functions to specify the value that the function will
return when it is called. When a function is executed, it may perform some computations or
operations, and the result can be sent back to the caller using the `return` statement.
27
Here's what you need to know about the `return` statement:
1. Returning a Value:
When you want to return a specific value from the function, you can use the `return`
statement followed by the value you want to return.
Note: The function will stop executing immediately after the `return` statement is
encountered, and the value will be passed back to the caller.
3. Returning None:
If a function doesn't have a `return` statement or has a `return` statement without any value,
it implicitly returns `None`.
28
The `return` statement is a powerful tool that enables functions to produce results
and pass data back to the calling code. Understanding how to use it correctly will
help you design and implement effective functions in Python.
Scope of a variable:
In Python, the scope of a variable refers to the region of the program where the variable is
accessible. The scope determines where a variable is created, modified, and used.
Global Scope:
● They are accessible from anywhere in the code, including inside functions.
Local Scope:
● They are accessible only within the function where they are defined.
● Local variables are created when the function is called and destroyed when the function returns.
Points to be noted:
29
● When the local variable and global variable have different names: the global variable can be
accessed inside the function
● When local and global variables have the same name: priority is given to the local copy of the
variable
global keyword
In Python, the global keyword is used to indicate that a variable declared inside a function
should be treated as a global variable, rather than a local variable. When you assign a value to
a variable inside a function, Python, by default, creates a local variable within that function's
scope. However, if you need to modify a global variable within a function, you must use the
global keyword to specify that you want to work with the global variable instead.
For example:
30
Example 1:
Example 2:
Example 3:
Example 4:
31
Passing list as an argument to the function:
Please note that when a list is passed as an argument, the original copy of the list is passed to
the function i.e. if any change is made at any index in the list inside the function, it is reflected
in the original list. That is because a list is a mutable datatype and in Python, when you pass a
list as an argument to a function, you are actually passing a reference to the list rather than a
copy of the list. This means that the function parameter will point to the same memory
location as the original list. As a result, any changes made to the list within the function will be
reflected in the original list outside the function.
However, if you assign a different list to a variable inside a function in Python, it will create a
new local variable that is separate from any variables outside the function. This local variable
will only exist within the scope of the function, and changes made to it won't affect the
original list outside the function.
Output:
32
Types of arguments passed to a function:
Positional Arguments:
● These are the most common types of arguments and are matched to the function
parameters based on their positions. The first argument corresponds to the first parameter,
the second argument corresponds to the second parameter, and so on.
● The number and order of positional arguments must match the function's parameter list.
Default Arguments:
● Default arguments are used when a function is called with fewer arguments than there are
parameters.
● The default values are specified in the function definition.
● If a value is not provided for a parameter during the function call, the default value is used.
Keyword Arguments:
● In this type, each argument is preceded by a keyword (parameter name) followed by an
equal sign.
● The order of keyword arguments does not matter, as they are matched to the function
parameters based on their names.
● These arguments provide flexibility to call a function with arguments passed in any order.
33
Python modules:
● In Python, a module is a file containing Python code that defines variables, functions, and
classes.
● Modules allow you to organize and reuse code by breaking it into separate files, making it
easier to maintain and understand complex programs.
● Python's standard library comes with a vast collection of built-in modules that cover various
functionalities
● If needed, you can also create your own custom modules.
● To use a module in your Python code, you need to import it using the import statement.
math module:
● The math module in Python is a built-in module that provides various mathematical
functions and constants.
● It is part of the Python Standard Library i.e. it does not require any additional installation to
use.
● To use the math module, you need to import it at the beginning of your Python script.
● Once you've imported the module, you can access its functions and constants using the math
prefix.
Here are some commonly used functions and constants provided by the math module:
Mathematical Constants:
● math.pi: Represents the mathematical constant π (pi).
● math.e: Represents the mathematical constant e (Euler's number).
Basic Mathematical functions :
● math.sqrt(x): Returns the square root of x.
● math.pow(x, y): Returns x raised to the power y.
● math.exp(x): Returns the exponential of x (e^x).
● math.log(x, base): Returns the logarithm of x to the specified base (default base is e).
Trigonometric Functions (all angles are in radians):
● math.sin(x), math.cos(x), math.tan(x): Sine, cosine, and tangent of x, respectively.
● math.asin(x), math.acos(x), math.atan(x): Arcsine, arccosine, and arctangent
of x, respectively.
Hyperbolic Functions:
● math.sinh(x), math.cosh(x), math.tanh(x): Hyperbolic sine, cosine, and tangent of x,
respectively. Angular Conversion:
● math.degrees(x): Converts x from radians to degrees.
● math.radians(x): Converts x from degrees to radians. Miscellaneous:
● math.ceil(x): Returns the smallest integer greater than or equal to x.
● math.floor(x): Returns the largest integer less than or equal to x.
● math.factorial(x): Returns the factorial of x.
34
Example 1:
Example 2:
Example 3:
Statistics module:
● The statistics module in Python is another built-in module that provides functions for
working with statistical data.
● It offers a variety of statistical functions to compute measures like mean, median, standard
deviation, variance, etc.
● The statistics module is part of the Python Standard Library, so there's no need to install any
additional packages to use it.
Here are some commonly used functions provided by the statistics module:
● statistics.mean(data): Calculates the arithmetic mean (average) of the data.
● statistics.median(data): Computes the median value of the data.
● statistics.mode(data): Finds the mode (most common value) in the data.
Example 1:
35
Example 2:
random module
● The random module in Python is another built-in module that provides functions for
generating random numbers, and sequences, and making random choices.
● It is commonly used for tasks such as random number generation, random shuffling, and
random sampling.
Here are some commonly used functions provided by the random module:
Example 1:
Possible options:
a) green c) blue
b) yellow d) orange
36
Solution:
Here, the possible values for the variable random sample are 3, 4 and 5. Hence, the
possible Outputs of the above code are b) Yellow and d) orange.
Example 2:
Code:
Output:
Example 3:
Output Options:
37
i. 29 : 26 : 25 : 28 : ii. 24 : 28 : 25 : 26 :
iii. 29 : 26 : 24 : 28 : iv. 29 : 26 : 25 : 26 :
Solution:
Option iv
Example 4:
Output Options:
Solution:
Option i and option iv
Assignment
1. What will be the output of the following code?
a) 10 b) 30 c) error d) 20
2. What is the scope of a variable defined inside a function?
a) Global scope b) Local scope c)Universal scope d)Function scope
3. In Python, can a function return multiple values simultaneously?
a) Yes b) No
38
7. The values being passed through a function call statement are called
a) Actual parameter d) None of these
b) Formal parameter
c) default parameter
8. Which of the following components are part of a function header in Python?
a) Function Name
b) Return Statement
c) Parameter List
d) Both a and c
9. Which of the following function header is correct?
a) def cal_si(p=100, r, t=2)
b) def cal_si(p=100, r=8, t)
c) def cal_si(p, r=8, t)
d) def cal_si(p, r=8, t=2)
a) global a
b) global b=100
c) global b
d) global a=100
a) 5 c) 4
b) 6 d) This code will raise an error.
39
13. A function is defined as below, the function call parameters can be:
16. 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 Lower and Upper.
c) 33 b) -33 c) 3 d)-3
a) 15 18 b) 46 56 c) 25 35 d) 13 12
40
a) 100#52 b) 85#52 c) 85#33 d) 52#52
20. Find the impossible option from the following
21. Look at the function definition and the function call and determine the correct output
a) 21 c) 61
b) 72 d) 71
a) [1, 2, 3, 4, 5, 6] c) [100, 2, 3, 4, 5]
b) [100, 2, 3, 4, 5, 6] d) [1, 2, 3, 4, 5]
a) [1, 2, 3, 4]
b) [5, 6, 7]
c) [1, 2, 3, 4, 5, 6, 7]
d) This code will raise an error.
41
24. Which of the following outputs is not possible:
Options:
a) 34:24:30:33:
b) 29:33:36:31:
c) 24:31:30:31:
d) 34:31:29:30:
25. What possible outputs(s) are expected to be displayed on screen at the time of execution
of the program from the following code? Also, specify the maximum values that can be
assigned to each of the variables FROM and TO.
a) 10#40#70# c) 50#60#70#
b) 30#40#50# d) 40#50#70#
26. What will be the possible outcomes:
a) Delhi#Mumbai#Chennai#Kolkata#
b) Mumbai#Chennai#Kolkata#Mumbai#
c) Mumbai# Mumbai #Mumbai # Delhi#
d) Mumbai# Mumbai #Delhi#Mumbai
27. What is/are the possible outcome/(s) for the following code?
28. What possible outputs(s) are expected to be displayed on screen at the time of execution
of the program from the following code?
42
a) 40#35#
b) 60#35#70#50#
c) 35#70#50#
d) 40#55#60#
29. What possible outputs(s) are expected to be displayed on screen at the time of execution
of the program from the following code?
a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
Output Options :
a) 25
b) 34
c) 20
d) None of the above
ii.
Output Options :
a) 99
b) 94
c) 93
d) None of the above
43
iii.
Output Options:
a) 1
b) 1 2
c) 1 2 3 4
d) 1 2 3
31. Assertion and Reason type questions
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
i. Assertion (A): To use a function from a particular module, we need to import the module.
Reason(R): import statement can be written anywhere in the program, before using a
function from that module.
ii. Assertion (A): In Python, functions can be defined inside other functions.
Reason (R): Python supports nested functions which allow functions to be defined within
other functions.
iii. Assertion (A): In Python, a function must always return a value.
Reason (R): If a return statement is not used in a function, it will return `None` by default.
iv. Assertion (A): In Python, the `def` keyword is used to create a new function. Reason(R): The
`def` keyword allows for the definition of both named and anonymous functions in Python.
v. Assertion (A): In Python, function parameters can have default values.
Reason(R): Default values for parameters are specified by assigning values in the
function definition.
44
33. Find and write the output of the following Python code:
36. Rewrite the following code after removing the syntactical errors (if any).
45
39. What will be the output of the following code?
46
code:
43. Find and write the output of the following Python code:
I ii
47
i. ii.
iii. iv.
v vi
48
i. ii.
iii. iv.
i. ii.
49
iii. iv.
Lab Exercise
1. Write a Python function named `calculate_gross_salary` that takes the basic salary (an
integer) as an argument and returns the gross salary. The gross salary is calculated as
follows:
- If the basic salary is less than or equal to 10000, the gross salary is the basic
salary plus 20% of the basic salary.
- If the basic salary is more than 10000, the gross salary is the basic salary
plus 25% of the basic salary.
Write the function definition for `calculate_gross_salary` and use it to calculate
the gross salary for a basic salary of 12000.
2. Write a Python function called calculate_average that takes a list of numbers as input and
returns the average of those numbers.
3. Write a function update_list(L) that receives a list as arguments and increases the value of
even elements by 2.
For example: if the list is [2,4,6,7,9] after the execution of the
function, the list should be: [4,6,8,7,9]
4. Difference between the Actual Parameter and the Formal Parameter?
5. Name the Python Library modules which need to be imported to invoke the
following functions:
a. sin()
b. randint()
7. Explain the concept of the ‘global’ keyword in Python. When would you use it?
50
Topics to be covered
• Introduction
• Types of errors
• Handling Exceptions Using Try–Except–Finally Blocks
51
52
EXCEPTION HANDLING
While executing a Python program, it may happen that the program does not execute at all or it can
generate unexpected output. This happens when there are syntax errors, run time errors, logical
errors or any semantic errors in the code.
It occurs when we put some It may occur when there may be some It occurs at the time of program
incorrect punctuation, improper sequence of statements or execution. Such errors produce
incorrect word sequence or incorrect use of operators. It will not incorrect output for specific
there are some undefined stop a program from executing but will values of input. These errors are
terms or missing parenthesis. produce incorrect output. It will also called Exceptions, which
Syntax errors are also known generate incorrect output for every occur when something
as Parsing errors. value of input. unexpected happens leading to
For example: For example: stopping the program
>>> p=2(num1+num2) If we want to find the sum of two execution.
numbers, write the following code: For example:
This statement is A, B = 10, 15 1. Division by zero.
mathematically correct but C=A*B 2. Finding the square root of a
the Python interpreter will print (“Sum is: “, C) negative number.
raise a SYNTAX error as there Here, the code will generate A * B but 3. Insufficient memory is
is no sign present between 2 we wanted to find Sum. Hence it is a available on the computer.
and parenthesis. The correct logical error. 4. Trying to open a file that does
statement will be: not exist.
>>> p=2*(num1+num2)
EXCEPTIONS:
● Run time errors are known as Exceptions.
● When an Exception is generated, the program execution is stopped.
● Removing errors from a code is referred to as EXCEPTION HANDLING.
● Commonly occurring exceptions are usually defined in the Interpreter. These are known as Built-in
Exceptions.
53
Some Built-in Exceptions are listed below:
EXCEPTION DESCRIPTION
ZeroDivisionError It is raised when an expression or a value is getting divided by zero (0).
For example: If c = 0, then p = b/c will result in ‘ZeroDivisionError’.
NameError It is raised when an identifier is not assigned any value earlier and is
being used in some expression. For example: if p = a*b/c then it will
result in ‘NameError’ when one or more variables are not assigned
values.
Value Error It is raised when the given value of a variable is of the right data type
but not appropriate according to the expression.
EXCEPTION HANDLING:
Every exception has to be handled by the programmer for the successful execution of the program.
To ensure this we write some additional code to give some proper message to the user if such a
condition occurs. This process is known as EXCEPTION HANDLING.
Exception handlers separate the main logic of the program from the error detection and correction
code. The segment of code where there is any possibility of error or exception is placed inside one
block. The code to be executed in case the exception has occurred is placed inside another block.
These statements for detection and reporting the execution do not affect the main logic of the
program.
54
An exception is said to be caught when a code designed for handling that particular exception is
executed. In Python, exceptions, if any, are handled by using the try-except-finally block. While
writing code, a programmer might doubt a particular part of code to raise an exception. Such
suspicious lines of code are written inside a try block which will be followed by an except block. The
code to handle every possible exception, that may arise in the try block, will be written inside the
except block.
If no exception occurs during the execution of the program, the program produces the desired
output successfully. But if an exception is encountered, further execution of the code inside the try
block will be stopped and the control flow will be transferred to the except block.
Example 1:
55
Example 2:
In the above example, the user entered a wrong value that raised ValueError. We can handle this
exception by using the ValueError exception.
Result:
Sometimes, a single piece of code in a program may have more than one type of error. If such an
event happens, we can use multiple except blocks for a single try block.
Example 1:
Example 2:
56
We can also handle exceptions without naming them.
Default exception messages can also be displayed when we are not handling exceptions by name.
try…except…else Clause: Just like Conditional and Iterative statements we can use an optional
else clause along with the try…except clause. An except block will be executed only when some
57
exceptions are raised in the try block. But if there is no error then except blocks will not be executed.
In this case, the else clause will be executed.
finally CLAUSE:
The try…except…else block in Python has an optional finally clause. The statements inside the finally
block are always executed whether an exception has occurred in the try block or not. If we want to
use the finally block, it should always be placed at the end of the clause i.e. after all except blocks
and the else block.
58
Assignment
2
When might you use the 'finally' block in exception handling?
a) To handle exceptions that are expected to occur frequently.
b) To provide a resolution for every possible error.
c) To close resources that were opened in the 'try' block, regardless of whether an
exception occurred or not.
d) To avoid having to use 'except' blocks.
a) Division by zero!
b) An arithmetic error occurred!
c) No error!
d) This code will raise a syntax error.
4 Which of the following is NOT a standard built-in exception in Python? a)
ValueError
b) IndexError
c) ExceptionError
d) KeyError
5
What is an exception in programming?
a) An error that occurs during runtime
b) A warning message from the compiler
c) A comment in the code
d) A statement that terminates the program
59
6 What is the purpose of the "try" block in a try-except construct?
a) To handle the exception by executing specific code
b) To specify the type of exception to be thrown
c) To define a custom exception class
d) To ensure a specific block of code always executes
8 Assertion (A): The "finally" block is mandatory after the try block.
Reasoning (R): The "finally" block contains code that is guaranteed to execute,
whether an exception occurs within the "try" block or not.
A. Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False
9 Assertion (A): Python allows multiple "except" blocks to be used within a single
"try" block to handle different exceptions.
Reasoning (R): By using multiple "except" blocks with different exception types,
Python provides the flexibility to handle various types of exceptions separately.
A. Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False
60
10
Code snippet:
12
What will be the output of the following code if the input is 2.2:
61
14 Consider the code given below:
Which of the following errors will be raised by the given Python code?
a) NameError
b) ValueError
c) TypeError
d) IOError
15 Code snippet:
17
Identify the statement(s) from the following options which will raise TypeError
exception(s):
a) print('5') b) print( 5 * 3) c) print('5' +3) d) print('5' + '3')
62
LAB EXERCISE:
1 Create a simple calculator program that takes two numbers and an operator (+, -, *, /) as
input. Implement exception handling to handle cases like division by zero and invalid
operators.
2
Create a program that asks the user for an integer input. Use exception handling to
ensure that the input is a valid integer. If the user provides invalid input, prompt them to
retry until a valid integer is entered.
3
Create a program that connects to a database and performs database operations (e.g.,
insert, update, delete). Use exception handling to deal with database-related exceptions,
such as connection errors or SQL syntax errors.
4 Create a program that reads data from a file specified by the user. Implement exception
handling to catch and handle the "FileNotFoundError" exception if the file does not
exist.
5 Define a dictionary with some key-value pairs. Ask the user for a key and attempt to
access the corresponding value from the dictionary. Handle the "KeyError" exception
and display a message if the key is not found.
63
Topic to be covered:
Introduction
Types of files
Access Specifiers in the file
seek ( ) and tell( )
Text files and its methods
Binary files and its methods
CSV files and its methods
Absolute and Relative Paths
64
1. Text Files
2. Binary Files
1. seek( ) 3. CSV Files
2. tell()
1. open() 1. r
2. write() 2. r+
3. read( ) 3. rb
4. close( ) 4. rb+
5. w
6. w+
File 7. wb
65
1. reader( ) Handling 8. wb+
2. writer( ) 9. a
2.1. writerow( ) 10. a+
2.2. writerows( ) 11. ab
12. ab+
1. read( )
2. readline( ) 1. tell( )
1. load ( ) 3. readlines( ) 2. seek( )
2. dump( )
FILE HANDLING
Files are used to store data permanently and can be
retrieved later.
Type of Files
1. Text Files
2. Binary Files
3. CSV Files
Steps for File handling:
1. Open File
2. Processing file i.e Read or Write from/to file
3. Close File
1. Opening Files:
I. file_object: This is a variable that will hold the file object returned by the `open()`
function. You'll use this variable to perform operations like reading from or writing
to the file.
II. open(): This is the built-in function used to open files in Python.
III. access_mode: This specifies the mode in which you want to open the file. Here are
some common access modes
a. open()
b. Open using ‘with’ statement.
● It's like turning the key to open a door. ● It's like having a helper who opens and
● You use it to open a file and get access closes the door or you automatically.
to its contents. ● You tell the helper what you want to
do with the door (read, write,
66
etc.), and they handle everything for
● After you're done reading or writing, you
you.
have to remember to close the file yourself,
● They make sure the door is properly
just like locking the door when you're done.
closed even if something unexpected
happens, like a sudden gust of wind.
Best Choice:
● Using `with` is usually better because it's safer and saves you from having to
remember to close the file.
● It's like having a reliable assistant who ensures everything is handled smoothly.
2. Closing Files:
● It's important to close files after you're done working with them to release system
resources.
● Not closing files can lead to resource leaks and other issues.
67
Access Specifiers in Files:
Access Mode Access Mode Access Mode Description File Pointer
for Text Files for Binary for CSV Files Position
Files
68
Default mode for file opening is “r” read mode. If we didn’t specify mode during the opening
of the file then it will automatically open the file in read mode.
Example:
Python Code:
69
Content of abc.txt file:
Text Files:
● It stores information in the form of ASCII or Unicode characters
● Each line of text is terminated with a special character called EOL (End of Line), which is
the new line character (‘\n’) in python by default.
● File extension will be .txt
Syntax: file_object.read( )
file_pointer.read(n): It will read the maximum n bytes/characters from the file.
f.read(7) # it will read 7 bytes/characters from the position of file pointer.
file_pointer.read( ): It will read the entire content of the file.
f.read( ) # it will read all the data of the file from the position of file pointer.
70
readline( ): It will read one complete line in one go from the file. It returns the data in the form
of a string.
Syntax: file_object.readline( )
file_pointer.readline( ): It will read the entire line.
file_pointer.readline(n): It will read the first ‘n’ bytes from the file.
f.readline(5) #it will read the first 5 characters/bytes from the file.
readlines( ): It will return all the lines of the file as the elements of the list. I.e. the 1st line of
the file will be the first element of the list and so on.
Syntax: file_object.readlines( )
file_pointer.readlines( ): It will read all the lines of the file as the elements of the list.
f.readlines( ) #it will read all the lines of the file as the elements of the list.
71
72
Tips on writing text file code in exam:
73
Example 1:
Write a function count_char() that reads a file named “char.txt” counts the number of times
character “a” or “A” appears in it.
Example 2:
Write a function count_word() that reads a text file named “char.txt” and returns the number
of times word “ the” exists.
Example 3:
Write a function count_line() that reads a text file named “char.txt” and returns the number
of lines that start with a vowel.
74
Writing data into Files
1. write( ): It takes string as an input and writes it into the file.
a. Syntax: file_object.write(string)
b. i.e. f.write(“Hello World”)
2. writelines( ): It is used to write multiple lines as a list of strings into the file. In this each
element of c the list will be treated as a separate line in the file.
a. Syntax: file_object.writelines(list of strings)
b. i.e. data=[“I am a student of DOE”, “I studies in class 12th”]
>>>f.writelines(data)
Code Output
75
Code:
Output:
Question: Write a program in python with reference to above program, the content of the text
files should be in different lines.
I.e.
Priya
Disha
Tanisha
Krishna
Aman
Code
Output
76
Content of “Toppers.txt” file:
Write a program in python to count vowels, consonants, digits, spaces, special characters,
spaces, words and lines from a text file named “student.txt”.
Content of File:
Code
77
Output:
Lab Exercise:
1. Define a function SGcounter() that counts and display number of S and G present in
a text file ‘A.txt”
e.g., SAGAR JOON IS GOING TO MARKET.
It will display S:2 G:2
2. Write a function in Python that counts the number of “is”, “am” or “are” words present
in a text file “HELLO.TXT”. If the “HELLO.TXT” contents are as follows: Here are two
sentences that contain "is," "am," or "are":
“She is studying for her final exams.
We are planning a trip to the mountains next weekend.”
The output of the function should be: Count of is/am/are in file: 2
3. Write a method in python to read lines from a text file HELLO.TXT to find and display
the occurrence of the word “hello”.
4. Write a user-defined function named Count() that will read the contents of a text file named
“India.txt” and count the number of lines which start with either “I” or “T”. E.g. In the
following paragraph, there are 2 lines starting with “I” or “T”:
“The Indian economy is one of the largest and fastest-growing in the world,
characterized by a diverse range of industries including agriculture, manufacturing,
services, and information technology. It boasts a sizable consumer base and a dynamic
entrepreneurial spirit. However, it also faces challenges such as income inequality,
poverty, and infrastructure gaps, which the government continually addresses
through policy reforms and initiatives to foster sustainable growth .”
5. Write a method in python to read lines from a text file AZAD.TXT and display those lines,
which are starting with an alphabet ‘T’.
78
Binary Files:
1. Binary files are made up of non-human readable characters and symbols, which require
specific programs to access its contents.
2. In this translation is not required because data is stored in bytes form.
3. Faster than text files.
4. pickle module is used for working with binary files import pickle
5. File extension will be .dat
6. There is no delimiter to end the file.
Pickling: It is the process of converting python object into byte stream. Pickling is done at the
time of writing into a binary file.
Unpickling: It is the process of converting a byte stream into python object. Unpickling is done
at the time reading from a binary file.
Program
Input
79
File Content
Example: data = pickle.load(f) #Here ‘data’ is an identifier and ‘f’ is a file pointer.
80
Question: Write a menu based program in python which contain student details in binary file and
should have following facilities:
81
82
Comma Separated Value (CSV) Files:
1. It is a plain text file which stores data in a tabular format, where each row represents
a record and each column represents a field and fields are separated by comma in csv
files.
2. csv module is used for working with csv files:
83
b. writerows(): This method is used to write multiple rows to the CSV file.
7. We can read csv file data in excel file also.
i. Reader Function: For reading data from csv file we require csv. reader( ) function.
ii. Writer Function:For writing data to the csv file we take a file object as input and write
the data into the file.
a. writerow( ): It writes a single row of data to the CSV file.
b. writerows( ): It writes a list of rows of data to the CSV file.
Code:
Output in IDLE:
84
Result in Notepad: Result in Excel:
Code:
Output in IDLE:
85
READING FROM CSV FILES
File Content:
86
87
Assignment
1. What is the purpose of file handling in Python?
a. To store data permanently
b. To perform mathematical operations on files
c. To create graphical user interfaces
d. To handle network connections
3. Which of the following mode in file opening statement results or generates an error
if the file does not exist?
a. a+ b. r+ c. w+ d. None of the above
5. What are the three modes in which a file can be opened in Python?
a. r, w, and a b. r+, w+, and a+ c. rb, wb, and ab d. All of the above
7. Which of the following commands is used to open the file “STUDENT.DAT” for only
writing in binary format?
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
88
10. A text file readme.txt is opened in Python. What type of data is stored in f?
>>> file=open('readme.txt')
>>> f=file.readlines()
11. Find P and Q from the options while performing object serialization
>>> import pickle
>>> spc=open("yoyo.dat","wb")
>>> x=500
>>> pickle.dump(P,Q)
a. x,spc b. spc, x c. 'yoyo.dat',500 d. 'yoyo.dat','500'
12. What is NOT a valid difference between the write() and writelines() methods in
Python?
a. The write() method writes a single string to a file, while the writelines() method
writes a list of strings to a file.
b. The write() method does not append a newline character to the end of the string,
while the writelines() method does.
c. The write() method moves the file pointer to the next position, while the
writelines() method does not.
d. All of the above are valid.
13. What happens if you try to open a non-existent file in Python using 'r' mode?
a. It raises a FileNotFoundError
b. It creates an empty file
c. It raises an IOError
d. It opens a file in read mode
14. Which of the following options can be used to read the first line of a text file
Myfile.txt?
a. myfile = open('Myfile.txt'); myfile.read()
b. myfile = open('Myfile.txt','r'); myfile.read(n)
c. myfile = open('Myfile.txt'); myfile.readline()
d. myfile = open('Myfile.txt'); myfile.readlines()
15. Assume that the position of the file pointer is at the beginning of 3rd line in a text file.
Which of the following option can be used to read all the remaining lines?
a. myfile.read() b. myfile.read(n) c. myfile.readline() d. myfile.readlines()
16. A 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.
89
i. myfile = open('student.txt','rb')
ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r')
iv. myfile = open('student.txt')
17. Which of the following statements is incorrect in the context of binary files?
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
18. Which of the following commands is used to write the list L into the binary file,
STUDENT.DAT,where f is the file handler ?
19. Which of the following commands is used to read each record from the binary file
STUDENT.DAT,where f is the file handler.
a. r = pickle.load(f)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
20. Which of the following statement is true?
a. pickling creates an object from a sequence of bytes
b. pickling is used for object serialization
c. pickling is used for object deserialization
d. pickling is used to manage all types of files in Python
90
24. What is the correct expansion of CSV files?
a. Comma Separable Values
b. Comma Separated Values
c. Comma Split Values
d. Comma Separation Values
25. Which of the following is not a function / method of csv module in Python?
a. read() b) reader() c) writer() d) writerow()
26. Which of the following statements opens a binary file record.bin in write mode and
writes data from a list lst1 = [1,2,3,4] on the binary file?
a. with open('record.bin','wb') as myfile: pickle.dump(lst1,myfile)
b)with open('record.bin','wb') as myfile:
pickle.dump(myfile,lst1)
c) with open('record.bin','wb+') as myfile:
pickle.dump(myfile,lst1)
d) with open('record.bin','ab') as myfile:
pickle.dump(myfile,lst1)
27. Which of the following functions changes the position of file pointer?
a. flush() b) tell() c) seek() d) offset()
a. 3 b) 4 c) 5 d) 6
29. 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.
91
30. What is the significance of the tell() method?
a. tells the path of file
b. tells the current position of the file pointer within the file
c. tells the end position within the file
d. checks the existence of a file at the desired location
34 What is the difference between the read() and readline() methods in Python?
a. The read() method reads all of the data from a file, while the readline() method
reads only one line of data at a time.
b. The read() method returns a string, while the readline() method returns a list of
strings.
c. The read() method does not move the file pointer, while the readline() method
moves the file pointer to the next line.
d. All of the above
92
37 If the file pointer is at the beginning of the file and you use seek(5, 0), where will the
file pointer be?
38 Identify the missing part in the code to write the list object in the file
>>> import pickle
>>> x=[1,3,5,7]
>>> f=open('w.dat','wb')
>>> pickle. (x,f)
>>> f.close()
a. write() b. writeline() c. load() d. dump()
39 A text file myfile0.txt has two lines of text, what will be stored in the variable ‘ctr’
when the following code is executed?
>>> ctr=0
>>> spc=open("myfile0.txt")
>>> while(spc.readline()):
ctr += 1
a. 0 b. 1 c. 2 d. 3
40 Write a statement to send the file pointer position 10 bytes forward from current
location of file ,consider fp as file object.
a. fp.seek(10) b.fp.seek(10,1) c. fp.tell(10) d. fp.seek(1,10)
42 How many lines does the file myfile00.txt has after the code is executed?
>>> mylist=['India', '\nis', '\nmy', '\ncountry', '\nand', '\nI', '\nam', '\na', '\nproud',
'\ncitizen']
>>> spc=open("myfile00.txt","w")
>>> spc.writelines(mylist)
a). 2 b). 10 c). 9 d). 1
44 What is the difference between 'rb' and 'r' when opening a file in Python?
a. 'rb' opens the file in binary mode, 'r' in text mode
b. 'rb' reads the file backward, 'r' reads it forward
93
c. 'rb' is for reading, 'r' is for writing
d. 'rb' and 'r' are the same
Suppose the root directory (School) and present working directory are the same.
What will be the absolute path of the file Syllabus.jpg?
a) School/syllabus.jpg
b) School/Academics/syllabus.jpg
c) School/Academics/../syllabus.jpg
d) School/Examination/syllabus.jpg
94
3 Suppose content of 'Myfile.txt' is : Humpty Dumpty sat on a wall
Humpty Dumpty had a great fall
5
Suppose the content of 'data.txt' is:
Python is a powerful programming language. It
is used widely for various applications.
10
20
30
40
95
●
7. Consider a file named 'text.txt' with the following content:
9. Raghav is trying to write a tuple tup1 = (1,2,3,4,5) on a binary file test.bin. Consider
the following code written by him.
96
10. Given the following code to write a list to a binary file:
11. Observe the following code and answer the questions that follow:
12. Observe the following code and answer the questions that follow:
1. Assertion (A): CSV (Comma Separated Values) is a file format for data storage
which looks like a text file.
Reason (R): The information is organized with one record on each line and each
field is separated by comma.
2 Assertion (A): A binary file is a computer-readable file that contains binary data.
Reason (R): Binary files can store data in formats such as images, audio, and
executables.
97
3. Assertion (A): Text files are easier to read and edit using simple text editors.
Reason (R): Text files store data in a human-readable format with plain text.
4. Assertion (A): Binary files are more prone to corruption than text files.
Reason (R): Binary files are usually larger in size and contain more complex data.
5. Assertion (A): Opening a file in read mode ('r') will create a new file if it does not
exist.
Reason (R): The read mode is used for reading the content of an existing file.
6. Assertion (A): Opening a file in append mode ('a') will allow adding new data
without modifying the existing content.
Reason (R): The append mode places the file cursor at the beginning of the file.
1. Mr. Manish Kumar is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written the following
code. As a programmer, help him to successfully execute the given task.
2. Vaishali of class 12 is writing a program in Python for her project work to create a
CSV file “Teachers.csv” which will contain information for every teacher’s
identification Number , Name for some entries. She has written the following code.
However, she is unable to figure out the correct statements in few lines of code,
hence she has left them blank. Help her write the statements correctly for the
missing parts in the code.
98
3. Sachin of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written the following
code. As a programmer, help him to successfully execute the given task.
99
4 Shanvika is a programmer, who has recently been given a task to write a user
defined function named write_bin() to create a binary file called Cust_file.dat
containing customer information customer number (c_no), name (c_name),
quantity (qty), price (price) and amount (amt) of each customer.
The function accepts customer number, name, quantity and price. Thereafter, it
displays the message Quantity less than 10 Cannot SAVE', if quantity entered
is less than 10. Otherwise the function calculates amount as price quantity and
then writes the record in the form of a list into the binary file.
(i) Write the correct statement to open a file 'Cust_file.dat' for writing the data
of the customer.
(ii) Which statement should Shanvika fill in Statement 2 to check whether quantity
is less than 10.
(iii) Which statement should Shanvika fill in Statement 3 to write data to the binary
file and in Statement 4 to stop further processing if the user does not wish to enter
more records.
(iv) What should Shanvika fill in Statement 5 to close the binary file named
Cust_file.dat and in Statement 6 to call a function to write data in binary file?
100
5. Divisha is a Python programmer. She has written a code and created a binary file
record.dat with employe eid, ename and salary. The file contains 10 records. She
now has to update a record based on the employee id entered by the user and
update the salary. The updated record is then to be written in the file temp.dat.
The records which are not to be updated also have to be written to the file
temp.dat. If the employee id is not found, an appropriate message should to be
displayed. As a Python expert, help her to complete the following code based on
the requirement given above:
101
Lab exercise
1. Write the definition of a function Count_Line() in Python, which should read each
line of a text file "SHIVAJI.TXT" and count total number of lines present in text
file. For example, if the content of the file "SHIVAJI.TXT" is as follows:
Shivaji was born in the family of Bhonsle.
He was devoted to his mother Jijabai.
India at that time was under Muslim rule.
The function should read the file content and display the output as follows:
2 Write a function in Python that counts the number of “Me” or “My” words present
in a text file “STORY.TXT”. If the “STORY.TXT” contents are as follows: My first
book was Me and My Family. It gave me chance to be Known to the world.
Output :
Number of words ending with a digit are 4
3 Write a function AMCount() in Python, which should read each character of a text
file STORY.TXT, should count and display the occurrence of alphabets A and M
(including small cases a and m too).
Example: If the file content is as follows:
4 Write the definition of a Python function named LongLines ( ) which reads the
contents of a text file named 'LINES.TXT' and displays those lines from the file which
have at least 10 words in it. For example, if the content of 'LINES.TXT' is as follows:
102
5 Write a function count Words (in Python to count the words ending with a digit in
a text file "Details.txt".
Example:
If the file content is as follows:
On seat2 VIP1 will sit and
On seat1 VVIP2 will be sitting
Output will be: 4
6. Write a method/function DISPLAYWORDS() in python to read lines from a text
file STORY.TXT, and display those words, which are less than 4 characters.
103
Topic to be covered:
Stack
Operation On Stack(Push, Pop, Peek, Display)
Implementation Of Stack Using List
Applications Of Stack
104
105
DATA STRUCTURE
Data structure can be defined as a set of rules and operations to organize and store data
efficiently. We can also say that it is a way to store data in a structured way. We can apply
different operations like reversal, slicing, counting etc. of different data structures. Hence,
Data Structure is a way to organize multiple elements so that certain operations can be
performed easily on whole data as a single unit as well as individually on each element.
In Python, Users are allowed to create their own Data Structures which enable them to define
the functionality of created data structures. Examples of User-defined data structures in
Python are Stack, Queue, Tree, Linked List etc. There are some built-in data structures also
available in Python like List, Tuple, Dictionary and Set.
Linear data structures are single-level data structures having their elements in a sequence like
a stack, queue and linked list.
Non-linear data structures are multilevel data structures like tree and graph.
STACK:
A Stack is a Linear data structure which works in a LIFO (Last In First Out) manner (or we can
say FILO i.e. First In Last Out manner). It means that Insertion and Deletion of elements will
be done only from one end generally known as TOP only. In Python, we can use a List data
structure to implement Stack.
106
Application of Stack:
1. Expression Evaluation
2. String Reversal
3. Function Call
4. Browser History
5. Undo/Redo Operations
Operations of Stack:
The Stack supports following operations:
107
Implementation of Stack:
In Python, the List data structure is used to implement Stack. For the PUSH operation, we use the
append() method of List while for the POP operation, we use the pop() method of List.
108
2. A list contains the following record of customers: [CBSE EXAM 2022-23]
[Customer_name, Room_type]
Write the following user-defined functions to perform given operations on the stack
named “Hotel”:
i. Push_Cust() - Push customer’s names of those customers who are staying in the ‘Delux’ Room Type.
ii. Pop_Cust() - To Pop the names of Customers from the stack and display them. Also, display
“Underflow” when there are no customers in the stack.
For example: If the list with customer details is as follows:
[“Siddarth”, “Delux”]
[“Rahul”, ”Standard”]
[“Jerry”, “Delux”]
The stack should contain:
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow
109
Assignment
PART A
1
Sanya wants to remove an element from the empty stack. Which of the following terms is
related to this?
(a) Empty Stack (b) Overflow (c) Underflow (d) Clear Stack
3 Insertion and Deletion operations of the Stack are known as ___________ respectively.
a. Insertion and Deletion
b. Push and Pop
c. Pop and Push
d. Enqueue and Dequeue
110
5 Which of the following is not an inherent application of Stack?
a. Reversing a String.
b. Evaluation of postfix expression.
c. Implementation of recursion.
d. Job Scheduling.
PART B
3. ASSERTION (A): LIFO is a technique to access data from queues. REASON(R): LIFO
stands for Last In First Out.
4. ASSERTION (A): A Stack is a Linear Data Structure that stores the elements in LIFO order.
REASON(R): A new element is added at one end and the element is removed from that
end only.
5. ASSERTION (A): A situation occurs when one tries to delete an element from an empty
stack.
REASON(R): This situation is called an Overflow.
6. ASSERTION (A): A stack is a LIFO structure.
REASON (R): Any new element pushed into the stack always gets positioned at the index
after the last existing element in the stack.
111
PART C
1 Write a function in Python POPSTACK (L) where L is a stack implemented by a list of numbers. The
function returns the value deleted from the stack.
2
A list contains the following record of a customer:
[Customer_name, Phone_number, City]
Write the following user-defined functions to perform given operations on the stack named
‘status’:
(i) Push_element() - Push an object containing the name and Phone number of customers who
live in Goa to the stack
(ii) Pop_element() - Pop the objects from the stack and display them. Also, display
“Stack Empty” when there are no elements in the stack.
For example: If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”] the
stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”] The output
should be:
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”] Stack Empty
3
Write a function in Python, Push(SItem) where SItem is a dictionary containing the details of
stationery items– {Sname:price}.
The function should push the names of those items in the stack that have a price greater than
75. Also, display the count of elements pushed into the stack. For example: If the dictionary
contains the following data:
Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25} The
stack should contain: Notebook
Pen
Output should be: ‘Stack has 2 items’.
4. Write a function, Push (Vehicle) where Vehicle is a dictionary containing details of vehicles –
{Car_Name: Maker}. The function should push the name of a car manufactured by ‘TATA’
(including all the possible cases like Tata, TaTa, etc.) to the stack. For example:
If the dictionary contains the following data:
Vehicle = {‘Santro’: ‘Hyundai’, ‘Nexon’: ‘TATA’, ‘Safari’ : ‘Tata’}
The stack should contain:
Safari
Nexon [CBSE EXAM 2022-23]
112
5. A list, NList, contains the following records as list elements:
Each of these records is nested together to form a nested list. Write the following user-defined
functions in Python to perform the specified operations on the stack named travel.
i. Push_element(NList): It takes the nested list as an argument and pushes a list object containing
the name of the city and country, which are not in India and the distance is less than 3500 km
from Delhi.
ii. Pop_element(): It pops the objects from the stack and displays them. Also, the function
should display “Stack Empty” when there are no elements in the stack.
For example: If the nested list contains the following data:
NList=[[“Newyork”,”USA”,11734], [“Naypyidaw”, “Myanmar”,3219],
[“Dubai”,”UAE”,2194], [“London”,”England”,6693], [“Gangtok”, “India”,1580],
[“Columbo”, ”Sri Lanka”, 3405]] The stack should contain:
[“Naypyidaw”, “Myanmar”,3219], [“Dubai”,”UAE”,2194], [“Columbo”, ”Sri Lanka”,
3405]
The output should be:
[“Columbo”, ”Sri Lanka”, 3405]
[“Dubai”,”UAE”,2194]
[“Naypyidaw”, “Myanmar”,3219]
Stack Empty [CBSE SQP 2023]
6. Write a function in Python, Push(SItem) where, SItem is a dictionary containing the details of
stationary items—{Sname:price}. The function should Push the names of those items in the
stack that have a price greater than 75. Also, display the count of elements pushed into the
stack.
For example:
If the dictionary contains the following data:
SItem: {‘Pen’: 106, ‘Pencil’: 59, ‘Notebook’: 80, ‘Eraser’:25} The stack
should contain:
Notebook
Pen
The output should be: The count of elements in the stack is 2. [CBSE SQP 2022]
113
LAB EXERCISE
1 Create a stack that stores dictionaries as elements. Each dictionary represents a person's
information ( name, age, city).
● Implement a `push_dict` method to push a dictionary onto the stack of persons above age
20.
● Implement a `pop_dict` method to pop the top dictionary from the stack.
2 Create a stack to manage student records. Each student record is represented as a dictionary
containing attributes like student ID, name, and GPA.
● Implement a `push_student` method to push student records onto the stack with GPA above
60.
● Implement a `pop_student` method to pop the top student record from the stack.
3 Assume a nested dictionary. Each dictionary can contain other dictionaries as values.the
format of the dictionary is as follows:
{1:{‘a’:’one,’b’:’two},2:{‘x’:10},3:{‘y’:100,’z’:200}....} Create a stack that
stores dictionaries as elements.
{‘x’:10}
{‘a’:’one,’b’:’two}
4
Write the definition of a function POP_PUSH (LPop, LPush, N) in Python. The function should
Pop out the last N elements of the list LPop and Push them into the list LPush. For example:
If the contents of the list LPop are [10, 15, 20, 30] and the value of N is 2, then the function
should create the list LPush as [30, 20] And the list LPop should now contain [10, 15]
NOTE: If the value of N is more than the number of elements present in LPop, then display the
message "Pop not possible".
114
named 'Hotel':
● PushCust() - To Push customers' names of those customers who are staying in the 'Delux'
Room Type.
● PopCust() - To Pop the names of customers from the stack and display them. Also, display
"Underflow" when there are no customers in the stack.
For example:
If the lists with customer details are as follows:
[["Siddarth", "Delux"] , ["Rahul", "Standard"], ["Jerry", "Delux"]] The stack
should contain:
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow
Write a function in Python, Push (Vehicle) where Vehicle is a dictionary containing details of
vehicles (Car_Name: Maker). The function should push the name of the car manufactured by
TATA (including all the possible cases like Tata, TaTa, etc.) to the stack. 3
For example:
If the dictionary contains the following data: Vehicle=("Santro": "Hyundai", "Nexon": "TATA",
"Safari": "Tata"} The stack should contain
Safari
Nexon
115
Topics to be covered
1. Evolution of networking
2. Data communications terminologies
3. Transmission Media
4. Network Devices
5. Network Topologies
6. Network Types
7. Network Protocols
116
117
What is a Network?
It is a collection of Inter-connected computers and other devices that can
communicate with each other i.e. it is a collection of hardware and software components
that are connected for effective data and information transfer where one
system/device is the sender and the other is the receiver.
Evolution of Networking
Network Communication started in the earliest times with the evolution of humans. Also, all
living beings communicate with each other in one way or the other. Early man used to
communicate using symbols, then with the development of modern languages and
intelligence, communication media came into the picture. And, with the advent of computer
systems, data communication became important to making necessary decisions and passing
messages quickly.
In the year 1967, the first computer Network started in America and was named ARPANET.
ARPANET
(Advanced Research Project Agency Network) that was designed to protect America from
any nuclear attack form the USSR. It was the first system to use the TCP/IP protocol suite
and was based on Client-Server (sender-receiver) architecture.
NSFNet
National Science Foundation Network, was started in 1980 to help in Academic and
Scientific Research. It connected its server with the ARPANET in the year 1986. In the year
1990, the NSFNet, ARPANET and other smaller networks were joined together to form the
INTERNET (Interconnected Networks).
118
Internet:
It is the global network of interconnected devices that may/may not follow
the same set of rules. They are connected for sharing information and
establishing communication. It is made up of two parts:
a. Intra-Net:
The word Intra means inside or within.
Therefore, an Intranet means the network in
an organization. It is created using the
protocols of LANs and PANs. Example: Wipro
uses its network in the company.
b. Extranet:
It is the network that lies outside the limits of
the Intra-Net. Dell and Intel use networks for
business-related operations.
c. Interspace:
It's a software program that lets many users talk to each other
in real-time using audio, video, and text.
Data Communication
Data:
It is raw facts and figures that may have many meanings. Examples: 11,
A123x@r67Y, etc.
Information:
The data that has a defined meaning is known as the information. Examples:
Roll No. 11, Password: A123x@r67Y, etc.
Data Channel:
It is a medium to carry information or data from one place to another.
Baud:
It is the measurement of the data transfer rate in a communication channel.
119
Bits per Second:
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 Narrowband Channels.
Switching Techniques:
These are used for transmitting data across the networks. The various
switching techniques are:
a. Circuit Switching:
First, a connection is made between the sender and receiver. Then, the
data is sent from the source computer to the destination computer.
Before the data transfer, a call setup is needed to establish the
connection. This method is best for connections that need a steady bit
rate for communication.
b. Message Switching:
With this technique, the message is first sent to a switching office, which
stores the data in a buffer. Then, the switching office looks for an
available link to the receiver and sends the data. There's no limit to the
size of the message block that can be sent over the network.
c. Packet Switching:
It is the most efficient data communication technique used to send and
receive data over the internet. Instead of using a dedicated line for data
communication, the data is sent through the network on its own and put
back together at the destination computer. The data is split into fixed-
size packets before being sent. Each packet includes a piece of the data
and the address information.
120
Transmission Medias
Transmission media refers to the medium by which the data is transferred
from one device to another. A transmission media can be:
a. Wired Transmission Media
b. Wireless Transmission Media
B. Coaxial Cable:
Coaxial cables consist of a copper conductor
surrounded by a dielectric insulating material and a
metallic shield. They are commonly used in Cable
Television (CATV) networks and some older Ethernet
installations.
121
Fiber optic cables use strands of glass or plastic to transmit data as
pulses of light. They offer high data transfer rates, long-distance
capabilities, and immunity to electromagnetic interference. Fiber
optics are commonly used in high-speed data networks,
telecommunications, and internet backbone connections.
D. Ethernet Cable:
Ethernet cables, such as Cat5e, Cat6, and Cat7, are a
subset of twisted pair cables specifically designed for
Ethernet networking. They are used to connect devices
in local area networks (LANs) and provide reliable data
transmission.
B. 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 low data transfer rates compared to Wi-Fi, Infrared (IR):
Infrared communication uses infrared light to send data
between devices. It's commonly used in remote controls
122
for TVs, audio systems, and other electronic devices
used at home.
C. Microwaves:
These are high-frequency waves that can be used to
transmit data over long distances in a straight line,
but these cannot pass through solid objects. It
consists of a transmitter, receiver, and air
(transmission media).
E. 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.
G. Cellular Networks:
Cellular networks provide wireless communication over a large geographic
area using cell towers. They are the foundation for mobile phone networks
and mobile internet access.
123
Wireless transmission media allow devices to connect without using physical
cables, giving more mobility and flexibility. However, they can be affected by
interference, have a limited range, and usually provide slower data transfer
speeds compared to wired media. The choice of wireless media depends on
the coverage area needed, data transfer speed, power usage, and potential
interference in the environment.
Sink Node:
It's a node that doesn't connect to other nodes. It sends information to other
nodes but can't get information by itself.
Network Devices:
For smooth working of computer network, other than computers and wirings,
many devices play an important role. These devices are known as Network
Devices.
A. Modem:
MODEM or Modulator-Demodulator allows us to reach the global
network easily. It is used to send and receive the data over the
telephone lines or cable connections. Since ordinary telephone lines
cannot carry digital information, a modem changes the data from
Analog to Digital format and vice versa.
C. NIC:
A Network Interface Card (NIC) is a device used to connect the
network to the Internet. It is sometimes called the TAP (Terminal
Access Point) since different manufacturers give different names to
this device. Hence, it is sometimes referred to as NIU (Network
Interface Unit).
124
The NIC has a unique physical address for each card, and it is known as
MAC (Media Access Control) Address.
D. MAC Address:
A MAC (Media Access Control) address is a special ID given to a
network device, like a computer or a phone, so it can talk to other
devices on a network. It's like a fingerprint for the device. This address
is stored in the device's hardware and is made up of 12 characters,
often shown as numbers and letters. MAC addresses help make sure
data gets to the right place on a network. Example:
10 : E8 : 05 : 67 : 2A : GS
Manufacturer ID Card No.
E. 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 speed
of up to 10 Gbps. It can connect devices in both
wired and wireless LAN or WAN.
F. Router:
It is responsible for forwarding data from one network to another. The
main purpose of a router is sorting and distribution of the data
packets to their destination, based on the IP address. The router uses
the Logical address scheme.
G. Logical Address:
A logical address, also known as a virtual address, is a reference used
to identify a location in memory. Logical addresses are used by the
CPU and operating system to organize and manage memory allocation
and facilitate multitasking.
H. 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.
I. Switch:
It is a device that is used to divide networks
into smaller networks called subnets or LAN
125
segments. This helps to avoid network traffic
as it divides the traffic into smaller parts. It is
responsible for filtering data packets and
then transmission over the network.
J. Repeaters:
A repeater is a network device that amplifies, restores and re-
broadcasts signals for long-distance transmission.
K. Bridge:
It is a device that links two networks. It is a smart system that knows
which system lies on which side and in which network. These can
handle the networks that follow different protocols.
L. Gateway:
It connects two dissimilar networks and establishes an intelligent
connection between local and external networks with completely
different architectures. It is also known as a protocol translator.
M. Wi-Fi Card:
It's the LAN adapter, either outside or inside the
computer, with a built-in antenna and wireless radio. Its
big advantage is that it lets a computer become a
workstation without needing a physical connection to
the network.
Network Topologies
Topology refers to how computers, devices, or nodes are connected within
a network. It defines the physical or logical layout of the network and how
data is transmitted between nodes. Different types of network topologies
include star, bus, ring, mesh, and hybrid. Each topology has its advantages
and disadvantages in terms of cost, scalability, and reliability.
A. Bus Topology:
1. In a bus topology, all devices are connected to a single communication
line called the bus or backbone.
2. Data is transmitted from one end of the bus to the other, and all
devices receive the data one by one.
3. It is relatively easy to implement and works well for small networks.
However, a single break in the bus can disrupt the entire network.
126
B. Star Topology:
1. In a star topology, all devices are connected
to a central hub or switch.
2. Each device has a dedicated point-to-point
connection to the central hub.
3. If one device or cable fails, only that specific
connection is affected, and the rest of the
network remains operational.
4. It is straightforward to add or remove
devices, making it scalable.
C. Ring Topology:
1. In a ring topology, devices are
connected in a closed loop, forming a
ring.
2. Each device is connected to exactly two
other devices, creating a continuous
circular pathway for data transmission.
3. Data travels in one direction around the
ring until it reaches the intended
recipient.
4. Failure of any single device or
connection can disrupt the entire
network.
D. Mesh Topology:
1. In a mesh topology, every device is connected
to every other device in the network. It
provides multiple unnecessary paths for data
transmission, which ensures high reliability
and fault tolerance.
2. Mesh networks are often used in important
situations where keeping the network running
all the time is very important. However,
setting up all the cables and connections can
cost a lot of money and can be hard to keep
organized.
E. Hybrid Topology:
1. A hybrid topology is a combination of two or
more basic topologies (e.g., star- bus or star-
ring).
2. It leverages the advantages of different
topologies and can be designed to suit
specific networking needs.
3. Hybrid topologies are commonly used in large networks or scenarios
127
with diverse connectivity requirements.
F. 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.
1. The root node acts as the central hub, and devices are connected to it
directly or through intermediary devices like switches or hubs.
128
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 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 the
establishment of PANs. PANs find applications in various scenarios,
such as:
129
devices.
f. Ad-Hoc Networking: These are commonly used as Ad-Hoc networks,
which are set up whenever needed and taken down when not needed
anymore. Devices can easily join the network when they're in range
and leave when they're 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 media, and can be controlled by an individual or an organization.
It is also known as Intranet as it is a network within an organization.
a. 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.
b. LANs offer high data transfer rates as the network has a limited span
enabling fast communication and resource sharing.
c. The network administrator can
easily manage and monitor
devices in a LAN.
d. The LANs are commonly used
in offices, homes, and
educational institutions.
e. LANs implement security
measures such as Firewalls,
access controls, and encryption
to protect data and
unauthorized access to the
network at a much cheaper
cost.
130
institutions to interconnect LANs and share resources like files,
databases, and applications.
c. They often use different Internet Service Providers
(ISPs) for effective data communication thereby strengthening the
backbone of the Internet.
d. These can be either privately owned, cooperative, or government-
owned to provide services to the public.
e. These networks have grown rapidly in the past few years as the spans
of cities have increased rapidly.
f. 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.
131
Difference between LAN, MAN, and WAN
Network Protocols:
These are the set of rules that are required to run the internet keeping in
mind the security of data for the sake of users.
1. TCP (Transmission Control Protocol):
a. Connection-oriented protocol for reliable data transmission.
b. Provides error checking, retransmission of lost packets, and in-order delivery.
c. Slower than UDP due to the additional overhead for reliability.
2. UDP (User Datagram Protocol):
a. Connectionless protocol for fast, unreliable data transmission.
b. No error checking or retransmission, suitable for real-time applications.
c. Lower overhead compared to TCP.
3. IP (Internet Protocol):
a. Responsible for addressing and routing packets across networks.
b. IP version 4 (IPv4) uses 32-bit addresses (e.g., 192.168.1.1).
c. IP version 6 (IPv6) uses 128-bit
addresses (e.g.,
2001:0db8:85a3:0000:0000:8a2e:0370:7334).
4. HTTP (Hypertext Transfer Protocol):
a. Used for web page communication between a client (browser) and a web
server.
b. Supports request methods like GET, POST, PUT, DELETE, etc.
5. HTTPS (Hypertext Transfer Protocol Secure):
a. Secure version of HTTP that uses encryption (TLS/SSL) to protect
data during transmission.
132
b. Uses port 443.
6. FTP (File Transfer Protocol):
a. Used for transferring files between a client and a server.
b. Can operate in active or passive mode.
7. SMTP (Simple Mail Transfer Protocol):
a. Used for sending email messages between servers.
b. Port 25 is used for unencrypted communication, and port 587 is
used for encrypted communication (SMTPS).
8. POP3 (Post Office Protocol version 3):
a. Used for retrieving email from a remote server to a local email client.
b. POP3 downloads emails to the client and removes them from the server.
9. IMAP (Internet Message Access Protocol):
a. Used for accessing email messages on a remote server from multiple clients.
b. IMAP keeps emails on the server and synchronizes changes across clients.
10. DNS (Domain Name System):
a. Translates human-readable domain names (e.g.,
www.example.com) into IP addresses.
b. Distributed hierarchical system for domain resolution.
11. DHCP (Dynamic Host Configuration Protocol):
a. Automatically assigns IP addresses and network configuration to
devices on the network.
b. Simplifies network administration by managing IP allocation.
12. ICMP (Internet Control Message Protocol):
a. Used for error reporting and diagnostics in IP networks.
b. Commonly associated with tools like ping to test network
connectivity.
13. SLIP (Serial Line Internet Protocol):
a. This is used for delivering/ relaying packets over the dial-up line.
b. It defines the encapsulation mechanism for the packets.
14. PPP (Point-to-Point Protocol):
a. It is the internet standard for the transmission of IP packets over serial lines.
b. It is currently the best solution for dial-up connections.
These are just some of the many network protocols that facilitate
communication and data transfer across the internet and local networks.
Each one serves specific purposes and plays a crucial role in modern
networking.
Web Services:
1. World Wide Web (WWW):
It is a global system of interconnected documents and resources that
are accessible over the internet. It operates based on hypertext links
which allows the users to navigate between different documents and
multimedia content.
133
2. 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.
3. URL:
Each web page and resource on the web can be accessed using a
unique address called the URL (Uniform Resource Locator).
4. Web Browser:
To access and view web pages on the internet (WWW), we need to
have an application named Web Browser. There are many web
browsers available on the internet like Google Chrome, Microsoft
Edge, Mozilla Firefox etc.
5. 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.
6. Weblinks:
These are the links available within the web pages that allow the users
to access the pages that contain the topic-related content.
7. HTML:
Hyper Text Markup Language (HTML) was developed to structure and
organize 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 the presentation of
content.
8. XML:
Extensible Markup Language (XML) is designed to carry and store data
in a structured and platform-independent format. These use 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.
9. Websites:
These are collections of various web pages and data that are
accessible to all and are available on the internet. Many types of
restrictions such as screenshot protections, and copying of data can be
implemented on the websites for data protection.
10.Web Hosting:
This refers to the service of providing storage space, server resources,
and internet connectivity to make websites and web applications
134
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.
135
15. Remote Access VPN:
Allows individual users to connect securely to a corporate network
from remote locations using client software installed on their devices.
136
Multiple Choice Questions:
1) Which network topology is characterized by a central node that connects
all devices on the network?
a) Bus
b) Star
c) Ring
d) Mesh
2) In a bus topology, what happens if there is a break in the main communication line?
a) The entire network becomes inoperative
b) Only the affected segment becomes inoperative
c) Data packets are automatically rerouted through an alternative path
d) The network speed decreases but remains functional
3) Which network topology provides fault tolerance and redundancy due to
multiple interconnections between devices?
a) Bus
b) Star
c) Ring
d) Mesh
4) In a ring topology, what prevents data packets from endlessly circulating the loop?
a) Bridges
b) Routers
c) Token passing
d) Firewalls
5) Which network topology allows the expansion of the network by simply
adding more devices to the central hub?
a) Bus
b) Star
c) Ring
d) Mesh
6) What is the main disadvantage of a mesh topology?
a) High installation cost
b) Difficult to set up
c) Limited scalability
d) Susceptible to data collisions
7) Which network topology is commonly used in Ethernet networks and
provides centralized management?
a) Bus
b) Star
c) Ring
d) Mesh
8) In a star topology, what happens if the central hub fails?
a) The entire network becomes inoperative
b) Only the affected segment becomes inoperative
c) Data packets are automatically rerouted through an alternative path
d) The network speed decreases but remains functional
137
9) Which network topology is best suited for small networks and has a
simple and cost- effective design?
a) Bus
b) Star
c) Ring
d) Mesh
10) What network topology is typically used in token ring networks to
regulate data transmission?
a) Bus
b) Star
c) Ring
d) Mesh
11) Which transmission medium uses electrical signals to transmit data over
short distances inside a computer or between devices in a local network?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Infrared transmission
12) Which transmission medium offers the highest data transmission speeds
and is immune to electromagnetic interference?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Wireless transmission
13) In fiber-optic cables, data is transmitted through:
a) Electric signals
b) Infrared waves
c) Radio waves
d) Light pulses
14) Twisted-pair cables are commonly categorized into two types: unshielded
twisted pair (UTP) and:
a) Fiber-optic twisted pair (FOTP)
b) Shielded twisted pair (STP)
c) Coaxial twisted pair (CTP)
d) Broadband twisted pair (BTP)
15) Which transmission medium is most susceptible to signal attenuation
(weakening) over long distances?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Microwave transmission
16) The transmission medium that uses radio waves to carry signals is known as:
a) Wi-Fi
b) Bluetooth
c) Fiber-optic cable
138
d) Twisted-pair cable
17) Which transmission medium is commonly used for cable television (CATV)
and internet services?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Satellite transmission
18) What type of transmission medium is suitable for underwater
communications and long- distance networking?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Infrared transmission
19) Which transmission medium uses the least secure method of data
transmission and is easily intercepted by unauthorized users?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Wireless transmission
20) Which transmission medium allows communication between devices
using infrared light waves?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Infrared transmission
21) Which of the following networks covers a large geographic area and is
often used to connect multiple local area networks (LANs)?
a) LAN (Local Area Network)
b) WAN (Wide Area Network)
c) MAN (Metropolitan Area Network)
d) PAN (Personal Area Network)
22) Which type of network is designed to connect devices within a limited
physical area, such as a home or office?
a) WAN (Wide Area Network)
b) LAN (Local Area Network)
c) SAN (Storage Area Network)
d) WLAN (Wireless Local Area Network)
23) The network that uses radio waves to connect devices without the need
for physical cables is called:
a) WLAN (Wireless Local Area Network)
b) WAN (Wide Area Network)
c) MAN (Metropolitan Area Network)
d) SAN (Storage Area Network)
24) A network that is completely contained within a single device, such as
connecting a smartphone to a smartwatch, is known as:
139
a) LAN (Local Area Network)
b) PAN (Personal Area Network)
c) WAN (Wide Area Network)
d) WLAN (Wireless Local Area Network)
25) A network that spans across multiple buildings within a campus or a city is called:
a) LAN (Local Area Network)
b) WAN (Wide Area Network)
c) PAN (Personal Area Network)
d) MAN (Metropolitan Area Network)
26) What type of network is the internet?
a) LAN (Local Area Network)
b) WAN (Wide Area Network)
c) SAN (Storage Area Network)
d) MAN (Metropolitan Area Network)
27) Which type of network is the most suitable for securely sharing
information between two geographically distant offices of the same
organization?
a) LAN (Local Area Network)
b) WAN (Wide Area Network)
c) SAN (Storage Area Network)
d) WLAN (Wireless Local Area Network)
28) What type of network is commonly used to connect devices like printers,
scanners, and computer peripherals?
a) LAN (Local Area Network)
b) PAN (Personal Area Network)
c) WLAN (Wireless Local Area Network)
d) MAN (Metropolitan Area Network)
140
14. What are the main drawbacks of coaxial cables?
15. What advantage do fibre optic cables have over coaxial cables?
16. Name some examples of devices that use infrared signals.
17. Which type of transmission media offer more security- guided or
unguided? Why?
18. Which transmission media is commonly used to transmit data over short distances?
19. Which transmission media is commonly used to transmit data over long distances?
20. What are the main factors that influence the choice of transmission media in a
network?
21. What is a Local Area Network (LAN)?
22. What is a Personal Area Network (PAN)?
23. What is a Metropolitan Area Network (MAN)?
24. What is a Wide Area Network (WAN)?
25. What is Virtual Private Network (VPN)?
26. What is a domain name service?
27. What do you understand by Web Hosting?
28. Define website, web link, and web server.
29. Differentiate between hypertext and hyperlink.
30. What are the different internet protocols?
31. Define SMTP, POP, and FTP.
32. Define WWW.
33. Define XML.
34. Define HTML.
141
Case Study based questions
Ques: 1 A web server is a special computer system running on HTTP through web pages.
The web page is a medium to carry data from one computer system to another.
The working of the webserver starts from the client or user. The client sends their
request through the web browser to the webserver. The web server takes this
request, processes it and then sends back processed data to the client. The server
gathers all of our web page information and sends it to the user, which we see on
our computer system in the form of a web page. When the client sends a request
for processing to the web server, a domain name and IP address are important to
the webserver. The domain name and IP address are used to identify the user on
a large network.
A. Web servers are:
a. IP addresses
b. Computer systems
c. Webpages of a site
d. A medium to carry data from one computer to another
B. What does the web server need to send back information to the user?
a. Home address
b. Domain name
c. IP address
d. Both b and c
C. What is the full form of HTTP?
a. Hypertext Transfer Protocol
b. Hypertext Transfer Procedure
c. Hyperlink Transfer Protocol
d. Hyperlink Transfer Procedure
D. The translates internet domain and host names to IP address
a. Domain name system
b. Routing information protocol
c. Google
d. Network time protocol
E. A computer that requests resources or data from another computer is
called as __________computer
a. Server b. Client c. None of the above d. a and b
F. DNS stands for:
a. Domain Name Security
b. Domain Number System
c. Document Name System
d. Domain Name System
G. What is the format of the IP address?
a. 34 bit b. 32 bit c. 16 bit d. 64 bit
142
Ques: 2 In mid-80’s another federal agency, the NSF created a new high-capacity network
called NSFnet, which was more capable than ARPANET. The only drawback of
NSFnet was that it allowed only academic research on its network and not any
kind of private business on it. Now, several private organizations and people
started working to build their networks, named private networks, which were
later (in the 1990s) connected with ARPANET and NSFnet to form the Internet.
The Internet became popular in the 1990s after the development of the World
Wide Web.
vi. A piece of icon or image on a web page associated with another webpage
is called
1. URL
2. Hyperlink
3. Plugin
4. Extension
143
Ques: 3 TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of
communication protocols used to interconnect network devices on the
internet. TCP/IP can also be used as a communications protocol in a private
computer network (an intranet or an extranet). TCP defines how applications
can create channels of communication across a network. It also manages how a
message is assembled into smaller packets before they are then transmitted
over the internet and reassembled in the right order at the destination address.
IP defines how to address and route each packet to make sure it reaches the
right destination. Each gateway computer on the network checks this IP address
to determine where to forward the message. TCP/IP uses the client-server
model of communication in which a user or machine (a client) is provided a
service (like sending a web page) by another computer (a server) in the
network. Collectively, the TCP/IP suite of protocols is classified as stateless,
which means each client request is considered new because it is unrelated to
previous requests. Being stateless frees up network paths so they can be used
continuously.
1. Which of the following protocols is used in the internet?
a) HTTP b. DHCP c. DNS d. All of the above
2. Which one of the following is an application layer protocol used on the
internet?
a) Remote procedure call
b) Internet relay chat
c) Resource reservation protocol
d) Local procedure call
3. Which protocol assigns an IP address to the client connected to the internet?
a) DHCP
b) IP
c) RPC
d) RSVP
4. Several protocols for upper layers in Bluetooth use:
a) UDP b) HSP c) ETC d) L2CAP
5. Internet protocols are a set of rules to govern:
a) communication between computers on a network
b) standard
c) metropolitan communication
d) bandwidth
6. Checksum is used on the internet by several protocols although not at the
a) session layer
b) transport layer
c) network layer
d) data link layer
7. The network layer at the source is responsible for creating a packet from
data coming from another
a) Station b) link c) node d) protocol
144
Ques: 4 A blog is a publication of personal views, thoughts, and experiences on web
links. It is a kind of personal diary note about an individual. The contents
published on a blog are organized in a reverse manner, which means recent
posts appear first and the older posts are further downwards. Blogger – a
person who posts a blog in the form of text, audio, video, weblinks, etc is
known as a blogger. Bloggers have followers who follow them to get instant
messages posted by the blogger. In most cases, celebrities, business tycoons,
famous politicians, social workers, speakers, etc. are successful bloggers
because people follow them to learn about their success stories and ideas.
i. Using websites for building networks with friends and relatives is called as
a. social networking
b. blogging
c. net-banking
d. e-commerce
ii. Websites used to buy and sell something are categorized under
a. social networking sites
b. e-commerce websites
c. search engines
d. entertainment sites
iii. Google is an example of
a. social network
b. entertainment
c. search engine
d. none of these
iv. Which of the following is an example of micro-blogging?
a. Orkut
b. facebook
c. google +
d. X
v. Which of the following is not used as a blogging platform?
a. TypePad
b. Blogger
c. WordPress
d. Pinterest
vi. _________ was one of the first uses of the Internet and is still the most
popular use, accounting for most of the traffic on the Internet.
a. blogs
b. chat rooms
c. E-mail
d. discussion boards
145
Ques: 5 An email is a service of sending or receiving emails or
messages in the form of text, audio, video, etc. over the
internet. Various service providers are providing email
services to users. The most popular service providers in India
are Gmail, Yahoo, Hotmail, Rediff, etc. An email address for
an email account is a unique ID. This email ID is used to
send and receive mail over the Internet. Each email address
has two primary components: username and domain name.
The username comes first, followed by the @) symbol and
then the domain name.
1. Unsolicited e-mail advertising is known as
a. newsgroup
b. junk ads
c. spam
d. none of the above
2. Which of the following is the correct format of email address?
a. name@website@info
b. [email protected]
c. www.nameofwebsite.com
d. name.website.com
3. MIME stands for
a. multipurpose internet mail extensions
b. multipurpose internet mail email
c. multipurpose internet mail end
d. multipurpose internet mail extra
4. Mail access starts with a client when the user needs to download e-mail
from the
a. mail box
b. mail server
c. IP server
d. Internet
5. When the sender and receiver of an email are on the same system, we
need only two
a. IP
b. domain
c. servers
d. user agents
6. NVT stands for
a. network virtual transmission
b. network virtual test
c. network virtual terminal
d. network virtual tell
146
Ques: 6 In 1989, Tim Berners Lee, a researcher, proposed the idea of the World Wide
Web). Tim Berners Lee and his team are credited with inventing Hyper Text
Transfer Protocol (HTTP), HTML and the technology for a web server and a web
browser. Using hyperlinks embedded in hypertext the web developers were able
to connect web pages. They could design attractive webpages containing text,
sound and graphics. This change witnessed a massive expansion of the Internet
in the 1990s.
i. What is a web browser?
a. A program that can display a webpage
b. A program used to view HTML documents
c. It enables a user to access the resources of the internet
d. All of the above
ii. Dynamic web page
a. is the same every time whenever it displays
b. generates on demand by a program or a request from the browser
c. both are the same every time whenever it displays and
generates on demand by a program or a request from the
browser
d. is different always in a predefined order
iii. URL stands for
a. unique reference label
b. uniform reference label
c. uniform resource locator
d. unique resource locator
iv. AJAX stands for
a. asynchronous javascript and XML
b. advanced JSP and XML
c. asynchronous JSP and XML
d. advanced javascript and XML
v. What is DOM?
a. convention for representing and interacting with objects in HTML
documents
b. application programming interface
c. hierarchy of objects in ASP.NET
d. scripting language
vi. An alternative to JavaScript on the Windows platform is
a. VBScript
b. ASP.NET
c. JSP
d. PHP
vii. A web cookie is a small piece of data that is
a. sent from a website and stored in the user’s web browser
while a user is browsing a website
b. sent from a user and stored in the server while a user is browsing a
website
c. sent from the root server to all servers
d. sent from the root server to other root servers
147
Ques: 7 E-business, commonly known as electronic or online business is a business where
an online transaction takes place. In this transaction process, the buyer and the
seller do not engage personally, but the sale happens through the internet. In
1996, Intel’s marketing and internet team coined the term “E-business. E-
Commerce stands for electronic commerce and is a process through which an
individual can buy, sell, deal, order and pay for products and services over the
internet. In this kind of transaction, the seller does not have to face the buyer to
communicate. A few examples of e-commerce are online shopping, online ticket
booking, online banking, social networking, etc.
148
Ques: 8 Due to the rapid rise of the internet and digitization, Governments all over the
world are initiating steps to involve IT in all governmental processes. This is the
concept of e-government. This is to ensure that the Govt. administration
becomes a swifter and more transparent process. It also helps save huge costs.
E-Group is a feature provided by many social network services which helps you
create, post, comment to and read from your “own interest” and “niche-specific
forums”, often over a virtual network. “Groups” create a smaller network within
a larger network and the users of the social network services can create, join,
leave and report groups accordingly. “Groups” are maintained by “owners,
moderators, or managers”, who can edit posts to “discussion threads” and
“regulate member behaviour” within the group.
i. E-Government:
a. can be defined as the “application of e-commerce technologies to
government and public services.”
b. is the same as internet governance
c. can be defined as “increasing the participation in internet use by socially
excluded groups”
d. none of the above
ii. Privacy law is intended to protect the personal information about:
a. Individuals in society
b. computer networks
c. Employees
d. Students
iii. What does TAN stand for?
a. Tax Deduction Account Number
b. Tax Deduction and Collection Account Number
c. Taxable Account Number
d. Tax Account Number
iv. An e-group is a collection of users
a. who conducts seminars
b. who get together on weekends
c. who have regular video conferences
d. having the ability to access and contribute to forum topics
v. Whenever a new comment is posted, users of the e-group recent a
notification that there is a new contribution to the discussion.
a. SMS
b. E-mail
c. WhatsApp
d. Calls
149
Ques: 9 Search Engines allow us to filter the tons of information available on the internet
and get the most accurate results. And while most people don’t pay too much
attention to search engines, they immensely contribute to the accuracy of
results and the experience you enjoy while scouring through the internet.
Besides being the most popular search engine covering over 90% of the
worldwide market, Google boasts outstanding features that make it the best
search engine in the market. It boasts cutting-edge algorithms, an easy-to-use
interface, and a personalized user experience. The platform is renowned for
continually updating its search engine results and features to give users the best
experience.
1. Search engines are:
a. Software systems that are designed to search for information on the
world wide web
b. Used to search documents
c. Used to search videos
d. All of the above
2. We get a list of sites after typing a word in the search bar called:
a. Single word
b. Key phrase
c. Site
d. All of the above
3. The search results are shown in a line of results. This is called:
a. Search engine pages
b. Categories
c. Search engine result pages
d. Tag list
4. Search engines can search which type of information.
a. Videos
b. Images
c. Documents
d. All of the above
5. Web search engines store information about web pages with the help of:
a. Web router
b. Web crawler
c. Web indexer
d. Web organizer
6. Web crawler is also called:
a. Web spider
b. Web manager
c. Ink directory
d. Search optimizer
7. SEO is the process of _______ of a website or a web page in a search
engine’s search results.
a. Generating cached files
b. Affecting the visibility
c. Getting meta tags
a. All of these
150
Ques: 10 Ayurveda Training Educational Institute is setting up its centre in Hyderabad
with four specialized departments for Orthopedics, Neurology and Pediatrics
along with an administrative office in separate buildings. The physical distances
between these department buildings and the number of computers to be
installed in these departments and administrative offices are given as follows.
You, as a network expert, have to answer the queries as raised by them in (i) to
4. Suggest the topology of the network and network cable for efficiently
connecting each computer installed in each of the buildings out of the
following:
Topologies: Bus Topology, Star Topology
151
Ques: 11 M/S Adco Informatics Services is an educational service organization.
It is planning to setup its India campus in Chennai with its head office
in Hyderabad. The Chennai campus has 4 buildings- ADMIN, MEDIA,
ENGINEERING, and BUSINESS.
Head
Office
Admin Engineering 45 m
Admin Business 80 m
Engineering Business 25 m
Admin Media 60 m
Engineering Media 60 m
Business Media 75 m
Admin 140
Engineering 70
Business 35
Media 20
Hyderabad 30
1. Suggest and draw the cable layout to efficiently connect various blocks of
buildings within the Chennai campus for connecting the devices.
2. Which network device will be used to connect computers in each block
to form a local area network?
3. Which block, in Chennai Campus should be made the server? Justify.
4. Which fast and effective wireless transmission medium should preferably
be used to connect the head office at Hyderabad with the campus in
Chennai?
5. Is there a requirement for a repeater in the given cable layout?
Why/Why not?
152
Ques: 12 Rocksons Communications International (RCI) is an online corporate training
provider company for IT-related courses. The company is setting up their new
campus in Bengaluru. You as a network expert have to study the physical
locations of various blocks and the number of computers to be installed. In the
planning phase, provide the best possible answers for the queries (i) to (v) raised
by them.
i. Suggest the most appropriate block, where RCI should plan to install the
server.
ii. Suggest the most appropriate block-to-block cable layout to connect all
three blocks for efficient communication.
iii. Which type of a network out of the following is formed by connecting the
computers of these three blocks? (LAN, MAN, WAN, PAN)
iv. Which wireless channel out of the following should be opted by RCI to
connect to students from all over the world? (Infrared, Microwave,
Satellite)
v. What is the satellite communication?
153
Ques: 13 Ayurveda Training Educational Institute is setting up its centre in Hyderabad with
four specialized departments for Orthopedics, Neurology and Pediatrics along
with an administrative office in separate buildings. The physical distances
between these department buildings and the number of computers to be
installed in these departments and administrative offices are given as follows.
You, as a network expert, have to answer the queries raised by them.
Shortest distances between various locations in metres :
Pediatrics Unit 45
Neurology 60
Orthopedics Unit 85
i. Suggest the most suitable location to install the main server of this
institution to get efficient connectivity.
ii. Suggest the best cable layout for effective network connectivity of the
building having a server with all the other buildings.
iii. Suggest the devices to be installed in each of these buildings for
connecting computers installed within the building out of the
following:
(1) Gateway (2) Modem (3) Switch
iv. Suggest the topology of the network and network cable for efficiently
connecting each computer installed in each of the buildings out of the
following:
Topologies: Bus Topology, Star Topology
Network Cable: Single Pair Telephone Cable, Coaxial Cable,
Ethernet Cable.
154
Ques: 14 Sanskar University of Uttarakhand is
setting up a secured network for its
campus at Nainital for operating day-
to-day office and web-based
activities. They are planning to have
network connectivity between four
buildings. Answer the questions after going through the building positions on
the campus and other details given below:
The distance between various buildings of the university is given as follows:
Main Admin 50
Main Academics 70
Admin Finance 50
Finance Academics 70
Admin Academics 40
Number of Computers:
Main 200
Admin 100
Finance 75
Academics 70
As an expert, you are required to give the best possible solutions for the given
queries of the university administration:
a. Suggest the cable layout for the connection between the various
buildings.
b. Suggest the most suitable building to house the server of the
network of the university.
c. Suggest the placement of the following devices with justification:
Switch/Hub Repeater
d. Suggest the technology out of the following for setting-up very fast
internet connectivity among buildings of the university
Optical Fibre
Coaxial Cable
Ethernet Cable
155
Ques: 15 A school library is connecting computers in its units in a LAN. The
library has 3 units as shown in the diagram below:
Circulation Unit
Students Unit
Teachers Unit
156
Ques: 16 MyPace University is setting up its academic blocks at Naya Raipur and is
planning to set up a network. The University has 3 academic blocks and one
Human Resource Centre as shown in the diagram below:
a. Suggest the most suitable place (i.e., Block/Centre) to install the server of
this university with a suitable reason.
b. Suggest an ideal layout for connecting these blocks/centres for wired
connectivity.
c. Which device will you suggest to be placed/installed in each of these
blocks/centres to efficiently connect all the computers within these
blocks/centres?
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 1250 Km from the university. Which type of network of LAN,
MAN or WAN will be formed? Justify your answer.
157
EXERCISES
Long Answer Type Questions
1. Differentiate between the Circuit switching, and Packet Switching techniques with
examples.
2. Explain the Wired Transmission media with the help of suitable examples and
diagrams.
OR
Explain the guided transmission media with the help of suitable examples.
3. Explain the unguided transmission media with the help of suitable examples.
OR
Explain the various wireless transmission media with the help of suitable diagrams.
4. What do you understand by network topologies? Explain in brief, the various
topologies available for establishing a successful network.
5. What are the ways by which a network can be setup in a building? Give reasons to
support your answer.
6. Differentiate between LAN, MAN, and WAN giving suitable examples.
7. Based on the geographical span, what are the various topologies used for
establishing communications? Explain giving suitable examples and diagrams.
8. Explain the concept of bus topology. How is it different from bi-directional ring
topology?
9. Discuss the tree topology in detail. What are its applications and potential
limitations?
10. Discuss the advantages and drawbacks of guided transmission media.
11. What are the advantages and drawbacks of unguided transmission media?
158
CASE STUDIES
Ques 1 Infotainment Ltd. Is an event management company with its prime office
located in Bengaluru. The company is planning to open its new division at
three different locations in Chennai named Vajra, Trishula, and Sudershana.
You, as a networking expert need to suggest solutions to the questions in
part (a) to (e), keeping in mind the distances and other given parameters.
159
Ques 2 Quackers Inc., an IT-based firm, located in Delhi is planning to setup a
network for its four branches within a city with its Marketing department in
Kanpur. As a network professional, give solutions to questions (i) to (v), after
going through the branch locations and other details which are given below:
Distance between various branches is as follows:
Branch Distance
Branch A to Branch B 40 m
Branch A to Branch C 80 m
Branch A to Branch D 65 m
Branch B to Branch C 30 m
Branch B to Branch D 35 m
Branch C to Branch D 15 m
Delhi Branch to Kanpur 300 km
Number of computers in each of the branches:
Branch Number of Computers
Branch A 15
Branch B 25
Branch C 40
Branch D 115
i.Suggest the most suitable place to install the server for the Delhi branch
with a suitable reason.
ii.Suggest an ideal layout for connecting all these branches within Delhi.
iii.Which device will you suggest that should be placed in each of these
branches to efficiently connect all the computers within these branches?
iv.Delhi firm is planning to connect to its Marketing department in Kanpur
which is approximately 300 km away. Which type of network of LAN,
MAN, or WAN will be formed? Justify your answer.
v.Suggest a protocol that shall be needed to provide help for transferring
files between the Delhi and Kanpur branches.
160
Ques 3 Trinity Tech Corporation is a professional consultancy company. The company
is planning to set up their new offices namely HR, Sales, and Production in
India with its hub at Hyderabad. As a network adviser, you have to understand
their requirements and suggest the best available solutions, their queries are
mentioned in (A) to (D) below.
A. Which will be the most appropriate block where TTC should plan to install
their server?
B. Draw a block cable layout to connect all the buildings in the most
appropriate manner for efficient communication.
C. What will be the best possible connectivity out of the following, you will
suggest connecting the new set up of offices in Bengaluru with its
Amsterdam-based office.
● Satellite Link
● Microwave
● Fiber-Optic Cable
D. Which of the following devices will be suggested by you to connect each
computer in each of the buildings?
● Switch
● Modem
● Gateway
161
Ques 4 The Indian Heights School in Mussoorie is starting up the network between its
different wings. There are four buildings named SENIOR, JUNIOR, ADMIN,
and HOSTEL as shown below.
162
Ques 5 The Aakar University of Madhya Pradesh is setting up a secured network for its
campus in Himachal Pradesh for operating its day-to-day office and web-based
activities. They are planning to have network connectivity between four
buildings. Answer the question (a) to (d) after going through the building
positions on the campus and other details which are given below:
The distances between various buildings of the university are given as:
Building 1 Building 2 Distance (in meters)
Main Admin 50
Main Finance 100
Main Academic 70
Admin Finance 50
Finance Academic 70
Admin Academic 60
Number of Computers:
Building No. of Computers
Main 150
Admin 75
Finance 50
Academic 60
As a network expert, you are required to give the best possible solutions for
the given queries of the university administration:
a. Suggest the cable layout for the connections between the various
buildings.
b. Suggest the most suitable building to house the server of the network of
the university.
c. Suggest the placement of the following with justification:
● Switch/Hub
● Repeater
d. Suggest the communication media out of the following for setting-up very
fast Internet connectivity among buildings of the university
● Optical Fiber
● Coaxial Cable
● Ethernet Cable
163
Topics to be covered
Database concepts
Relational data model
Structured Query Language
Interface of Python with an SQL database
164
165
UNIT-III
DATABASE MANAGEMENT:
DATABASE CONCEPT:
INTRODUCTION OF DATABASE:
Database is a word which is composed of two words: Data and Base. Data means raw facts and
figures and base is the place or location where data is being stored.
Or we can say that a Database is a collection of interrelated data or records in an organized form.
So, it can be easily accessed, managed and updated. Interrelated data means that the data is related
or connected with respect to the given attribute/column.
The database uses various fields to manage and store large amounts of information in an organized
and structured format.
Need of Database:
1. Centralized Storage: Storage of data in a single location or central database.
2. Data Integrity: Enforces data integrity rules which ensures that the information stored is
accurate, valid and consistent.
3. Data Security: Control access to sensitive data and protect data from unauthorized access.
4. Data Retrieval: Authorized Users/Applications can access and retrieve the information as
per their need.
5. Efficient Data Retrieval: Database helps users to retrieve data efficiently.
166
DBMS Model:
DBMS refers to the architecture/approach for how data is stored, organized and manipulated in a
database. There are several types of DBMS Models.
1. Relational Model:
Data is organized in tables with rows and columns.
2. Hierarchical Model:
Data is organized in a Tree-like structure to the parent-child relationship.
3. Network Model:
Similar to the hierarchical model. It uses pointers to navigate through data.
4. Object-Oriented Model:
Data is represented as an object. This model uses object-oriented databases.
Now as per your CBSE syllabus, we will discuss the Relational Data Model in detail.
167
Relational Data Model:
The relation Data Model was proposed by E.F. Codd in 1970.
In simple words, we can say that a Relational data model is a model which uses relation to organize
data. Here, Relation means table and table is composed of rows and columns.
After creating a conceptual data model using an ER (Entity Relationship) Diagram we need to
convert it into a Relational Data Model so that we can implement it using any RDBMS language like
MySQL, Oracle SQL etc.
Before we proceed further, let’s discuss some aspects of the Conceptual Data Model
Conceptual Data Model is used to capture the meaning of data from the viewpoint of the user and
try to represent it using Data Model tools like ER diagrams and Object Oriented Diagram
168
Relation/Table:
Relation is also known as table and table is a collection of related data and information in rows and
columns. The relation is composed of rows and columns.
Row/Tuple/Record:
Row represents the horizontal form of Table/Relation. A row is also known as a tuple/record.
Column/Attributes:
Columns represent the vertical form of the Table/Relation. The column is also known as an attribute.
Cardinality:
The total number of rows/records/tuples in a relation is called Cardinality.
Degree:
The total number of columns/attributes in a relation is called the Degree.
Domain:
Domain is a set of possible values or range of valid values or a set of all unique values that an
attribute/column can hold.
A Domain of a database is a set of atomic values (which can’t further be distributed) of a particular
attribute/column.
169
For Example:
In the table Employee, Attribute/column ‘gender’ may have only ‘M’, ‘F’ and ‘T’ domains. Only these
values are valid for that column.
The domain of ‘S_No’ contains a set of all possible roll numbers.
Domain of ‘Martial_Status’ contains a set of all possible values like ‘Married’, ‘Widow’, ‘Unmarried’
or ‘Divorce’.
In the below diagram 4, table Employee contains ‘S_No’, ‘Name’, ‘Address’, ‘Gender’ and
‘Marital_status’. Two domains are showing ‘gender’ and ‘marital_status’ which contain a set of
possible values that an attribute can hold. Gender can only hold three possible values and marital
status can only hold four possible values.
DATATYPES IN SQL:
Before discussing commands in detail we need to learn about the datatype of
column/attribute:
We need to assign a data type when we are declaring any column/attribute. Every column required
a name and datatype. This data type is used to declare the type of data that will be stored in a
particular column. There are lots of data types available in SQL. We will discuss some important
data types here.
170
Commonly used datatype in SQL:
1. Numeric Type:
171
VARCHAR(SIZE) varchar stands for a variable length character
string.
range of varchar is 0 to 65535
DATE AND DATE As the name suggests it is used to store the date
in any attribute
TIME
supported format : YYYY-MM-DD
DATATYPE
TIME Used to store time in any attribute
supported format : HH:MM:SS
Keys:
In the database, the key applies some kind of constraint/restriction on the table (depending on the
type of key applied) or we can say that keys are used to uniquely identify a tuple in a table/relation.
To extract any particular row/record from a table, we need a key attribute which contains unique
values.
172
Primary Key:
Primary Key is a unique identifier which identifies a unique record in a particular table. It must
contain unique values for each record and the Primary key attribute/column/field can’t be NULL. A
table can have only ONE primary key.
Note: A Primary key must be a candidate key but not all candidate keys are Primary key.
Candidate Key:
Candidate key is a set of one or more columns that could be used as primary key and from the set
of these candidate keys, one column is selected as primary key.
From Diagram 5, Candidate keys can have more than one attribute like Emp_ID, Name, and Address
etc.
Alternate Key:
After selecting the primary key from the candidate key, the remaining keys (which are also eligible
for the primary key) are called Alternate Key.
Foreign Key:
A Foreign key is a column or group of columns in a table that provides a link between two tables.
It is an attribute whose values can be derived from the primary key of some other table.
It ensures Referential Integrity. Referential Integrity is a protocol that ensures that the relationship
between record/row is valid and can’t change in related data.
173
DBMS2 - QUESTION-RELATED TO RELATIONAL DATA MODEL
174
25 Which clause is used to sort the result set in ascending order
26 Which operator is used to search for a specific pattern in a column?
27 Key constraints ensure that each column of the table contains a unique value for each row.
28 Which key constraints ensure that a column in a table does not contain any NULL values?
29 Which DDL command is used to modify a table.
30 Which clause is used to filter the result set of groups?
175
SQL perform the following operation:
▪ Create a database
▪ Create a table
▪ Create view
▪ Insert data
▪ Update data
▪ Delete data
▪ Execute Query
▪ Set Permission or Constraints in the table
SQL Commands:
SQL commands are a predefined set of commands which are already defined in SQL. Commands are
combinations of keywords and statements you want to execute. Keywords are reserved words that
have special meaning for SQL, you don’t need to define them as they are already defined in SQL. All
you need to use these keywords with your particular statements.
CLAUSE IN SQL:
Clause: Clause are built-in functions which are used to deal with data inside the table that help SQL
to filter and analyse data quickly.
176
Any SQL statement is composed of two or more clauses.
These clauses are used with your SQL statements to filter commands you may learn in detail in
further sections. Some mainly used clauses are discussed below.
NOTE: All SQL statements are terminated with (;) semicolon
SQL statements are not case sensitive, which means SQL treats both upper and lowercase
commands as the same.
177
SQL (Structured Query Language)
Constraints:
Constraints in SQL are sets of rules that are applied to the data in a relation/table. Constraints are
used to ensure the accuracy and reliability of the data. Constraints can be at column level or table
level. Column-level constraints apply to a column, and table-level constraints apply to the whole
table. After applying constraints to the table, if any violation happens, then the data can’t be
inserted or the action can’t be completed.
Types of constraints:
1. Unique: This constraint ensures that all values present or inserted in a column are different.
2. Not Null: This constraint ensures that no null values are present or inserted in a column.
3. Primary key: The primary key applies both unique and not null constraints to the column. It
uniquely identifies a unique tuple/row in a relation/table.
4. Foreign Key: unique, not null and primary key constraint applies to a single table whereas the
foreign key constraint applies to two tables.
Let’s assume that our parent table Student has already been created. Now we will create child
table awards and apply foreign key constraints on it. (Note: Foreign key relation can only be
applied on child table)
SQL Query
create table <child table name> (<column name 1> <data type>, <column name 2> <data
type>,…, foreign key(<column name>) references <parent table name>(<column name>));
Foreign key constraint ensures that only that data can be inserted in column ID of the
Awards table which is present in column ID of the Student table.
178
Here, As ID ‘1’ is already present in the parent table ‘student’, So, ID ‘1’ can be inserted in the
child table ‘awards’.
Now, we will try to insert ID ‘6’ in the child table ‘awards’ which is not present in the parent
table ‘student’.
Here we can see that when we tried to insert value 6 in column ID of child table awards, it
showed an error. This is how a foreign key works.
179
Show tables: To view the list of
available/created databases in SQL, the show
tables command is used.
Query: show tables;
Create table: To create a new table in the selected database. For example, if I want to create a table
Student with the following attributes and data types:
180
inserted in the previous
command.
Query: select * from <table
name>;
181
Query: alter table <table name> add <column name><data type> [constraint];
Example: Let’s add a column ‘class’ with data type varchar and size 50 and nulls are not allowed.
(b) Drop a column from the table: Let’s delete the column ‘class’ from the table ‘student’ which we
added in the previous section.
Command: alter table <table name> drop column<column name>;
(c) Modifying column of a table: We have different ways to modify a table like column name, data
type, default value, size, order of columns, and constraints.
(i) Changing column name: We can change the column name of a table using the alter
command.
Example: In table student, Let’s change column name Student_ID to ID.
Query: alter table <table name> change column <old column name> <new column name>
<data type>
182
(ii) Changing column data type: We can change the column data type from varchar to char or
int to varchar etc. of a table using the alter command.
Example: in table student, Let’s change the datatype of column ‘ID’ from int to varchar.
Query: alter table <table name> modify column <column name> <new data type> <size>
(iii) Changing the maximum size of the data in a column: We can change the maximum size of
the data in a column of a table using the alter command.
Example: In table student, Let's change the size of column ID from varchar(50) to
varchar(40)
Query: alter table <table name> modify column <column name> <data type with size>
183
(iv) Changing the order of the column: We can change the order of the column of a table using
the alter command. For example, in table student, we are going to place column ID after
column Age.
Query: alter table <table name> modify <column name> <data type with size> [first|after
<column name>]
184
(v) Add/drop constraints/column: We can add/drop constraints in a table using the alter
command.
Adding primary key: Let’s add the primary key at column ‘ID’ using the alter command.
Dropping primary key: Let’s remove the primary key at column ID which was added in
the previous section.
185
Adding a new column: Let’s add a column ‘country’ with data type char of size 50 to
the table ‘student’ using the alter command.
Query: alter table <table name> add column <column name> <data type with size>;
Dropping a column: Let’s remove a column ‘country’ which was added in the last
section using the alter command.
We have already covered a few DML Commands like insert and select. Now we will discuss delete
and update commands.
1. Delete command: The delete command is used to delete data from the table. Where clause is
used to give condition in a SQL query. All those tuples which satisfy the condition will be deleted
from the table.
Command: delete from <table name> where <condition>;
Now, let’s delete the data of all those students from the student table whose ID is greater than
5.
186
2. Update command: The update command is used to update data from the table. Where clause
is used to give condition in a SQL query. All those tuples which satisfy the condition will be
updated in the table.
Command: update <table name> set <column name>=<new data> where <condition>;
Now, let’s update the Address from ‘Delhi’ to ‘Sonipat’ of that student whose name is ‘Amit’.
187
Aliasing:
Aliasing in SQL is the process of assigning a nick name or a temporary name to a table or column.
We create aliases to make queries more readable and easier to use. The alias can be created using
the ‘as’ keyword. Creating aliases doesn’t change the name of any table or column permanently.
188
Distinct clause:
The distinct clause is used to display unique values by neglecting all the duplicate values. Distinct
clause can be used for more than one column.
Here in the ‘student’ table, two duplicate IDs 1 and 3 are present. Now using distinct clauses we can
get unique values.
As we can see all duplicate IDs are removed but it is temporary. Duplicate values are not removed
and are still present in the table.
Where clause: The WHERE clause in SQL is used to filter the results of a SELECT statement by
specifying one or more conditions. All those tuples which meet the condition will be included in the
final result.
The WHERE clause is a very powerful technique to select particular rows from a table. It can be used
to filter by the values in a column, by the values in multiple columns, or by the outcome of any
calculation.
Where clause can be used with the select statement to filter the result.
Where clause can be used with an update statement to update the data of the table that
matches with the condition.
189
Where clause can be used with a delete statement to delete the rows of the table that match
with the condition.
Query: where <condition>;
Examples:
1. To filter the result based on only one condition:
190
Example of in clause: if we want to find the data of those students who live in either ‘Delhi’ or
‘Jaipur’ or ‘Gurugram’. Now to solve this problem, we have two ways. Either we write multiple
comparisons using or keyword or we can use in clause. Now you will see that using in clause for
comparing with a list of items is an easy option.
Example of not in clause: if we want to find the data of those students who don’t live in ‘Delhi’ or
‘Jaipur’ or ‘Gurugram’.
Between Clause: It is used to filter the rows in output based on the range of values.
Query: where <column name> between <starting value> and <ending value>;
Note: The final result of the between clause filters the rows of the table based on the range of
values including starting and ending values.
Order by Clause: It is used to sort the output of the select statement in ascending or descending
order.
Query: order by <column name> [ASC|DESC];
Note: If not mentioned, by default it will sort the output in ascending order. So, if you want to sort
the data in ascending order, you need not mention the order of sorting as it is the default mode of
sorting.
191
We can sort multiple columns together in ASC and DESC order.
NULL: In SQL, null is a special value which means the absence of a value or a field doesn’t have a
value. Null doesn’t mean zero. Null also doesn’t mean empty string. Null is a kind of placeholder of
that value which is not present or not known.
Example: If the phone number of a student is not known at present, we can store NULL instead of
zero or make it empty.
192
Example: To find out the names of students whose phone numbers are NULL.
Example: To find out the names of students whose phone numbers are not NULL.
Like operator: Like operator is used to match a pattern. The like operator is used with the where
clause. Like operator has 2 wildcards:
193
Example 2: To match a string that ends with ‘a’, its pattern will be ‘%a’. As we don’t know how many
characters are there before ‘a’, so ‘%’ sign is used before ’a’.
Example 3: To match a string that contains ‘a’, its pattern will be ‘%a%’. As we don’t know how
many characters are there before or after ‘a’, so ‘%’ sign is used before and after ’a’.
Example 4: To match a string that has a letter ‘a’ at the second position, its pattern will be ‘_a%’. As
we know there must be exactly one character before ‘a’ and we don’t know how many characters
are thereafter ‘a’, so the ‘_’ sign is used before ‘a’ and the ‘%’ sign is used after ’a’.
Example 5: To match a string that has exactly 5 characters, its pattern will be ‘_ _ _ _ _’. As we know
there must be exactly 5 characters, so the ‘_’ sign is used 5 times.
194
Example 6: To match a string that has exactly 7 characters and ends with ‘t’, its pattern will be ‘_ _
_ _ _ _ t’. As we know there must be exactly 7 characters, so the ‘_’ sign is used 6 times before ‘t’.
Update Command:
It is used to update the existing data in a table.
Command: update <table name> set <column name> = <new data> where <condition>;
Example 1: Let’s update the Age to 18 of that student whose name is Amit.
195
Example 2: Let’s update the city to ‘Delhi’ of that student whose ID is 1 and Age is 17.
Delete Command: It is used to delete the existing rows in a table that matches the condition.
Query: delete from <table name> where <condition>;
Example 1: Let’s delete the data of those students whose ID is 1 but whose age is not 18.
196
Example 2: Let’s delete all data from the student table. To do this, we need to give a condition that
matches all the records. As IDs are greater than 0, so let’s delete all those records where ID is greater
than 0. Note: The same can be done using the truncate command. truncate student;
197
Aggregate Functions:
Aggregate functions are those functions that operate on a list of values and return a single-digit
value or we can summarize the data using aggregate functions.
1. Max: it is used to find out the maximum value from a column.
198
5. Count: it is used to count the number of values in a column.
Note: Distinct keyword can be used with aggregate functions to find out the max, min, sum, avg,
and count of unique values.
Example: Let’s find out the total number of cities from where students came to study. Here more
than one student is from the same city. So, we need to use distinct keyword along with the count
function.
Group by clause:
The GROUP BY clause is used to group rows that have the same values into summary rows. Group
by clause is often used with aggregate functions like MAX(), MIN(), SUM(), AVG() and COUNT() to
group the result by one or more columns.
199
Query: group by <column name>
Example 1: Let’s count the number of students of having same age in the student table.
Having clause: It is used to filter the result set of group by clause in the select statement.
Note: To filter the result set of the group by clause, only having clause can be used whereas for all
other queries where clause is used.
Types of joins:
1. Cartesian product (cross join): It gives all possible combinations from more than one table.
It combines every row from one table with every row from another table. Suppose we have
200
5 rows in the first table and 4 rows in the second table then the total number of rows in the
Cartesian product of these two tables will be 20 rows.
Cardinality of the final table of Cartesian product = cardinality of the first table *
cardinality of the second table.
Example: we have two tables’ ‘student’ and ‘awards’. Let’s apply the Cartesian product to
these two tables.
2. Equi join: It joins the tables based on one common column. However, the final result will
consist of a common column from both tables.
Example: we have two tables - student and awards. Let’s apply equi join on these two tables.
Here both the tables have common column IDs. So, to avoid ambiguity (confusion), we need
to mention the table name before the column name.
201
3. Natural Join: It joins the tables based on one common column. However, the final result will
consist of a common column only once.
Example: we have two tables’ - students and awards. Let’s apply natural join on these two
tables.
Here both the tables have common column IDs. But there is no ambiguity arises on the name
of the common column.
202
Password = It should be the same as we set during MySQL installation.
Example: Let’s create a connection of Python with MySQL and test it.
Output:
Here in the above example, I had not set any database password, so, the passwd option is
not mentioned in the connection string. is_connected() function checks whether the
connection string can connect Python with MySQL or not. If the connection string can make
a connection with Python and MySQL, is_connected() returns True otherwise False.
3. Create a cursor
Cursor: It is a pointer or iterator which points towards the resultset of the SQL query.
Whenever a SQL query runs, It gives the entire result set in one go. We may not require the
entire resultset at once. So, a cursor is created and data from the entire resultset will be
fetched row by row as per our requirement.
Syntax: <cursor object> = <connection object>.cursor()
4. Execute query
Syntax: <cursor object>. execute(<SQL query string>)
203
b) fetchone(): It returns one row from the resultset in the form of a tuple. It returns None
if no more records are there. To get multiple rows, we need to run fetchone() multiple
times.
Syntax: <variable name>=<cursor>.fetchone()
c) fetchmany(): It returns n number of records from the resultset in the form of a list where
each record is in the form of a tuple. It returns an empty tuple if no more records are
there.
Syntax: <variable name>=<cursor>.fetchmany(n)
d) rowcount: It is the cursor’s property to count the number of rows in the resultset.
Syntax: <variable name>=<cursor>.rowcount
Example: Refer to the example of fetchmany()
1. Using % formatting:
Whenever we need to complete an SQL query based on user input, we write a placeholder
‘%s’ on that place.
Example: Let’s fetch all the data of the student table where age is ‘x’ and city is ‘y’. (Here,
the value of x and y will be given by the user during run time).
204
2. Using format() function:
Whenever we need to complete an SQL query based on user input, we write a placeholder
{} on that place. If we need to complete the SQL query based on multiple user inputs, we
write placeholder {}, {}, {} and so on at those places and pass user-defined values in the
format function sequentially. Here 1st values passed in the format function will be passed
to 1st {}, 2nd values passed to 2nd {}, 3rd value passed to 3rd {} and so on.
Example: Let’s fetch all the data of the student table where age is ‘x’ and city is ‘y’. (Here,
the value of x and y will be given by the user during run time).
Commit: Whenever we perform update, delete or insert query, the commit() function must be run
before closing the connection.
Syntax: <connection object>.commit()
Example 1: Insert data in the student table which will be given by the user during run time.
Data in the student table before insertion
205
Python code:
Output:
206
Example 2: Delete data of those students whose ID is given by the user during run time in the
student table.
In the previous example, after inserting a record in the student table, we have 8 records in the
student table. (Kindly refer previous example for the current state of the student table).
Python code:
Output:
207
Example 3: Update the name of those students whose name and ID are given by the user during
run time in the student table.
In the previous example, after deleting a record in the student table, we have 7 records in the
student table. (Kindly refer previous example for the current state of the student table).
Python code:
Output:
208
209
DBMS3 - MULTIPLE CHOICE QUESTIONS (MCQ)
9. Which key is used to uniquely identify a record in a table and doesn’t allow NULL values?
210
a. Alternate key c. Super key
b. Primary key d. Foreign key
11. A candidate key that is not selected as the primary key can serve as a unique identifier.
a. Alternate key c. Candidate key
b. Primary key d. Surrogate key
13. A column or set of columns in a table that refers to the primary key of another table.
a. Alternate key c. Candidate key
b. Primary key d. Foreign key
14. Which of the following SQL commands is used to view a list of all databases?
a. select databases c. view databases
b. show databases d. project databases
15. Which of the following SQL commands is used to use/select a particular database?
a. use b. select c. view d. project
16. Which SQL commands are used to define and maintain the physical structure or schema of a
table in a database like creating, altering and deleting database objects such as tables and
constraints?
a. DDL
b. DML
c. DCL
d. TCL
17. Which SQL command is used to change or modify any attribute/column like the addition or
deletion of columns in the database?
a. create
b. alter
c. delete
d. update
211
b. data
c. query
d. view
21. Which command is used to display a list of all the tables in the current database?
a. display tables;
b. show tables;
c. view tables;
d. select all tables;
22. Which command is used in the where clause to search NULL values in a particular column?
a. IS NULL
b. IN NULL
c. NOT NULL
d. IS NOT NULL
24. Which SQL function is used to determine the no. of row or non-null values?
a. min
b. max
c. count
d. sum
25. Which SQL function is used to count the entire number of rows in the database table?
a. count
b. count(*)
c. max
d. min
212
26. In a relational database, a key that establishes a link between two tables?
a. Primary key
b. Alternate key
c. Foreign key
d. Candidate key
27. A table containing data organized in the form of rows and columns in a relational data model?
a. Relation
b. View
c. Tuple
d. Database
28. Which SQL clause is used to filter the result of a SELECT statement in a Relational Database?
a. from
b. where
c. join
d. having
30. How many candidate keys can a relation/table have in a relational database
a. One
b. Two
c. Multiple
d. None
31. What is the main difference between the candidate key and the primary key?
a. A candidate key can contain a NULL value but a primary key can’t contain a NULL value
b. A primary key can contain unique value but the candidate key doesn't need to have a unique
value
c. The primary key is chosen by the designer from the available list of candidate keys.
d. No difference
32. Which DDL command is used to modify the structure of an existing table?
a. create table
b. modify table
c. alter table
d. update table
33. Which DDL command is used to remove a table along with its all content from a database?
a. DELETE TABLE
213
b. DROP TABLE
c. REMOVE TABLE
d. ERASE TABLE
34. Which constraint enforces data integrity by ensuring that a column always contains values?
a. NULL
b. NOT NULL
c. CHECK
d. DEFAULT
35. Which of the following SQL commands is used to change the sequence of attributes in a
relation?
a. modify
b. change
c. column
d. sequence
36. Which SQL clause ensures the selection of unique data from an attribute?
a. different
b. distinct
c. not null
d. prime
37. What is the main difference between CHAR and VARCHAR datatypes in SQL?
a. CHAR is case-sensitive while VARCHAR is non case sensitive
b. CHAR stores variable length strings while VARCHAR stores fixed length string
c. CHAR stores fixed length strings while VARCHAR stores variable length string
d. CHAR is used for storing numeric data while VARCHAR is used for text data
38. What is the prime purpose of unique key constraints in a relational database?
a. To ensure that values in a column are NULL
b. To ensure that values in a column are unique
c. To define the relationship between tables
d. To specify a condition that must be met for data to be valid in a column
39. Which constraint key is used when you want to enforce uniqueness but allows NULL values in
the database
a. PRIMARY KEY
b. UNIQUE KEY
c. NOT NULL
d. CHECK
214
c. ALTER
d. DELETE
41. Which keyword is used for table aliasing that involves giving a table short and alternative name
to simplify query syntax?
a. from
b. as
c. where
d. on
42. Which SQL clause is used in the database table to eliminate duplicate rows from the query
result?
a. group by
b. distinct
c. describe
d. duplicate
43. Which of the following clauses in SQL is most appropriate to use to select matching tuples in a
specific range of values?
a. IN
b. LIKE
c. BETWEEN
d. IS
44. Which of the following SQL datatype allows NULL values by default?
a. INT
b. CHAR
c. VARCHAR
d. All of the above
45. Which of the following is NOT a required argument to the connect() function?
a. Hostname
b. Username
c. Password
d. Database name
47. Which method is used to fetch n numbers of results from a SQL query?
a. fetchall()
b. fetchone()
215
c. fetchmany()
d. All of the above
48. _______ it is a pointer or iterator which points towards the resultset of the SQL query.
a. cursor
b. rset
c. temp
d. None of these
49. Which of the following is not a valid method to fetch records from a database in Python.
a. fetchmany()
b. fetchone()
c. fetchmulti()
d. fetchall()
50. To get all the records from the result set, you may use ___________.
a. cursor.fetchmany()
b. cursor.fetchall()
c. cursor.fetchone()
d. cursor.execute()
1. What is SQL?
2. Differentiate between DML and DDL. Explain with the help of examples.
3. What are the different types of SQL data type?
4. What is the difference between a where statement and a having statement in SQL?
5. What is a primary key?
6. Differentiate between a database table and a database record.
7. What is Foreign Key? And how does it relate to a database?
8. What is the Domain in a database?
9. Explain the role of the clause in a query of SQL commands.
10. What is Aliasing?
11. Explain char, varchar and int datatype in SQL with examples.
12. Differentiate between candidate key and alternate key?
13. Differentiate between degree and cardinality of a table with the help of an example.
14. What are database keys? Explain all the database keys.
15. What are the constraints in SQL?
16. Explain the wildcards used with the like operator.
17. What are joins in SQL?
18. Differentiate between Natural Join and Equi Join.
19. Explain any two aggregate functions in SQL.
20. What is a cursor?
216
21. What is the role of the commit() function in SQL?
22. What is a Cartesian product? What will be the number of rows in the output table if we apply
the Cartesian product on two tables T1 and T2 with 9 and 10 rows respectively?
23. Explain the alter table command with the help of an example.
24. Differentiate between the fetchall() function and the fetchmany() function in SQL.
25. In SQL, Define the aggregate function and write the name of the aggregate function which will
display the cardinality of a table.
1. Assertion (A): The COUNT function can work with distinct keyword.
Reason (R): The DISTINCT keyword can only be used with the COUNT function.
2. Assertion (A): The HAVING clause can only be used with a GROUP BY statement.
Reason (R): WHERE clause can be used in place of HAVING clause in GROUP BY
statement.
3. Assertion (A): The LIKE operator is used for pattern matching in the WHERE clause.
Reason (R): % and _ wildcard are used with the LIKE operator for making a pattern.
8. Assertion (A): The HAVING clause is used to filter aggregated data in SQL queries.
217
Reason (R): The HAVING clause is used to group rows with similar values in one or
more columns into result sets.
9. Assertion (A): Inner Join retrieves rows that have matching values in both tables being
joined.
Reason (R): Inner join excludes rows with no matching values
10. Assertion (A): Between operator is used to filter data within a specified range.
Reason (R): Where clause works exactly the same as between operator
1. Write a MySQL query to create the table ‘Employee’ with the following structure and constraint.
Table: Employee
2. Write a MySQL query to create the table ‘Student’ and ‘Activities’ with the following structure
and constraint.
Table: Student
Column_Name DataType(size) Constraint
Student_ID varchar(20) Primary key
Student_Name char(80) Not Null
Gender char(20) Not Null
Class varchar(30)
Age int(20) Not Null
Address Varchar(150) Unique
Phone Int(15) Not Null, Unique
Table: Activities
Column_Name DataType(size) Constraint
Student_ID varchar(20) Foreign key references to
Student_ID of Employee
218
table
Activity_Name char(80) Not Null
Position char(30) Not Null
3. Anmol maintains a database of medicines for his pharmacy using SQL to store the data.
The structure of the table PHARMA for the purpose is as follows:
● Name of the table-PHARMA
● The attributes of PHARMA are as follows:
MID - numeric
MNAME - character of size 20
PRICE - numeric
UNITS - numeric
EXPIRY – date
Table: PHARMA
(c) Anmol has received a new medicine to be added to his stock, but for which he does not know
the number of UNITS. So he decides to add the medicine without its value for UNITS. The rest of the
values are as follows:
M7 SUCRALFATE 17 2022-03-20
Write the SQL command that Anmol should execute to perform the required task.
(d) Anmol wants to change the name of the attribute UNITS to QUANTITY in the table PHARMA.
Which of the following commands will he use for the purpose?
I. UPDATE
II. DROP TABLE
219
III. CREATE TABLE
IV. ALTER TABLE
(e) Now Anmol wants to increase the PRICE of all medicines following commands will he use for the
purpose?
I. UPDATE SET
II. INCREASE BY
III. ALTER TABLE
IV. INSERT INTO
A cursor named Cur is created in Python for a connection of a host which contains the database
TRAVEL. Write the output for the execution of the following Python statements for the above
SQL Table PASSENGERS:
Cur.execute(‘USE TRAVEL’)
Cur.execute(‘SELECT * FROM PASSENGERS’)
Recs=Cur.fetchall()
For R in Recs:
Print(R[1])
5. Write SQL statements for the following queries (i) to (v) based on the relations CUSTOMER and
TRANSACTION given below:
Table: CUSTOMER
C1 RISHABH M 15000
C2 AAKASH M 12500
C3 INDIRA F 9750
C4 TUSHAR M 14600
C5 ANKITA F 22000
Table: TRANSACTION
220
C5 2019-12-31 1500 CREDIT
1. To display all information about the CUSTOMERS whose NAME starts with 'A'.
2. To display the NAME and BALANCE of Female CUSTOMERS (with GENDER as 'F') whose
TRANSACTION Date (TDATE) is in the year 2019.
3. To display the total number of CUSTOMERS for each GENDER.
4. To display the CUSTOMER NAME and BALANCE in ascending order of GENDER.
5. To display CUSTOMER NAME and their respective INTEREST for all CUSTOMERS where
INTEREST is calculated as 8% of BALANCE.
6. The IT Company XYZ has asked their IT manager Ms. Preeti to maintain the data of all the
employees in two tables EMPLOYEE and DEPT. Ms. Preeti has created two tables EMPLOYEE and
DEPT. She entered 6 rows in the ‘EMPLOYEE’ table and 5 rows in the ‘DEPT’ table.
Table: DEPT
D_CODE D_NAME CITY
D001 INFRASTRUCTURE DELHI
D002 MARKETING DELHI
D003 MEDIA MUMBAI
D005 FINANCE KOLKATA
D004 HUMAN RESOURCE MUMBAI
Table: EMPLOYEE
E_NO NAME DOJ DOB GENDE D_CODE Salary
R
1001 Vinay 2013-09- 1991-09- MALE D001 250000
02 01
1002 Ruby 2012-12- 1990-12- FEMALE D003 270000
11 15
1003 Anuj 2013-02- 1987-09- MALE D005 240000
03 04
1007 Sunny 2014-01- 1988-10- MALE D004 250000
17 19
1004 Rohit 2012-12- 1986-11- MALE D001 270000
09 14
1005 Preeti 2013-11- 1989-03- FEMALE D002 NULL
18 31
Note: DOJ refers to the date of joining and DOB refers to the date of Birth of employees.
Based on the above data, answer the following questions:
1. Identify the column which can be considered as the primary key in the ‘EMPLOYEE’ table.
221
2. Identify the column which can be considered as primary key in the DEPT table
3. What is the degree and cardinality of the’ EMPLOYEE’ table?
4. What is the degree and cardinality of the’ DEPT’ table?
5. Write SQL queries for the following:
1) Insert two new rows in the Employee table with the following data:
1006 Rahul 2019-11-06 1992-01-04 MALE D003 156000
2) To display E_NO, NAME, GENDER from the table EMPLOYEE in descending order of E_NO.
3) To display the NAME of all the ‘FEMALE’ employees from the table EMPLOYEE.
4) To display the E_NO and NAME of those employees from the table EMPLOYEE who are
born between ‘1987- 01-01’ and ‘1991-12-01’.
5) To display the NAME and CITY of those employees whose DEPARTMENT is either ‘MEDIA’
or ‘FINANCE’.
6) To display the NAME of those employees whose name starts with the letter ‘R’.
7) To display the ‘NAME’ of those employees whose name contains the letter ‘n’.
8) To display the ‘NAME’ of those employees whose name has exactly 5 letters.
9) To display D_NAME and CITY from table DEPT where D_NAME ends with the letter ‘G’ and
CITY is ‘DELHI’.
10) To display the maximum SALARY of the ‘EMPLOYEE’ table.
11) To delete data of all those employees whose age is less than 25.
12) To update SALARY to 230000 of those employees whose ‘E_NO’ is 1004.
13) To change the sequence of the DOB column in the employee table and move it before the
DOJ column.
14) To add a new column MOBILE int(20) before column SALARY in the employee table.
15) To set SALARY to 300000 of all those employees whose age is NULL.
16) To Increase the salary of all employees by 30000 in the EMPLOYEE table.
17) To display the average SALARY of the EMPLOYEE table.
18) To display the names of employees who have a SALARY of more than 200000 in ascending
order of NAME.
19) To display department-wise average salary of employees.
20) To display the total number of departments in XYZ company.
21) To delete data of all the employees whose D_CODE is not ‘D001’.
22) To display E_NO, NAME and SALARY of all those employees who don’t live in ‘DELHI’.
23) To change column name CITY to D_CITY in the DEPT table.
24) To delete the EMPLOYEE table.
25) To delete the ‘D_NAME’ column from the DEPT table.
7. A garment store is considering maintaining its inventory using SQL to store the data. as a
database administrator, Mr.Rohit has decided that:
● Name of the database – STORE
● Name of the table – GARMENT
● The attributes of GARMENT table are as follows:
▪ GCODE – numeric
▪ DESCRIPTION – character of size 50
▪ PRICE – numeric
▪ FCODE – varchar of size 10
222
Table: GARMENT
GCODE DESCRIPTION PRICE FCODE
8. Write the output of the following SQL queries based on table TRANSACTION given below:
Table: TRANSACTION
223
1 11 5000 CREDIT 2019-10-11 SUCCESS
Table: COMPANY
1 15 SBI
3 50 ICICI
4 34 HDFC
9. The code given below reads the records from the table employee and displays only those
records of employee table who don’t live in the city 'Delhi':
E_ID – varchar(50)
E_Name – char(50)
Salary – int(15)
City – char(20)
Note the following to establish connectivity between Python and MySQL:
Username is root
224
Password is 12345
The table exists in a MySQL database named company.
The table has four attributes (E_ID, E_Name, Salary, City).
10. The code given below deletes the records from the table employee which contains the
following record structure:
E_ID – varchar(50)
E_Name – char(50)
Salary – int(15)
City – char(20)
Note the following to establish connectivity between Python and MySQL:
Username is root
Password is 12345
The table exists in a MySQL database named company.
The table has four attributes (E_ID, E_Name, Salary, City).
225
__________________ #Statement 5
print(‘Data deleted’)
11. Write a Python program to delete all the tuples from the Student table whose age>14.
Note the following to establish connectivity between Python and MySQL:
Username is root
Password is 12345
The table exists in a MySQL database named School.
The table has five attributes (Stu_ID, Stu_Name, age, Address)
12. Write a Python program to insert 5 records in the Employee table. Take these 5 records as input
from the user (One record at a time).
Note the following to establish connectivity between Python and MySQL:
Username is root
Password is 12345
The table exists in a MySQL database named company.
The table has five attributes (Emp_ID, Emp_Name, DOJ, Gender, Salary)
13. Write a Python program to update the name of an employee in the Employee table whose
employee ID is ‘E1001’ (Take updated name as input from the user).
Note the following to establish connectivity between Python and MySQL:
Username is root
Password is 12345
The table exists in a MySQL database named company.
The table has five attributes (Emp_ID, Emp_Name, DOJ, Gender, Salary)
226
Class: XII Session: 2023-24
Computer Science (083)
Sample Question Paper (Theory)
Time allowed: 3 Hours Maximum Marks: 70
General Instructions:
Please check this question paper contains 35 questions.
The paper is divided into 4 Sections- A, B, C, D and E.
Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
[1]
227
Options:
a. PYTHON-IS-Fun
b. PYTHON-is-Fun
c. Python-is-fun
d. PYTHON-Is -Fun
5 In MYSQL database, if a table, Alpha has degree 5 and cardinality 3, and 1
another table, Beta has degree 3 and cardinality 5, what will be the degree
and cardinality of the Cartesian product of Alpha and Beta?
a. 5,3 b. 8,15
c. 3,5 d. 15,8
6 Riya wants to transfer pictures from her mobile phone to her laptop. She 1
uses Bluetooth Technology to connect two devices. Which type of network
will be formed in this case?
a. PAN b. LAN
c. MAN d. WAN
7 Which of the following will delete key-value pair for key = “Red” from a 1
dictionary D1?
a. delete D1("Red")
b. del D1["Red"]
c. del.D1["Red"]
d. D1.del["Red"]
8 Consider the statements given below and then choose the correct output 1
from the given options:
pride="#G20 Presidency"
print(pride[-2:2:-2])
[2]
228
Options:
a. ndsr
b. ceieP0
c. ceieP
d. yndsr
Options:
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4
Options:
a.
[3]
229
RED*
WHITE*
BLACK*
b.
WHITE*
BLACK*
c.
WHITE* WHITE*
BLACK* BLACK*
d.
YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*
[4]
230
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
[5]
231
(c) A is True but R is False
(d) A is false but R is True
17 Assertion(A): List is an immutable data type 1
Reasoning(R): When an attempt is made to update the value of an
immutable variable, the old variable is destroyed and a new variable is
created by the same name in memory.
18 Assertion(A): Python Standard Library consists of various modules. 1
Reasoning(R): A function in a module is used to simplify the code and
avoids repetition.
SECTION B
19 (i) Expand the following terms: 1+1=
2
POP3 , URL
(ii) Give one difference between XML and HTML.
OR
(i) Define the term bandwidth with respect to networks.
(ii) How is http different from https?
20 The code given below accepts a number as an argument and returns the 2
reverse number. Observe the following code carefully and rewrite it after
removing all syntax and logical errors. Underline all the corrections made.
[6]
232
21 Write a function countNow(PLACES) in Python, that takes the 2
dictionary, PLACES as an argument and displays the names (in
uppercase)of the places whose names are longer than 5 characters.
For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New
York",5:"Doha"}
The output should be:
LONDON
NEW YORK
OR
Write a function, lenWords(STRING), that takes a string as an argument
and returns a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the
tuple will have (4, 3, 2, 4, 4, 3)
22 Predict the output of the following code: 2
23 Write the Python statement for each of the following tasks using BUILT-IN 1+1=
2
functions/methods only:
(i) To insert an element 200 at the third position, in the list L1.
(ii) To check whether a string named, message ends with a full stop
/ period or not.
[7]
233
OR
A list named studentAge stores age of students of a class. Write the
Python command to import the required module and (using built-in
function) to display the most common age value from the given list.
24 Ms. Shalini has just created a table named “Employee” containing 2
columns Ename, Department and Salary.
After creating the table, she realized that she has forgotten to add a primary
key column in the table. Help her in writing an SQL command to add a
primary key column EmpId of integer type to the table Employee.
Thereafter, write the command to insert the following record in the table:
EmpId- 999
Ename- Shweta
Department: Production
Salary: 26900
OR
[8]
234
SECTION C
26 Predict the output of the Python code given below: 3
27 Consider the table CLUB given below and write the output of the SQL 1*3=
3
queries that follow.
[9]
235
4687 SHYAM 37 MALE CRICKET 1300 2004-
04-15
1245 MEENA 23 FEMALE VOLLEYBALL 1000 2007-
06-18
1622 AMRIT 28 MALE KARATE 1000 2007-
09-05
1256 AMINA 36 FEMALE CHESS 1100 2003-
08-15
1720 MANJU 33 FEMALE KARATE 1250 2004-
04-10
2321 VIRAT 35 MALE CRICKET 1050 2005-
04-30
[10]
236
P02 Kashish Clerk NULL 1600
P03 Mahesh Superviser 48000 NULL
Based on the given table, write SQL queries for the following:
(i) Increase the salary by 5% of personals whose allowance is known.
(ii) Display Name and Total Salary (sum of Salary and Allowance) of
all personals. The column heading ‘Total Salary’ should also be
displayed.
(iii) Delete the record of personals who have salary greater than 25000
30 A list, NList contains following record as list elements: 3
[City, Country, distance from Delhi]
Each of these records are nested together to form a nested list. Write the
following user defined functions in Python to perform the specified
operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an
argument and pushes a list object containing name of the city and
country, which are not in India and distance is less than 3500 km
from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays
them. Also, the function should display “Stack Empty” when there
are no elements in the stack.
For example: If the nested list contains the following data:
NList=[["New York", "U.S.A.", 11734],
["Naypyidaw", "Myanmar", 3219],
["Dubai", "UAE", 2194],
["London", "England", 6693],
[11]
237
["Gangtok", "India", 1580],
["Columbo", "Sri Lanka", 3405]]
The stack should contain:
['Naypyidaw', 'Myanmar'],
['Dubai', 'UAE'],
['Columbo', 'Sri Lanka']
The output should be:
['Columbo', 'Sri Lanka']
['Dubai', 'UAE']
['Naypyidaw', 'Myanmar']
Stack Empty
SECTION D
31 Consider the tables PRODUCT and BRAND given below: 1*4=
4
Table: PRODUCT
PCode PName UPrice Rating BID
P01 Shampoo 120 6 M03
P02 Toothpaste 54 8 M02
P03 Soap 25 7 M03
P04 Toothpaste 65 4 M04
P05 Soap 38 5 M05
P06 Shampoo 245 6 M05
Table: BRAND
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
[12]
238
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT
and BRAND.
(ii) Display the structure of the table PRODUCT.
(iii) Display the average rating of Medimix and Dove brands
(iv) Display the name, price, and rating of products in descending order
of rating.
32 Vedansh is a Python programmer working in a school. For the Annual 4
Sports Event, he has created a csv file named Result.csv, to store the
results of students in different sports events. The structure of Result.csv
is :
[St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost'
or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the
following user defined functions:
Accept() – to accept a record from the user and add it to the file
Result.csv. The column headings should also be added on top of the csv
file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
SECTION E
[13]
239
33 Meticulous EduServe is an educational organization. It is planning to setup 1*5=
5
its India campus at Chennai with its head office at Delhi. The Chennai campus
has 4 main buildings – ADMIN, ENGINEERING, BUSINESS and MEDIA
a) Suggest and draw the cable layout to efficiently connect various blocks of
buildings within the CHENNAI campus for connecting the digital devices.
[14]
240
b) Which network device will be used to connect computers in each block to
form a local area network?
c) Which block, in Chennai Campus should be made the server? Justify your
answer.
d) Which fast and very effective wireless transmission medium
should preferably be used to connect the head office at DELHI with the
campus in CHENNAI?
e) Is there a requirement of a repeater in the given cable layout? Why/
Why not?
34 (i) Differentiate between r+ and w+ file modes in Python. 2+3=
5
(ii) Consider a file, SPORT.DAT, containing records of the following
structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file
SPORT.DAT and copies the records with Sport name as “Basket Ball”
to the file named BASKET.DAT. The function should return the total
number of records copied to the file BASKET.DAT.
OR
(i) How are text files different from binary files?
(ii) A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME, MTYPE]}
Where
MNO – Movie Number
MNAME – Movie Name
MTYPE is Movie Type
Write a user defined function, findType(mtype), that accepts mtype
as parameter and displays all the records from the binary file
CINEMA.DAT, that have the value of Movie Type as mtype.
35 (i) Define the term Domain with respect to RDBMS. Give one example 1+4=
5
to support your answer.
[15]
241
(ii) Kabir wants to write a program in Python to insert the following record
in the table named Student in MYSQL database, SCHOOL:
rno(Roll number )- integer
name(Name) - string
DOB (Date of birth) – Date
Fee – float
Note the following to establish connectivity between Python and
MySQL:
Username - root
Password - tiger
Host - localhost
The values of fields rno, name, DOB and fee has to be accepted from
the user. Help Kabir to write the program in Python.
OR
(i) Give one difference between alternate key and candidate key.
[16]
242
Sartaj, now wants to display the records of students whose fee is more than
5000. Help Sartaj to write the program in Python.
[17]
243
Class XII
Marking Scheme
SECTION A
1 False 1 mark for 1
correct
answer
[1]
244
ceieP0
BLACK*
[2]
245
18 Option b 1 mark for 1
correct
Both A and R are true but R is not the correct explanation for A answer
SECTION B
19 (i) ½ mark for 1+1=2
each correct
POP3 – Post Office Protocol 3 expansion
(ii)
(i) Bandwidth is the maximum rate of data transfer over 1 mark for
correct
a given transmission medium. / The amount of definition
information that can be transmitted over a network.
[3]
246
(ii) https (Hyper Text Transfer Protocol Secure) is the 1 mark for
correct
protocol that uses SSL (Secure Socket Layer) to
difference.
encrypt data being transmitted over the Internet.
Therefore, https helps in secure browsing while http
does not.
21 ½ mark for 2
correct
function
header
½ mark for
correct loop
½ mark for
correct if
statement
½ mark for
displaying
OR
the output
½ mark for
correct
function
header
½ mark for
using split()
[4]
247
½ mark for
adding to
tuple
½ mark for
return
statement
OR
import statistics
1 mark for
print( statistics.mode(studentAge) )
correct
import
statement
1 mark for
correct
command
with mode()
and print()
[5]
248
As the primary key is added as the last field, the command for
inserting data will be: 1 mark for
correct
INSERT INTO Employee INSERT
VALUES("Shweta","Production",26900,999); command
Alternative answer:
INSERT INTO
Employee(EmpId,Ename,Department,Salary)
VALUES(999,"Shweta","Production",26900);
OR
To delete the attribute, category:
1 mark for
ALTER TABLE Sports correct
DROP category; ALTER TABLE
command
with DROP
To add the attribute, TypeSport
1 mark for
correct
ALTER TABLE Sports ALTER TABLE
command
ADD TypeSport char(10) NOT NULL; with ADD
SECTION C
26 ND-*34 ½ mark for 3
each correct
character
27
[6]
249
4
(ii)
CNAME SPORTS
AMINA CHESS
(iii)
CNAME AGE PAY
AMRIT 28 1000
VIRAT 35 1050
28 1 mark for 3
correctly
opening and
closing files
½ mark for
correctly
reading data
1 mark for
correct loop
and if
statement
OR
½ mark for
displaying
data
1 mark for
correctly
opening and
closing the
files
[7]
250
½ mark for
correctly
reading data
1 mark for
correct loop
and if
statement
½ mark for
displaying
the output.
(ii)
SELECT Name, Salary + Allowance AS
"Total Salary" FROM Personal;
(iii)
DELETE FROM Personal
WHERE Salary>25000
[8]
251
30 1 ½ marks for 3
each function
SECTION D
31 (i) 1 mark for 1*4=4
each correct
SELECT PName, BName FROM PRODUCT P,
query
BRAND B WHERE P.BID=B.BID;
(ii)
DESC PRODUCT;
(iii)
SELECT BName, AVG(Rating) FROM PRODUCT
P, BRAND B
WHERE P.BID=B.BID
GROUP BY BName
HAVING BName='Medimix' OR
BName='Dove';
(iv)
SELECT PName, UPrice, Rating
FROM PRODUCT
ORDER BY Rating DESC;
[9]
252
32 ½ mark for 4
accepting
data
correctly
½ mark for
opening and
closing file
½ mark for
writing
headings
½ mark for
writing row
½ mark for
opening and
closing file
½ mark for
reader object
½ mark for
print heading
½ mark for
printing data
SECTION E
33 a) 1 mark for 1*5=5
each correct
Bus Topology
answer
ENGINEERING
Admin
BUSINESS
MEDIA
[10]
253
b) Switch
c) Admin block, as it has maximum number of computers.
d) Microwave
e) No, a repeater is not required in the given cable layout as the
length of transmission medium between any two blocks does not
exceed 70 m.
½ mark for
correct try
and except
block
½ mark for
correct loop
1 mark for
correctly
copying data
[11]
254
½ mark for
correct
return
statement
½ mark for
correctly
opening and
closing files
½ mark for
correct try
and except
block
½ mark for
correct loop
½ mark for
OR correct if
(i) Text files: statement
Binary Files
Extension is .dat
Data is stored in binary form (0s and 1s), that is not
human readable.
(ii)
[12]
255
Note: Any other correct logic may be marked
35 (i) Domain is a set of values from which an attribute can ½ mark for 1+4=5
correct
take value in each row. For example, roll no field can
definition
have only integer values and so its domain is a set of
½ mark for
integer values correct
example
(ii)
½ mark for
importing
correct
module
1 mark for
correct
connect()
½ mark for
correctly
accepting the
input
Note: Any other correct logic may be marked
1 ½ mark for
correctly
[13]
256
executing the
query
½ mark for
correctly
using
OR commit()
½ mark for
importing
correct
module
1 mark for
correct
connect()
1 mark for
correctly
executing
the query
½ mark for
correctly
using
fetchall()
1 mark for
correctly
[14]
257
displaying
data
[15]
258
CLASS: XII SESSION: 2023-24
General Instructions:
4. _______ error occurs when an identifier used in the expression does not find its value 1
during run time.
a. ValueError
b. TypeError
c. NameError
d. IdentifierError
259
6. Physical or logical arrangement of network refers to as: 1
a. Routing
b. Looping
c. Topology
d. Networking
T= min(1,6,0,-3,100)
(a) 1
(b) -3
(c) 0
(d) None of above
260
b. It disables writing but enables reading operations.
c. It enables reading followed by writing operations.
d. None of the above
16. Which of the following function is used with the csv modules in Python to read the content of a 1
csv file into an object?
a. readrow() b. readrows() c. reader() d. load()
Q17 and 18 are ASSERTION (A) and REASONING (R) based questions. Mark the
correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False.
(d) A is false but R is True
17. Assertion (A): The key concept of data structure is to manage the storage of data in the memory 1
efficiently.
Reason (R): The data structure is a way to create a logical structure in the memory so that the
storage of numerous data values could be managed using minimum space. It helps in a fast
accessing of data during execution of a program.
18. Assertion(A): Every open file maintains a file-pointer and keeps track of its position after every 1
operation.
Reason (R): Every read and write operation takes place at the current position of the file pointer.
SECTION B
OR
261
Sum of Odd numbers:87
OR
Predict the output for the following code:
L1 = [10,20,30]
L2 = [110, 220, 330]
L3 = L1+L2
L4 = L3[0:4]
print(L4)
L4[0] = L4[0]*10
L4[2] = L4[1]*5
L4[1] = L4[2]
L4[3] = L4[3] - 10
print(L4)
SECTION C
Table: CITY
FIELD NAME DATA TYPE REMARKS
CityCode CHAR(5) Primary Key
CityName VARCHAR(20)
Size Integer
AvgTemp Integer
PollutionRate Integer
Population Integer
27. Write a function in Python with function call to count the number of lines in a text file 3
‘Detail.txt’ which is starting with alphabet ‘T’.
OR
Write a function in Python with function call to read the text file “Data.txt” and count
the number of times ‘my’ occurs in the file.
28. a. What is meant by pickling and unpickling of files in Python? 1+1+1
b. Difference between r+ and w+ modes of text files?
262
c. Name the modules required for working on text files, binary files and csv files in
Python.
29. 1. Expand the following: SMTP, XML 1+1+1
2. Out of the following, which is the fastest wired and wireless mediumof transmission?
30. Write a program in Python to implement a stack for these book details: (bookno, 3
bookname), i.e. Each node of the stack should contain two information about a book, book
number and book name. Also provide the option for user if he/she wants to view all
records of stack or only last added record.
SECTION D
31. Ashok is a Python programmer who has written a code and created a binary file 4
‘emp.dat’ with employee id, name and salary. The file contains 10 records. He wants to
update a record based on the employee id entered by user and update the salary. The
updated record is then to be written in the file ‘temp.dat’ along with the records which
are not to be updated. An appropriate message is displayed if employee id is not found.
As a programmer, help him to complete the following code:
import _____________ #Statement 1
def update_data():
rec={}
f = open (“emp.dat”, “rb”)
t = open (“______________”) #Statement 2
found = false
emp_id = int(input(“Enter employee id to update record : “))
while True:
try:
rec = _____________________ #Statement 3
if rec [“Employee_id”] == emp_id:
found= True
rec[“Salary”] = int(input(“Enter new Salary:”))
pickle._________________ #Statement 4
else:
pickle.dump(rec,t)
except:
break
if found == True:
print(“The salary is updated.”)
else:
print(“Employee id not found!!”)
f.close()
t.close()
1. Which module should be imported in the program? (Statement 1)
2. Write the correct statement required to open a temporary file named ‘temp.dat’.
(Statement 2)
3. Which statement should Ashok fill in Statement 3 to read the data from the binary
file?
4. Write appropriate code to update data in the file. (Statement 4)
263
32. Write a program in Python to get student details (Rollno, Name and marks) for multiple 4
students from the user and create a CSV file by writing all the student details in one go.
Also read and display the data of CSV file.
SECTION E
33. Happy Faces Corporation has set up its new centre at Noida, Uttar Pradesh for its 5
office and web-based activities. It has 4 blocks ofbuildings.
Block B
Block A
Block D
Block C
264
a. 6 b. 8 c. 18 d. None of these
3. The output for statement len(L[1]) will be:
a. 1 b. 3 c. Exception d. Syntax Error
4. print(L[:2] will generate value:
a. [4] b. [4,7] c. [4,7,[2,5.7,9.6]] d. Error
5. L.append[4,5,6] will generate output:
a. Error
b. Append a sublist [4,5,6] into L
c. Append three elements in list 4, 5 and 6
d. None of these
OR
Read the following passage and answer the questions that follows:
Lists are the container which store the heterogeneous elements of any type like integer,
character or floating point that store in square brackets[].
Consider the following list for Python:
D = [“Raja”, 4.87, ‘Delhi’, ‘Kerala’, [23, 7.56, ‘Neha’], 98]
What will the following statements do as per above definition of D:
1. D [4][-3]
2. len( D[3])
3. d [2] = 54
4. print (D[0] + D[1])
5. print (D[1:5:3]
35. Ami has joined as teaching assistant. She is working with data files using Python. She is 5
currently working on the following incomplete code:
Color= [‘Red’, ‘Orange’, ‘Crimson’, ‘Magenta’, ‘Fuschia’, ‘Blue’, ‘Black’]
def LenColors(_______,______): #Statement 1
with _____________________: #Statement 2
for c in Color:
________________________: #Statement 3
__________________________ #Statement 4
Fname =’Colors.txt’
N = int(input(“Enter a number (between 3 to 7): “))
__________________________ #Statement 5
FILE = open(Fname)
print(File.read())
265
Atif won a junior programming contest and as a prize, he is attending a Python
workshop. In one of his assignments, he has been given a text file namely Demo.txt as
shown below:
The total turnover of the bamboo sector in the state has increased from the base
levels of Rs 27.90 crores in 2006-07.
The turnover was 83.7 crore during the FY 2015-16 which has increased to over Rs. 93.53
cr during 2016-17.
#tripura #bamboo #mission
[email protected]
Atif has been asked to complete the following code as per the instructions below:
F = ___________ #Statement 1
Ch = “ ” #initially stored a space
Dcount = 0
Ccount = 0
While Ch:
_______________________ #Statement 2
If __________________________: #Statement 3
_______________________ #Statement 4
_______________________: #Statement 5
________________________ #Stataement 6
print(“Count 1: “,Dcount)
print(“Count 2: “,Ccount)
F.close()
Help him complete the code as per instruction given below:
a. Complete Statement 1 so that the given file is opened for reading.
b. Complete Statement 2 so that one character is read from the open file into the
variable Ch.
c. Complete code for Statement 3 and Statement 4 so that it counts number of
digits in the file, and stores the count in the variable Dcount.
d. Complete code for Statement 5 and Statement 6 so that it counts number of
these special characters ‘@’,’#’ and ‘-‘, in the variable Ccount.
After completing code, what will be the output of produced by the code
266
CLASS: XII SESSION: 2023-24
General Instructions:
Please check this question paper contains 35 questions.
The paper is divided into 5 Sections- A, B, C, D and E.
Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
All programming questions are to be answered using Python Language only.
Q No Question Marks
Section A
1 State True or False: 1
CSV file is also known as delimited text file which can be opened in
Notepad and Spreadsheet both.
2 The query to display all the tables stored in a database is: 1
a. Display Tables;
b. Show Tables;
c. All Tables;
d. Show tables in <database name>;
3 Consider the following expression: 1
True or not False and False and not True
Which of the following will be correct output if the given expression is
evaluated?
True b. False c. None d. Null
4 ____________ function splits the given string based on delimiter and 1
store the result in the form of list.
partition() b. split() c. divide() d. clear()
5 In a table there can be more than one attribute which contains unique 1
values. These columns are known as _________________
Primary Key b. Alternate Key c. Candidate Key
6 1
A device that amplifies a signal being transmitted on the network is
known as:
267
Modem b. Repeater c. Hub d. Switch
7 Write the output of the code given below: 1
dict = {"stname": "Ajay", "age": 17}
dict['age'] = 27
dict['address'] = "Bikaner"
print(dict)
8 Find the output of the following code 1
number= [1,5,7,0,4]
print(number[2:3])
(a) [5]
(b) [7]
(c) [7,0]
(d) None of above
9 1
What is output of following code segment
T= min(1,6,0,-3,100)
(a) 1
(b) -3
(c) 0
(d) None of above
10 What is the purpose of the random module? 1
a.) To generate random numbers for cryptography.
b.) To generate random numbers for statistical analysis
c.) To generate random numbers for various applications.
To generate truly random numbers for secure applications.
11 The internet facility that facilitates remote login is: 1
HTTP b. FTP c. TELNET d. LAN
12 A ____________ is a block of organized and reusable code. 1
a. Parameter b. Argument c. Definition d.
Function
13 When will the else part of try-except-else be executed? 1
a. Always
b. When an exception occurs
c. When no exception occurs
When an exception occurs in to except block
14 Which of the following is not an aggregate function? 1
AVG b. MAX c. JOIN d. COUNT
15 Which of the following transmission media has the highest bandwidth? 1
a. Co-axial cable
b. Fiber optic cable
c. Twisted pair cable
d. None of these
268
16 Which of the following function is used with the csv modules in Python 1
to read the content of a csv file into an object?
readrow() b. readrows() c. reader() d. load()
Q17 and 18 are ASSERTION (A) and REASONING (R) 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.
A is false but R is True
17 Assertion: The order of execution of the statements in a program is 1
known as flow of control.
Reason: The flow of control can be implemented using control
structures.
18 Assertion: Keyword arguments are related to the function calls. 1
Reason: When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
Section B
19 Name the protocol: 2
1. Used to transfer voice using packet switched network.
Used for chatting between two groups or between two individuals
20 What will be the output of the following code? 2
def Func1(x):
try:
print(5/x)
except:
print(“Error…”)
21 What is the difference between parameters and arguments? 2
22 Define Stack. Give any two applications of Stacks 2
23 Write a Python function that takes two lists and returns True if they 2
have at least one common member.
24 Write the code in Python to create a table Student in database School 2
with following fields:
Fields Datatype
Student_id varchar(6)
S_name varchar(20)
Class int(4)
Section char(2)
25 What will be the output of the following program? 2
a. def INCREASE(x):
a=a+x
return
a = 15
269
b = 10
increase(b)
print(a)
b. z = 1
def FUNC():
z = 10
print(z)
Section C
26 How can we import a module in Python? What are the possible 3
outcomes(s) executed from the following code? Also specify the
maximum and minimum values that can be assigned to variable
FLOWER.
FLOWER = random.randint(0,3)
NAME = [“Rose”, “Lily”, “Tulip”, “Marigold”]
for x in NAME:
for y in range (1, FLOWER):
print(x, end= “ ”)
print()
27 Write the output of the queries (a) to (c) based on the table, Furniture 3
given below.
FID Name Dt_of_Purchase Cost Disc.
B001 Double Bed 03-Jan-2018 45000 10
T010 Dinning Tabel 10-Mar-2020 51000 5
B004 Single Bed 19-Jul-2016 22000 0
C003 Long Back 30-Dec-2016 12000 3
Chair
T006 Console Table 17-Nov-2019 15000 12
B006 Bunk Bed 01-Jan-2021 28000 14
i.) SELECT SUM(DISCOUNT) FROM FURNITURE WHERE COST >
15000;
ii.) SELECT MAX(Dt_of_Purchase) FROM FURNITURE;
iii.) SELECT * FROM FURNITURE WHERE DISCOUNT > 5 AND FID
LIKE “T%”;
28 Write a program that uses a function which takes to string arguments 3
and returns the string comparison result of the two passed strings.
29 Consider the table Personal given below: 3
270
P04 Salil Clerk 31000 1900
P05 Ravina Supervisor NULl 2100
Based on the given table, write SQL queries for the following:
a. Increase the salary by 10% of persons whose allowance is given.
b. Display Name and Total salary (sun of salary and allowance) of
all persons. The column heading ‘TOTAL SALARY’ should also be
displayed.
c. Delete the record of Supervisors who have salary greater than
25000.
30 A list, NList, contains following record as list elements: 3
Each of these records are nested together to form a nested list. Write the
following user defined functions in Python to perform the specified
operations on the stack named travel.
i. Push_element(NList): It takes the nested list as an
argument and pushes a list object containing name of the city
and country, which are not in India and distance is less than
3500 km from Delhi.
ii. Pop_element(): It pops the objects from the stack and
displays them. Also, the
function should display “Stack Empty” when there are no
elements in the stack.
Section D
31 Anmol maintain that database of medicines for his pharmacy using SQL 4
to store the data.
The structure of the table PHARMA for the purpose is as follows:
Name of the table-PHARMA
The attributes of PHARMA are as follows:
MID - numeric
MNAME - character of size 20
PRICE - numeric
UNITS - numeric
EXPIRY – date
Table: PHARMA
MID MNAME PRICE UNITS EXPIRY
271
M3 METFORMIN 14 150 2022-05-23
M7 SUCRALFATE 17 2022-03-20
Write the SQL command which Anmol should execute to perform the
required task.
(c) Anmol wants to change the name of the attribute UNITS to QUANTITY
in the table PHARMA. Which of the following commands will he use for
the purpose?
I. UPDATE
II. DROP TABLE
III. CREATE TABLE
IV. ALTER TABLE
(d) Now Anmol wants to increase the PRICE of all medicines following
commands will he use for the purpose?
32 Write a program in Python to get student details (Rollno, Name and 4
marks) for multiple students from the user and create a CSV file by
writing all the student details in one go. Also read and display the data
of CSV file.
Section E
33 VishInternational Inc. is planning to connect its Bengaluru office setup 5
with its Head Office inDelhi. The Bengaluru Office G.R.K. International
Inc. is spread across an area of approx. 1 Square Killometer, consisting of
3 blocks : Human Resource, Academic and Administration.
You as a network expert have to suggest answers to the five quaries (i)
to (v) raised by them.
272
Mumbai Head
Office
Human Resources
Academics Administration
Human Resources 55
Administration 60
Academics 200
(i) Suggest the network type (out of LAN, MAN, WAN) for connecting
each of the following set of their Offices:
Mumbai Head office and Administration Office
Human Resources Office and Academics office
ii) Which device will you suggest to be procured by the company for
connecting all thecomputers within each of their offices out of the
following devices?
MODEM (b) Switch/Hub (c) Repeater
iii) Suggest a cable /wiring layout among the various blocks within the
Delhi OfficeSetup for connecting the Blocks.
iv) Suggest the most suitable in the Delhi Office Setup, to host the
Server. Give a suitable reason with your suggestion.
v) Suggest the most suitable media to provide secure, fast and reliable
data connectivity between Mumbai Head Office and the Delhi Office
273
Setup.
34 Write any two differences between text and binary files. 5
Write a program in python with function LineRead(), which reads the
contents of a text file “Memory.txt” and displays those lines from the
file which have at least 10 words in it.
For example, if the content of “Memory.txt” is as follows:
Five cows lived in a little forest.
They ate fresh grass in a large green meadow.
They were kind friends.
They decided to do everything together, so the lions couldn’t attack
them for food.
One day, five cows fought and each one started to eat grass in a
different place.
The lions decided to seize the opportunity and killed them one by one.
Then the output should be,
They decided to do everything together, so the lions couldn’t attack
them for food.
One day, five cows fought and each one started to eat grass in a
different place.
The lions decided to seize the opportunity and killed them one by one.
OR
Can a function return multiple values? If yes then explain with suitable
example.
A Binary file Book.dat has structure [BookNo, BookName, Author].
1. Write a user defined function FileData() to input data for a
record and add to book.dat.
Write a function CountData(Author) in Python which accepts the
AuthorName as parameter and count and return number of books by
the given author are stored in the binary file Book.dat.
35 Consider the following DEPT and EMPLOYEE tables. 5
Table: DEPT
D_CODE D_NAME CITY
274
Table: EMPLOYEE
E_NO NAME DOJ DOB GENDER D_CODE AGE
Note: DOJ refers to date of joining and DOB refers to date of Birth of
employees.
Write SQL queries for the following:
a. To display D_NAME and CITY from table DEPT where D_NAME ends
with letter ‘G’ and CITY is ‘DELHI’.
b. To delete data of all those employees whose age is less than 25.
c. To update AGE to 23 of those employee whose E_NO is 1004.
d. To change the sequence of DOB column in employee table and
move it before DOJ
column.
e. To add a new column MOBILE int(20) before column AGE in
employee table.
275
Series HEFG/C Set-4
Q.P. Code 91
Roll No.
$*
General Instructions :
This question paper contains five sections, Section A to E.
All questions are compulsory.
Section A has 18 questions carrying 1 mark each.
Section B has 7 Very Short Answer (VSA) type questions carrying 2 marks each.
Section C has 5 Short Answer (SA) type questions carrying 3 marks each.
Section D has 3 Long Answer (LA) type question carrying 5 marks each.
Section E has 2 questions carrying 4 marks each. One internal choice is given
in Q 35 against part C only.
All programming questions are to be answered using Python Language only.
91 ^ Page 1 of 19 P.T.O.
276
SECTION A
(a) Dictionary
(b) String
(c) List
(d) Tuple
(a) Day.pop()
(b) Day.pop(2)
(c) Day.pop(1)
(d) Day.pop("Tuesday")
(c) NONE
(d) NULL
91 Page 2 of 19
277
5. Select the correct output of the code :
S="Amrit Mahotsav @ 75"
A=S.split(" ",2)
print(A)
(a) ('Amrit', 'Mahotsav', '@', '75')
(b) ['Amrit', 'Mahotsav', '@ 75']
(c) ('Amrit', 'Mahotsav', '@ 75')
(d) ['Amrit', 'Mahotsav', '@', '75']
6. Which of the following modes in Python creates a new file, if file does not
exist and overwrites the content, if the file exists ?
(a) r+ (b) r
(c) w (d) a
278
10. Fill in the blank :
In a relational model, tables are called _________, that store data for
different columns.
(a) Attributes
(b) Degrees
(c) Relations
(d) Tuples
91 Page 4 of 19
279
14. What will the following expression be evaluated to in Python ?
print(6/3 + 4**3//8 4)
(a) 6.5
(b) 4.0
(c) 6.0
(d) 4
15. Which of the following functions is a valid built-in function for both list
and dictionary datatype ?
(a) items()
(b) len()
(c) update()
(d) values()
16. fetchone() method fetches only one row in a ResultSet and returns a
__________.
(a) Tuple
(b) List
(c) Dictionary
(d) String
Q. 17 and 18 are Assertion (A) and Reasoning (R) 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).
280
17. Assertion (A) : In Python, a stack can be implemented using a list.
Reasoning (R) : A stack is an ordered linear list of elements that works
on the principle of First In First Out (FIFO).
18. Assertion (A) : readlines() reads all the lines from a text file and
returns the lines along with newline as a list of strings.
Reasoning (R) : readline() can read the entire text file line by line
without using any looping statements.
SECTION B
20. (a) Write any two differences between Fiber-optic cable and Coaxial
cable. 2
OR
(b) Write one advantage and one disadvantage of wired over wireless
communication. 2
91 Page 6 of 19
281
21. (a) Given is a Python string declaration : 1
NAME = "Learning Python is Fun"
Write the output of : print(NAME[-5:-10:-1])
24. (a) Write the output of the Python code given below : 2
g=0
def fun1(x,y):
global g
g=x+y
return g
def fun2(m,n):
global g
g=m-n
return g
k=fun1(2,3)
fun2(k,7)
print(g)
OR
91 Page 7 of 19 P.T.O.
282
(b) Write the output of the Python code given below : 2
a=15
def update(x):
global a
a+=2
if x%2==0:
a*=x
else:
a//=x
a=a+5
print(a,end="$")
update(5)
print(a)
SECTION C
Table : Sport
ADMNO GAME
1100 CRICKET
1103 FOOTBALL
91 Page 8 of 19
283
(b) Write the output of the queries (i) to (iv) based on the table,
GARMENT given below : 2
TABLE : GARMENT
GCODE TYPE PRICE FCODE ODR_DATE
G101 EVENING GOWN 850 F03 2008-12-19
G102 SLACKS 750 F02 2020-10-20
G103 FROCK 1000 F01 2021-09-09
G104 TULIP SKIRT 1550 F01 2021-08-10
G105 BABY TOP 1500 F02 2020-03-31
G106 FORMAL PANT 1250 F01 2019-01-06
27. (a) Write a function in Python that displays the book names having
y in their name from a text file Bookname.t 3
Example :
s the names of following books :
OR
91 Page 9 of 19 P.T.O.
284
(b) Write a function RevString()
prints the words The rest of the
content is displayed normally. 3
Example :
If content in the text file is :
UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM
Output will be :
UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM
28. Write the output of any three SQL queries (i) to (iv) based on the tables
COMPANY and CUSTOMER given below : 3
Table : COMPANY
CID C_NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY CHENNAI MOBILE
666 DELL DELHI LAPTOP
Table : CUSTOMER
CUSTID CID NAME PRICE QTY
C01 222 ROHIT SHARMA 70000 20
C02 666 DEEPIKA KUMARI 50000 10
C03 111 MOHAN KUMAR 30000 5
C04 555 RADHA MOHAN 30000 11
91 Page 10 of 19
285
29. Write a function search_replace() in Python which accepts a list L of
numbers and a number to be searched. If the number exists, it is replaced
by 0 and if the number does not exist, an appropriate message is
displayed. 3
Example :
L = [10,20,30,10,40]
Number to be searched = 10
(ii) Pop_element() To pop the object from the stack and display it.
For example :
If the lists of courses details are :
3]
2]
3]
2]
3]
91 Page 11 of 19 P.T.O.
286
SECTION D
31. ABC Consultants are setting up a secure network for their office campus
at Noida for their day-to-day office and web-based activities. They are
planning to have connectivity between three buildings and the head office
situated in Bengaluru. As a network consultant, give solutions to the
questions (i) to (v), after going through the building locations and other
details which are given below :
BUILDING 3
Number of computers
Building Number of Computers
Building 1 25
Building 2 51
Building 3 150
Head Office 10
(i) Suggest the most suitable place to install the server for this
organization. Also, give reason to justify your suggested location. 1
(ii) Suggest the cable layout of connections between the buildings
inside the campus. 1
91 Page 12 of 19
287
(iii) Suggest the placement of the following devices with justification : 1
Switch
Repeater
(v) The System Administrator does remote login to any PC, if any
requirement arises. Name the protocol, which is used for the same. 1
import random
S=["Pen","Pencil","Eraser","Bag","Book"]
for i in range (1,2):
f=random.randint(i,3)
s=random.randint(i+1,4)
print(S[f],S[s],sep=":")
Options :
(I) Pencil:Book
(II) Pencil:Book
Eraser:Bag
(III) Pen:Book
Bag:Book
(IV) Bag:Eraser
91 Page 13 of 19 P.T.O.
288
(ii) The table Bookshop in MySQL contains the following
attributes :
B_code Integer
B_name String
Qty Integer
Price Integer
mydb=mysql.connect(host="localhost",
user="shop",passwd="Book",database="Bstore")
mycursor=__________ # Statement 1
qry= "update Bookshop set Qty=20 where
B_code=105"
___________________ # Statement 2
___________________ # Statement 3
OR
91 Page 14 of 19
289
(b) (i) Predict the output of the code given below : 2
text="LearningCS"
L=len(text)
ntext=""
for i in range (0,L):
if text[i].islower():
ntext=ntext+text[i].upper()
elif text [i].isalnum():
ntext=ntext+text[i 1]
else:
ntext=ntext+'&&'
print(ntext)
91 Page 15 of 19 P.T.O.
290
Statement 3 to read the complete result of the query into
the object named B_Details, from the table Bookshop in
the database.
mydb=mysql.connect(host="localhost",
user="shop",passwd="Book",database="Bstore")
mycursor=___________ # Statement 1
mycursor.execute("_________") # Statement 2
B_Details=__________ # Statement 3
for i in B_Details:
print(i)
33. (a) Write a point of difference between append (a) and write (w)
modes in a text file. 5
Write a program in Python that defines and calls the following
user defined functions :
(i) Add_Teacher() : It accepts the values from the user and
inserts
record consists of a list with field elements as T_id, Tname
and desig to store teacher ID, teacher name and
designation respectively.
(ii) Search_Teacher() : To display the records of all the PGT
(designation) teachers.
OR
(b) Write one point of difference between seek() and tell()
functions in file handling. Write a program in Python that defines
and calls the following user defined functions : 5
(i) Add_Device() : The function accepts and adds records of the
91 Page 16 of 19
291
SECTION E
Table : Salesperson
S_ID S_NAME AGE S_AMOUNT REGION
S001 SHYAM 35 20000 NORTH
S002 RISHABH 30 25000 EAST
S003 SUNIL 29 21000 NORTH
S004 RAHIL 39 22000 WEST
S005 AMIT 40 23000 EAST
91 Page 17 of 19 P.T.O.
292
35. Atharva is a programmer, who has recently been given a task to write a
Python code to perform the following binary file operation with the help
of a user defined function/module :
the item details stored in the binary file, items.dat, except for
the item whose item_id is 101. The data is stored in the following
format :
{item_id:[item_name,amount]}
def Copy_new():
f1=_____________ # Statement 2
f2=_____________ # Statement 3
item_detail=___________ # Statement 4
if _______________: # Statement 5
pickle.___________ # Statement 6
f1.close()
f2.close()
He has succeeded in writing partial code and has missed out certain
statements. Therefore, as a Python expert, help him to complete the code
91 Page 18 of 19
293
(i) Which module should be imported in the program ? (Statement 1) 1
(ii) Write the correct statement required to open the binary file
"items.dat". (Statement 2) 1
91 Page 19 of 19 P.T.O.
294
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Marking Scheme
Strictly Confidential
(For Internal and Restricted use only)
Senior School Certificate Examination, 2023 (Supplimentary)
SUBJECT NAME Computer Science (NEW) (PAPER CODE 91)
General Instructions: -
1 You are aware that evaluation is the most important process in the actual and correct
assessment of the candidates. A small mistake in ev aluation may lead to serious problems which
may affect the future of the candidates, education system and teaching profession. To avoid
mistakes, it is requested that before starting evaluation, you must read and understand the spot
evaluation guidelines carefully.
2 “Evaluation policy is a confidential policy as it is related to the confidentiality of the
examinations conducted, Evaluation done and several other aspects. Its’ leakage to the
public in any manner could lead to derailment of the examination system and affect the life
and future of millions of candidates. Sharing this policy/document to anyone, publishing in
any magazine and printing in News Paper/Website etc may invite action under various rules
of the Board and IPC.”
3 Evaluation is to be done as per instructions provided in the Marking Scheme. It should not be
done according to one’s own interpretation or any other consideration. Marking Scheme should
be strictly adhered to and religiously followed. However, while evaluating answers which are
based on latest information or knowledge and/or are innovative, they may be assessed for
their correctness otherwise and due marks be awarded to them. In class-XII, while
evaluating two competency-based questions, please try to understand the given answer and
even if the reply is not from the marking scheme but correct competency is enumerated by
the candidate, due marks should be awarded.
4 The Marking scheme carries only suggested value points for the answers
These are in the nature of Guidelines only and do not constitute the complete answer. The
students can have their own expression and if the expression is correct, the due marks should be
awarded accordingly.
5 The Head-Examiner must go through the first five answer books evaluated by each evaluator on
the first day, to ensure that evaluation has been carried out as per the instructions given in the
Marking Scheme. If there is any variation, the same should be zero after deliberation and
discussion. The remaining answer books meant for evaluation shall be given only after ensuring
that there is no significant variation in the marking of individual evaluators.
6 Evaluators will mark( √ ) wherever the answer is correct. For wrong answer CROSS ‘X” be
marked. Evaluators will not put right (✓)while evaluating which gives an impression that the
answer is correct and no marks are awarded. This is the most common mistake which
evaluators are committing.
7 If a question has parts, please award marks on the right-hand side for each part. Marks awarded
for different parts of the question should then be totaled up and written in the left-hand margin
and encircled. This may be followed strictly.
8 If a question does not have any parts, marks must be awarded in the left-hand margin and
encircled. This may also be followed strictly.
9 If a student has attempted an extra question, the answer of the question deserving more marks
should be retained and the other answer scored out with a note “Extra Question”.
10 No marks to be deducted for the cumulative effect of an error. It should be penalized only once.
11 A full scale of marks 0 to 70 has to be used. Please do not hesitate to award full marks if the
answer deserves it.
- 1 of 24-
295
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
12 Every examiner has to necessarily do evaluation work for full working hours i.e., 8 hours every
day and evaluate 20 answer books per day in main subjects and 25 answer books per day in other
subjects (Details are given in Spot Guidelines).This is in view of the reduced syllabus and number
of questions in question paper.
13 Ensure that you do not make the following common types of errors committed by the Examiner
in the past:-
● Leaving the answer or part thereof unassessed in an answer book.
● Giving more marks for an answer than assigned to it.
● Wrong totaling of marks awarded on an answer.
● Wrong transfer of marks from the inside pages of the answer book to the title page.
● Wrong question wise totaling on the title page.
● Wrong totaling of marks of the two columns on the title page.
● Wrong grand total.
● Marks in words and figures not tallying/not same.
● Wrong transfer of marks from the answer book to online award list.
● Answers marked as correct, but marks not awarded. (Ensure that the right tick mark is
correctly and clearly indicated. It should merely be a line. Same is with the X for incorrect
answers.)
● Half or a part of the answer marked correct and the rest is wrong, but no marks awarded.
14 While evaluating the answer books, if the answer is found to be totally incorrect, it should be
marked as cross (X) and awarded zero (0)Marks.
15 Any un-assessed portion, non-carrying over of marks to the title page, or totaling error detected
by the candidate shall damage the prestige of all the personnel engaged in the evaluation work
as also of the Board. Hence, in order to uphold the prestige of all concerned, it is again
reiterated that the instructions be followed meticulously and judiciously.
16 The Examiners should acquaint themselves with the guidelines given in the “Guidelines for spot
Evaluation” before starting the actual evaluation.
17 Every Examiner shall also ensure that all the answers are evaluated, marks carried over to the
title page, correctly totaled and written in figures and words.
18 The candidates are entitled to obtain a photocopy of the Answer Book on request on payment of
the prescribed processing fee. All Examiners/Additional Head Examiners/Head Examiners are
once again reminded that they must ensure that evaluation is carried out strictly as per value
points for each answer as given in the Marking Scheme.
1 In Python, string content is accepted within a pair of single quotes ' ' or within a pair of
double quotes " ".
2 In MySQL, CHAR/VARCHAR/DATE type content is accepted within a pair of single quotes ' ' or
within a pair of double quotes " ".
6 All answers/codes are suggestive, any other alternative correct answers to be accepted.
- 2 of 24-
296
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
General Instructions:
(i) This question paper contains five sections, Section A to E.
(ii) All questions are compulsory.
(iii) Section A has 18 questions carrying 1 mark each.
(iv) Section B has 7 Very Short Answer (VSA) type questions carrying 2 marks each.
(v) Section C has 5 Short Answer (SA) type questions carrying 3 marks each.
(vi) Section D has 3 Long Answer (LA) type questions carrying 5 marks each.
(vii) Section E has 2 questions carrying 4 marks each. One internal choice is given in Q.34 and Q.
35, against Part (iii) only.
(viii) All programming questions are to be answered using python language only.
SECTION - A
1 State True or False. 1
“Comments are not executed by interpreter.”
Ans True
(1 Mark for writing the correct answer)
2 Which of the following is not a sequential datatype in Python ? 1
(a) Dictionary (b) String
(c) List (d) Tuple
- 3 of 24-
297
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
6 Which of the following modes in Python creates a new file, if file does not exist and 1
overwrites the content, if the file exists ?
(a) r+ (b) r
(c) w (d) a
Ans (c) w
Ans (a) is
(1 Mark for writing the correct option)
9 Which of the following statement(s) would give an error after executing the following code? 1
S="Happy" # Statement 1
print(S*2) # Statement 2
S+="Independence" # Statement 3
S.append("Day") # Statement 4
print(S) # Statement 5
(a) Statement 2 (b) Statement 3
(c) Statement 4 (d) Statement 3 and 4
298
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
- 5 of 24-
299
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Q. 17 and 18 are Assertion (A) and Reasoning (R) based questions. Mark the correct
choice as
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but (R) is true.
17 Assertion (A) : In Python, a stack can be implemented using a list. 1
Reasoning (R) : A stack is an ordered linear list of elements that works on the principle
of First In First Out (FIFO).
Ans (c) (A) is true but (R) is false. .
(1 Mark for writing the correct option)
18 Assertion (A) : readlines() reads all the lines from a text file and returns the lines 1
along with newline as a list of strings.
Reasoning (R) : readline() can read the entire text file line by line without using any
looping statements.
Ans (c) (A) is true but (R) is false.
(1 Mark for writing the correct option)
SECTION - B
19 Ravi, a Python programmer, is working on a project in which he wants to write a function 2
to count the number of even and odd values in the list. He has written the following
code but his code is having errors. Rewrite the correct code and underline the
corrections made.
define EOCOUNT(L):
even_no=odd_no=0
for i in range(0,len(L))
if L[i]%2=0:
even_no+=1
Else:
odd_no+=1
print(even_no, odd_no)
Ans def EOCOUNT(L): # Error 1
even_no=odd_no=0
for i in range(0,len(L)): # Error 2
if L[i]%2==0: # Error 3
even_no+=1
else: # Error 4
odd_no+=1
print(even_no, odd_no)
(½ Mark for correctly identifying and correcting each of the four errors)
- 6 of 24-
300
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Coaxial cable
Slow, Economic, Convenient to lay down using the bus topology of networks
(2 Marks for writing the correct difference between Fiber-optic cable and
coaxial cable)
OR
(1 Mark for correctly defining Fiber-optic cable)
(1 Mark for correctly defining coaxial cable)
OR
(b) Write one advantage and one disadvantage of wired over wireless communication. 2
Ans Wired technologies:
Advantage:
● point to point connectivity between nodes and are not affected by the variation
in weather conditions.
● Speed is higher in wired connectivity.
Disadvantage:
● Cut in cable (Wired Technology) will result in network failure
Examples
● Optical Fiber, Ethernet Cable, Co-axial Cable are used in Wired Technologies
Wireless technologies:
Disadvantage:
● are not necessarily point to point connectivity between nodes and can be
affected by the variation in weather conditions.
● Speed is lesser as compared to wired connectivity.
Advantage:
● There is no issue of physical cut
Examples
● Bluetooth, Microwave, Radiowave, Satellite Links are examples of Wireless
Technologies
(1 Mark for writing any one correct advantage of wired over wireless
communication)
(1 Mark for writing any one correct disadvantage of wired over wireless
communication)
Note:
1 Mark for only specifying the names of Wired and Wireless Technologies
21 (a) Given is a Python string declaration : 1
NAME = "Learning Python is Fun"
Write the output of : print(NAME[-5:-10:-1])
Ans si no
(1 Mark for writing the correct output)
301
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
22 Explain the usage of HAVING clause in GROUP BY command in RDBMS with the help of an 2
example.
Ans HAVING is used for including conditions based on aggregate functions on groups.
OR
FIle Transfer Protocol
Ans -2
(2 Mark for writing the correct output)
Note:
Give only 1 mark if 2 written without minus sign
OR
- 8 of 24-
302
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
The function returns 1 if Exprs is equal to any of the values in the IN list, otherwise,
returns 0.
Example:
SELECT NAME, SECTION
FROM STUDENTS
WHERE SECTION IN (‘C’ , ‘D’);
Example:
SELECT ROLL, MARKS
FROM RESULT
WHERE MARKS BETWEEN 75 AND 100;
- 9 of 24-
303
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
SECTION-C
26 (a) Consider the following tables - Student and Sport : 1
Table : Student
ADMNO NAME CLASS
1100 MEENA X
1101 VANI XI
Table: Sport
ADMNO GAME
1100 CRICKET
1103 FOOTBALL
- 10 of 24-
304
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Ans
FCODE COUNT(*) MIN(PRICE)
F02 2 750
F01 3 1000
OR
def Book_Name():
fin=open('Bookname.txt')
for line in fin:
if 'y' in line or 'Y' in line: # or if 'Y' in line.upper():
print(line,end="") # ignore end=""
fin.close()
- 11 of 24-
305
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
OR
Any other correct equivalent code
(½ Mark for writing the function header correctly with any function identifier
and/or argument)
(½ Mark for opening the file correctly)
(½ Mark for reading/extracting the lines from the file)
(½ Mark for processing the lines one by one using a loop)
(½ Mark for checking condition for presence of ‘y’ or ‘Y’)
(½ Mark for printing the matching lines)
OR
(b) Write a function RevString() to read a textfile “Input.txt” and prints the words starting 3
with ‘O’ in reverse order. The rest of the content is displayed normally.
Example :
Output will be :
UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM
OR
Any other correct equivalent code
(½ Mark for writing the function header correctly)
(½ Mark for opening the file correctly)
(½ Mark for reading/separating all words from the file)
(½ Mark for checking the first alphabet of each word )
(½ Mark for displaying the matched word in reverse order)
(½ Mark for displaying all unmatched words)
28 (a) Write the output of any three SQL queries (i) to (iv) based on the tables COMPANY and 3
CUSTOMER given below :
Table : COMPANY
CID C_NAME CITY PRODUCTNAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAI MOBILE
555 BLACKBERRY CHENNAI MOBILE
666 DELL DELHI LAPTOP
- 12 of 24-
306
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Table: CUSTOMER
CUSTID CID NAME PRICE QTY
C01 222 ROHIT SHARMA 70000 20
C02 666 DEEPIKA KUMARI 50000 10
C03 111 MOHAN KUMAR 30000 5
C04 555 RADHA MOHAN 30000 11
MOBILE 3
Ans
DISTINCT(CITY)
DELHI
MUMBAI
CHENNAI
- 13 of 24-
307
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Example :
L = [10,20,30,10,40]
Number to be searched = 10
OR
Any other correct equivalent code
Write the following user defined functions to perform given operations on the stack
named 'Univ' :
(ii) Pop_element() - To pop the object from the stack and display it. Also, display
“Underflow” when there is no element in the stack.
- 14 of 24-
308
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
For example :
If the lists of courses details are :
["MCA", 200000, 3]
["MBA", 500000, 2]
["BA", 100000, 3]
Ans Univ=[]
def Push_element(Course):
for Rec in Course:
if Rec[1]>100000:
Univ.append(Rec)
def Pop_element():
while len(Univ)>0:
print(Univ.pop())
else:
print("Underflow")
OR
Course=[["MCA",200000,3],["MBA",500000,2],["BA",100000,3]]
Univ=[]
def Push_element():
for Rec in Course:
if Rec[1]>100000:
Univ.append(Rec)
def Pop_element():
while len(Univ)>0:
print(Univ.pop())
else:
print("Underflow")
OR
Any other correct equivalent code
(½ Mark for writing function header Push_element correctly with or without
argument)
(½ Mark for processing and checking each element of the courses list)
(½ Mark for appending the matched data into the stack Univ)
SECTION - D
- 15 of 24-
309
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
31 ABC Consultants are setting up a secure network for their office campus at Noida for
their day-to-day office and web-based activities. They are planning to have connectivity
between three buildings and the head office situated in Bengaluru. As a network
consultant, give solutions to the questions (i) to (v), after going through the building
locations and other details which are given below :
BENGALURU BRANCH
HEAD OFFICE
Number of computers
Building Number of Computers
Building 1 25
Building 2 51
Building 3 150
Head Office 10
(i) Suggest the most suitable place to install the server for this organization. Also, give 1
reason to justify your suggested location.
Ans Building 3
It has maximum number of computers
OR
Building 2
Considering closest to both the other buildings
(ii) Suggest the cable layout of connections between the buildings inside the campus. 1
Ans
- 16 of 24-
310
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
OR
Repeater to be placed between Building 1 and Building 3 because distance is more than
100 meters between these two buildings.
However, if the second layout given in this marking scheme is considered, repeater will
not be required at all.
(½ Mark for correctly suggesting placement of Switch)
(½ Mark for correctly suggesting placement of Repeater)
(iv) The organization is planning to provide a high-speed link with the head office situated in 1
Bengaluru, using a wired connection.
import random
S=["Pen","Pencil","Eraser","Bag","Book"]
- 17 of 24-
311
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Options:
(I) Pencil:Book (II) Pencil:Book
Eraser:Bag
Note the following to establish connectivity between Python and MySQL on a ‘localhost’ :
● Username is ‘shop’
● Password is ‘Book’
● The table exists in a MySQL database named Bstore.
The code given below updates the records from the table Bookshop in MySQL.
Statement 1 - to form the cursor object.
Statement 2 - to execute the query that updates the Qty to 20 of the records whose
B_code is 105 in the table.
Statement 3 - to make the changes permanent in the database.
Statement 1: mydb.cursor()
Statement 2: mycursor.execute(qry)
Statement 3: mydb.commit()
OR
Statement 3: mycursor.execute("COMMIT")
(1 Mark for writing each correct statement)
- 18 of 24-
312
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
OR
(b) (i) Predict the output of the code given below : 2
text="LearningCS"
L=len(text)
ntext=""
for i in range (0,L):
if text[i].islower():
ntext=ntext+text[i].upper()
elif text [i].isalnum():
ntext=ntext+text[i-1]
else:
ntext=ntext+'&&'
print(ntext)
Ans SEARNINGgC
(1 Mark for the output resulting from condition given if i.e. _EARNING__)
(1 Mark for the output resulting from condition given elif i.e. S_______gC)
OR
(½ Mark for correctly writing part of the output as S_________)
(½ Mark for correctly writing part of the output as _EAR______)
(½ Mark for correctly writing part of the output as ____NING__)
(½ Mark for correctly writing part of the output as ________gC)
- 19 of 24-
313
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
33 (a) Write a point of difference between append (a) and write (w) modes in a text file. 5
Write a program in Python that defines and calls the following user defined functions :
(i) Add_Teacher() : It accepts the values from the user and inserts record of a teacher
to a csv file ‘Teacher.csv’. Each record consists of a list with field elements as
T_id,Tname and desig to store teacher ID, teacher name and designation
respectively.
(ii) Search_Teacher() : To display the records of all the PGT (designation) teachers.
Ans a (append) mode - To open the file to write the content at the bottom(or end) of
existing content. It also creates the file, if it does not exist.
whereas
w (write) mode - To create a new file to write the content in it. It overwrites the file, if
it already exists.
import csv
def Add_Teacher():
fout=open("Teacher.csv","a",newline="\n")
T_id=int(input("Enter Teacher id: "))
Tname=input("Enter Teacher name: ")
desig=input("Enter Designation: ")
rec=[T_id,Tname,desig]
csvw=csv.writer(fout)
csvw.writerow(rec)
fout.close()
def Search_Teacher():
fin=open("Teacher.csv")
csvr=csv.reader(fin)
for record in csvr:
if record[2]=="PGT":
print(record)
fin.close()
Add_Teacher()
Search_Teacher()
(2 Mark for writing 1 point of difference between append(a) and write (w) modes)
OR
(2 Mark for illustrating the difference using only example)
OR
(1 Marks for correct explanation of append (a) mode)
(1 Mark for correct explanation of write (w) mode)
—------------------------------------------------------------------
(1 Mark for writing correct function definition of Add_Teacher(), ½ Mark for
partially correct code)
- 20 of 24-
314
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
Ans seek() method is used to move the file pointer to a specified location in the file object.
tell() method is used to return the current location of the file pointer in the file object.
import csv
def Add_Device():
fout=open("perpheral.csv","a",newline="\n")
P_id=int(input("Enter Device Id: "))
P_name=input("Enter Device name: ")
Price=int(input("Enter Price: ")
rec=[P_id,P_name,Price]
csvw=csv.writer(fout)
csvw.writerow(rec)
fout.close()
def Count_Device():
fin=open("peripheral.csv")
csvr=csv.reader(fin)
ctr=0
for record in csvr:
if int(record[2])<1000:
ctr=ctr+1
print("Count of Price<1000 is",ctr)
fin.close()
Add_Device()
Count_Device()
(2 Mark for writing 1 point of difference between seek() and tell() functions
with/without example)
OR
(2 Mark for illustrating the difference using only example)
OR
(1 Marks for correct explanation of seek() function)
(1 Mark for correct explanation of tell() function)
—------------------------------------------------------------------
- 21 of 24-
315
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
SECTION - E
34 The ABC Company is considering to maintain their salespersons records using SQL to
store data. As a database administrator, Alia created the table Salesperson and also
entered the data of 5 Salespersons.
Table : Salesperson
S_ID S_NAME AGE S_AMOUNT REGION
S001 SHYAM 35 20000 NORTH
S002 RISHABH 30 25000 EAST
S003 SUNIL 29 21000 NORTH
S004 RAHIL 39 22000 WEST
S005 AMIT 40 23000 EAST
316
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
● Copy_new() : to create a binary file new_items.dat and write all the item details
stored in the binary file, items.dat, except for the item whose item_id is 101.
The data is stored in the following format :
{item_id:[item_name,amount]}
- 23 of 24-
317
CBSE AISSCE 2023 Marking Scheme for Computer Science (NEW)
(Sub Code: 083 Series ∑HEFG/C Paper Code 91 Set-4)
(iii) Which statement should Atharva fill in Statement 3 to open the binary file 2
"new_items.dat" and in Statement 4 to read all the details from the binary file
"items.dat".
Ans open("new_items.dat","wb")
pickle.load(f1)
OR
f2=open("new_items.dat","wb")
item_detail = pickle.load(f1)
(1 Mark for correctly writing missing function/method in Statement 3)
(1 Mark for correctly writing missing function/method in Statement 4)
OR (Option for Part (iii) only)
(iii) What should Atharva write in Statement 5 to apply the given condition and in Statement 2
6 to write data in the binary file "new_items.dat".
Ans if key != 101:
pickle.dump(item_detail[key],f2) #OR any alternative valid code
OR
if key != item_id:
pickle.dump(item_detail[key],f2) #OR any alternative valid code
(1 Mark for correctly writing missing condition in Statement 5)
(1 Mark for correctly writing missing function/method in Statement 6)
- 24 of 24-
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Marking Scheme
Strictly Confidential
(For Internal and Restricted use only)
Senior Secondary School Certificate Examination, 2024
Subject Name: Computer Science (Q.P. CODE 91)
1 You are aware that evaluation is the most important process in the actual and correct
assessment of the candidates. A small mistake in evaluation may lead to serious problems which
may affect the future of the candidates, education system and teaching profession. To avoid
mistakes, it is requested that before starting evaluation, you must read and understand the spot
evaluation guidelines carefully.
3 Evaluation is to be done as per instructions provided in the Marking Scheme. It should not be
done according to one’s own interpretation or any other consideration. Marking Scheme should
be strictly adhered to and religiously followed. However, while evaluating, answers which are
based on latest information or knowledge and/or are innovative, they may be assessed for their
correctness otherwise and due marks be awarded to them. In class-XII, while evaluating two
competency-based questions, please try to understand given answer and even if reply is not from
marking scheme but correct competency is enumerated by the candidate, due marks should be
awarded.
4 The Marking scheme carries only suggested value points for the answers
These are in the nature of Guidelines only and do not constitute the complete answer. The
students can have their own expression and if the expression is correct, the due marks should be
awarded accordingly.
5 The Head-Examiner must go through the first five answer books evaluated by each evaluator on
the first day, to ensure that evaluation has been carried out as per the instructions given in the
Marking Scheme. If there is any variation, the same should be zero after deliberation and
discussion. The remaining answer books meant for evaluation shall be given only after ensuring
that there is no significant variation in the marking of individual evaluators.
6 Evaluators will mark( √ ) wherever answer is correct. For wrong answer CROSS ‘X’ be marked.
Evaluators will not put right (✓)while evaluating which gives an impression that answer is
correct and no marks are awarded. This is most common mistake which evaluators are committing.
7 If a question has parts, please award marks on the right-hand side for each part. Marks awarded
for different parts of the question should then be totaled up and written in the left-hand margin
and encircled. This may be followed strictly.
8 If a question does not have any parts, marks must be awarded in the left-hand margin and
encircled. This may also be followed strictly.
9 If a student has attempted an extra question, answer of the question deserving more marks
should be retained and the other answer scored out with a note “Extra Question”.
10 No marks to be deducted for the cumulative effect of an error. It should be penalized only once.
11 A full scale of marks 70 marks as given in Question Paper has to be used. Please do not hesitate
to award full marks if the answer deserves it.
Page 1/26
335
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
12 Every examiner has to necessarily do evaluation work for full working hours i.e., 8 hours every
day and evaluate 20 answer books per day in main subjects and 25 answer books per day in other
subjects (Details are given in Spot Guidelines).This is in view of the reduced syllabus and number
of questions in question paper.
13 Ensure that you do not make the following common types of errors committed by the Examiner
in the past:-
● Leaving answer or part thereof unassessed in an answer book.
● Giving more marks for an answer than assigned to it.
● Wrong totaling of marks awarded on an answer.
● Wrong transfer of marks from the inside pages of the answer book to the title page.
● Wrong question wise totaling on the title page.
● Wrong totaling of marks of the two columns on the title page.
● Wrong grand total.
● Marks in words and figures not tallying/not same.
● Wrong transfer of marks from the answer book to online award list.
● Answers marked as correct, but marks not awarded. (Ensure that the right tick mark is
correctly and clearly indicated. It should merely be a line. Same is with the X for incorrect
answer.)
● Half or a part of answer marked correct and the rest as wrong, but no marks awarded.
14 While evaluating the answer books if the answer is found to be totally incorrect, it should be
marked as cross (X) and awarded zero (0)Marks.
15 Any unassessed portion, non-carrying over of marks to the title page, or totaling error detected
by the candidate shall damage the prestige of all the personnel engaged in the evaluation work
as also of the Board. Hence, in order to uphold the prestige of all concerned, it is again
reiterated that the instructions be followed meticulously and judiciously.
16 The Examiners should acquaint themselves with the guidelines given in the “Guidelines for Spot
Evaluation” before starting the actual evaluation.
17 Every Examiner shall also ensure that all the answers are evaluated, marks carried over to the
title page, correctly totaled and written in figures and words.
18 The candidates are entitled to obtain photocopy of the Answer Book on request on payment of
the prescribed processing fee. All Examiners/Additional Head Examiners/Head Examiners are
once again reminded that they must ensure that evaluation is carried out strictly as per value
points for each answer as given in the Marking Scheme.
SPECIFIC INSTRUCTIONS FOR COMPUTER SCIENCE ONLY
1 In Python, string content is accepted within a pair of single quotes ' ' or within a pair of
double quotes " ".
2 In MySQL, CHAR/VARCHAR/DATE type content is accepted within a pair of single quotes ' ' or
within a pair of double quotes " ".
6 All answers/codes are suggestive, any other alternative correct answers to be accepted.
Page 2/26
336
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
General Instructions:
(i) Please check this question paper which contains 35 questions.
(ii) The paper is divided into 5 Sections - A, B, C, D and E.
(iii) Section A, consists of 18 questions (1 to 18). Each question carries 1 Mark.
(iv) Section B, consists of 7 questions (19 to 25). Each question carries 2 Marks.
(v) Section C, consists of 5 questions (26 to 30). Each question carries 3 Marks.
(vi) Section D, consists of 2 questions (31 to 32). Each question carries 4 Marks.
(vii) Section E, consists of 3 questions (33 to 35). Each question carries 5 Marks.
(viii) All programming questions are to be answered using Python Language only.
SECTION-A
1. State True or False : 1
While defining a function in Python, the positional parameters in the function header must
always be written after the default parameters.
Ans False
2. The SELECT statement when combined with ___ clause, returns records without repetition. 1
print (16*5/4*2/5–8)
4. What possible output from the given options is expected to be displayed when the 1
following Python code is executed ?
import random
Signal=['RED','YELLOW','GREEN']
for K in range (2, 0, – 1) :
R = random.randrange(K)
print (Signal[R], end = '#')
Page 3/26
337
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(a) YELLOW # RED # (b) RED # GREEN #
5. In SQL, the aggregate function which will display the cardinality of the table is __________. 1
(a) sum() (b) count(*)
6. Which protocol out of the following is used to send and receive emails over a computer 1
network ?
(a) PPP (b) HTTP
8. Consider the statements given below and then choose the correct output from the given 1
options :
myStr = "MISSISSIPPI"
print(myStr[:4]+"#"+myStr[–5:])
(a) MISSI#SIPPI (b) MISS#SIPPI
9. Identify the statement from the following which will raise an error : 1
(a) print("A"*3) (b) print(5*3)
Page 4/26
338
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans (c) print("15" + 3)
event="G20 Presidency@2023"
L=event.split(' ')
print(L[::–2])
(a) 'G20' (b) ['Presidency@2023']
11. Which of the following options is the correct unit of measurement for network bandwidth ? 1
(a) KB (b) Bit
(c) Hz (d) Km
Ans (c) Hz
a=20
def convert(a):
b=20
a=a+b
convert(10)
print(a)
Ans (b) 20
Ans False
Page 5/26
339
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
14. Which of the following is not a DDL command in SQL ? 1
(a) DROP (b) CREATE
Ans Protocol
OR
Name of any protocol
F=open('CONTENT.TXT')
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
17 Assertion (A) : CSV file is a human readable text file where each line has a number of fields, 1
separated by comma or some other delimiter.
Reason (R): writerow() method is used to write a single row in a CSV file.
Ans (b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
Reason (R): sort() does not exist as a method/function for strings in Python.
Page 6/26
340
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans (a) Both (A) and (R) are true and (R) is the correct explanation for (A).
SECTION-B
19 (A) (i) Expand the following terms: 2
XML ,PPP
(ii) Give one difference between circuit switching and packet switching.
OR
(B) (i) Define the term web hosting.
(ii) Name any two web browsers.
Ans (ii)
Circuit Switching Packet Switching
A dedicated path is established between Data to be transmitted is divided into small
the sender and the receiver before packets which are transmitted via nearest
starting data transmission. Entire data is service provider till all packets reach the
transmitted in one go. recipient where the packets are reassembled.
OR
Ans (B) (i) Web hosting is a service that allows users to put a website or a webpage onto the
internet, and make it a part of the World Wide Web.
(1 Mark for writing the correct definition of Web hosting)
20 The code given below accepts five numbers and displays whether they are even or odd: 2
Observe the following code carefully and rewrite it after removing all syntax and logical
errors :
Underline all the corrections made.
def EvenOdd()
for i in range(5) :
num=int(input("Enter a number")
if num/2==0:
print("Even")
else:
print("Odd")
EvenOdd()
Page 7/26
341
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans def EvenOdd(): # Error 1
for i in range(5) :
num=int(input("Enter a number")) # Error 2
if num%2==0: # Error 3
print("Even")
else:
print("Odd") # Error 4
EvenOdd()
21. (A) Write a user defined function in Python named showGrades(S) which takes the 2
dictionary S as an argument. The dictionary, S contains Name:[Eng,Math,Science] as
key:value pairs. The function displays the corresponding grade obtained by the
students according to the following grading rules :
OR
def showGrades(S):
for K in S:
Sum=0
for i in range(3):
Sum+=S[K][i]
if Sum/3>=90:
Grade="A"
elif Sum/3>=60:
Grade="B"
else:
Grade="C"
print(K,"–",Grade)
S={"AMIT":[92,86,64],"NAGMA":[65,42,43],"DAVID":[92,90,88]}
showGrades(S)
Page 8/26
342
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
OR
Any other correct variation of the code
(½ Mark for the loop to process individual students from the dictionary)
(1 Mark for calculating grades)
(½ Mark for displaying grades)
OR
(B) Write a user defined function in Python named Puzzle(W,N) which takes the
argument W as an English word and N as an integer and returns the string where
every Nth alphabet of the word W is replaced with an underscore ("_").
For example : if W contains the word "TELEVISION" and N is 3, then the function
should return the string "TE_EV_SI_N". Likewise for the word "TELEVISION" if
N is 4, then the function should return "TEL_VIS_ON".
Ans Word="TELEVISION"
def Puzzle(W, N):
NW=""
Count=1
for Ch in W:
if Count!=N:
NW+=Ch
Count+=1
else:
NW+="_"
Count=1
return NW
print(Puzzle(Word,3))
OR
def Puzzle(W,N):
W1=""
for i in range(len(W)):
if (i+1)%N==0:
W1=W1+"_"
else:
W1=W1+W[i]
return W1
print(Puzzle("TELEVISION",4))
OR
Any other correct variation of the code
22. Write the output displayed on execution of the following Python code : 2
LS=["HIMALAYA","NILGIRI","ALASKA","ALPS"]
D={}
for S in LS :
if len(S)%4 == 0:
D[S] = len(S)
for K in D :
print(K,D[K], sep = "#")
Page 9/26
343
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans HIMALAYA#8
ALPS#4
23. (A) Write the Python statement for each of the following tasks using built-in 1+1=2
functions/methods only :
(i) To remove the item whose key is "NISHA" from a dictionary named Students.
For example, if the dictionary Students contains
{"ANITA":90, "NISHA":76, "ASHA":92}, then after removal the dictionary
should contain{"ANITA":90,"ASHA":92}
(ii) To display the number of occurrences of the substring "is" in a string named
message.
For example if the string message contains "This is his book", then the
output will be 3.
(ii)
print(message.count("is"))
OR
message.count("is")
OR
Any other correct variation of the code
OR
(B) A tuple named subject stores the names of different subjects. Write the Python
commands to convert the given tuple to a list and thereafter delete the last element
of the list.
Page 10/26
344
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
OR
Any other correct variation of the code
24. (A) Ms. Veda created a table named Sports in a MySQL database, containing columns 2
Game_id, P_Age and G_name.
After creating the table, she realized that the attribute, Category has to be
added. Help her to write a command to add the Category column. Thereafter,
write the command to insert the following record in the table :
Game_id : G42
P_Age : Above 18
G_name : Chess
Category : Senior
OR
Page 11/26
345
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
25 Predict the output of the following code : 2
def callon(b=20,a=10) :
b=b+a
a=b-a
print(b, "#" , a )
return b
x=100
y=200
x=callon(x,y)
print (x,"@", y)
y=callon(y)
print (x,"@",y)
Ans 300#100
300@200
210#200
300@210
(Deduct ½ mark only if all the numeric parts of the output are correct but
formatting or/and separators are incorrect)
SECTION C
26. Write the output on execution of the following Python code: 3
S="Racecar Car Radar"
L=S.split()
for W in L :
x=W.upper()
if x==x[::-1]:
for I in x:
print(I,end="*")
else:
for I in W:
print(I,end="#")
print()
Ans R*A*C*E*C*A*R*
C#a#r#
R*A*D*A*R*
Note:
● Deduct ½ mark only if all the alphabets are correct but some cases -
lower/upper are incorrectly written
● Deduct ½ mark only if all the alphabets are correct but separators - */#
are incorrectly written OR new line not considered
Page 12/26
346
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
27 Consider the table ORDERS given below and write the output of the SQL queries that 1x3
=3
follow:
ORDNO ITEM QTY RATE ORDATE
1001 RICE 23 120 2023-09-10
1002 PULSES 13 120 2023-10-18
1003 RICE 25 110 2023-11-17
1004 WHEAT 28 65 2023-12-25
1005 PULSES 16 110 2024-01-15
1006 WHEAT 27 55 2024-04-15
1007 WHEAT 25 60 2024-04-30
Ans (i)
ITEM SUM(QTY)
RICE 48
PULSES 29
WHEAT 80
(ii)
ITEM QTY
RICE 25
WHEAT 28
(iii)
ORDNO ORDATE
1004 2023-12-25
1007 2024-04-30
Note:
● Ignore output heading
● Ignore order of rows
28 (A) Write a user defined function in Python named showInLines() which reads contents 3
of a text file named STORY.TXT and displays every sentence in a separate line.
Assume that a sentence ends with a full stop (.), a question mark (?), or an
exclamation mark (!).
Page 13/26
347
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
For example, if the content of file STORY.TXT is as follows :
Our parents told us that we must eat vegetables to be
healthy.And it turns out, our parents were right! So, what else
did our parents tell?
OR
def showInLines():
F = open("STORY.TXT",'r')
S=F.read()
for W in S:
if W.endswith(".") or W.endswith("?") or W.endswith("!"):
print(W)
elif W=="\n":
print(end="")
else:
print(W,end="")
F.close()
OR
Any other correct variation of the code
OR
(B) Write a function, c_words() in Python that separately counts and displays the
number of uppercase and lowercase alphabets in a text file, Words.txt.
Page 14/26
348
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans def c_words():
f=open("Words.txt","r")
Txt=f.read()
CLower=CUpper=0
for i in Txt:
if i.islower():
CLower+=1
elif i.isupper():
CUpper+=1
print(CLower, CUpper)
f.close()
OR
def c_words():
with open("Words.txt","r") as F:
Txt=f.read()
CL=CU=0
for i in Txt:
if i.islower(): # if i>="a" and i<="z":
CL+=1
elif i.isupper():# if i>="A" and i<="Z":
CU+=1
print(CL, CU)
Based on the given table, write SQL queries for the following:
(i) Add the constraint, primary key to column P_id in the existing table
Projects.
(ii) To change the language to Python of the project whose id is P002.
(iii) To delete the table Projects from MySQL database along with its data.
Page 15/26
349
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(ii) UPDATE Projects
SET LANGUAGE= "Python"
WHERE P_id = "P002";
Write the following user defined functions in Python and perform the specified
operations on a stack named BigNums.
(i) PushBig(): It checks every number from the list Nums and pushes all such
numbers which have 5 or more digits into the stack, BigNums.
(ii) PopBig(): It pops the numbers from the stack, BigNums and displays
them. The function should also display "Stack Empty" when there are
no more numbers left in the stack.
OR
Page 16/26
350
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
def PushBig():
for N in Nums:
if N >= 10000:
BigNums.append(N)
def PopBig():
while BigNums:
print(BigNums.pop())
print("Stack Empty")
OR
Any other correct variation of the code
Note:
Ignore the declarations of Nums and/or BigNums
SECTION D
31 Consider the tables Admin and Transport given below: 1x4
Table: Admin =4
S_id S_name Address S_type
S001 Sandhya Rohini Day Boarder
S002 Vedanshi Rohtak Day Scholar
S003 Vibhu Raj Nagar NULL
S004 Atharva Rampur Day Boarder
Table: Transport
S_id Bus_no Stop_name
S002 TSS10 Sarai Kale Khan
S004 TSS12 Sainik Vihar
S005 TSSl0 Kamla Nagar
(i) Display the student name and their stop name from the tables Admin and
Transport.
Page 17/26
351
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(ii) Display the number of students whose S_type is not known.
(iii) Display all details of the students whose name starts with 'V' .
OR
Any other correct query using/without using join
(iv) Display student id and address in alphabetical order of student name, from the table
Admin.
where
P_id is Peripheral device ID (integer)
P_name is Peripheral device name (String)
Price is Peripheral device price (integer)
Page 18/26
352
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Ans import csv
def Add_Device():
F=open("Peripheral.csv","a",newline='')
W=csv.writer(F)
P_id=int(input("Enter the Peripheral ID"))
P_name=input("Enter Peripheral Name")
Price=int(input("Enter Price"))
L=[P_id,P_name,Price]
W.writerow(L)
F.close()
def Count_Device():
F=open("Peripheral.csv","r")
L=list(csv.reader(F))
Count=0
for D in L:
if int(D[2])<1000:
Count+=1
print(Count)
F.close()
OR
Any other correct variation of the code
(½ Mark for opening the csv file correctly in the function Add_Device())
(½ Mark for reading the data from the user in the function Add_Device())
(½ Mark for writing the data correctly into the csv file in the function
Add_Device())
(½ Mark for opening the csv file correctly in the function Count_Device())
(½ Mark for reading the data from the file in the function Count_Device())
(½ Mark for loop in the function Count_Device())
(½ Mark for checking the condition and counting correctly in the function
Count_Device())
(½ Mark for printing the output correctly in the function Count_Device())
Note:
Full 4 mark should be awarded if the examinee has mentioned that there is no
mention of the task in the question
SECTION-E
33 Infotainment Ltd. is an event management company with its prime office located in 1x5
Bengaluru. The company is planning to open its new division at three different =5
locations in Chennai named as - Vajra, Trishula and Sudershana.
You, as a networking expert need to suggest solutions to the questions in part (i) to
(v), keeping in mind the distances and other given parameters.
Page 19/26
353
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(i) Suggest and draw the cable layout to efficiently connect various locations in
Chennai division for connecting the digital devices.
Ans
(Full 1 Mark for drawing any valid layout with OR without mentioning topology)
OR
(Only ½ mark for mentioning only topology without cable layout)
Page 20/26
354
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(ii) Which block in Chennai division should host the server? Justify your answer.
Ans Vajra can host the server as it has a maximum number of computers.
OR
Any other answer with valid justification
(iii) Which fast and effective wired transmission medium should be used to connect
the prime office at Bengaluru with the Chennai division?
(iv) Which network device will be used to connect the digital devices within each
location of Chennai division so that they may communicate with each other ?
Ans Switch/Hub/Router
(v) A considerable amount of data loss is noticed between the different locations of the
Chennai division, which are connected in the network. Suggest a networking device
that should be installed to refresh the data and reduce the data loss during
transmission to and from different locations of Chennai division.
Ans Repeater
OR
Mentioning any other valid reason or solution for data loss
34 (A) (i) Differentiate between 'w' and 'a' file modes in Python. 2+3
=5
Ans 'w':
Open the file in write mode.
If the file doesn’t exist, then a new file will be created.
The file pointer is in the beginning of the file.
If the file exists, the contents of the file, if any, are lost/truncated and the new data
is added as fresh data into the file.
'a':
Open the file in append mode.
If the file doesn’t exist, then a new file will be created.
The file pointer is at the end of the file.
If the file exists, the new data is added at the end of the file without deleting the
previous contents of the file.
Page 21/26
355
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
( 1 Mark each for any one correct characteristics of ‘a’ mode)
(ii)
Consider a binary file, items.dat, containing records stored in the given format :
{item_id: [item_name,amount]}
Write a function, Copy_new(), that copies all records whose amount is greater than
1000 from items.dat to new_items.dat.
OR
def Copy_new():
try:
F1=open("items.dat","rb")
F2=open("new_items.dat","wb")
D2={}
try:
while True:
D1=pickle.load(F1)
for k,v in D1.items():
if v[1]>1000:
D2[k]=v
except:
pickle.dump(D2,F2)
F1.close()
F2.close()
except:
print('File Opening Error')
OR
def Copy_new():
f=open("items.dat","rb")
f1=open("new_items.dat","wb")
while True:
try:
r=pickle.load(f)
for k,v in r.items():
if v[1]>1000:
pickle.dump(r, f1)
Page 22/26
356
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
except:
break
f.close()
f1.close()
OR
Any other correct variation of the code
OR
(B) (i) What is the advantage of using with clause while opening a data file in Python ?
Also give syntax of with clause.
The advantage of using with clause is that any file that is opened using this clause is
closed automatically, once the control comes outside the with clause.
Example:
with open("myfile.txt","r+") as file_object:
content = file_object.read()
(ii)
A binary file, EMP.DAT has the following structure :
[Emp_Id, Name, Salary]
where
Emp_Id : Employee id
Name : Employee Name
Salary : Employee Salary
Write a user defined function, disp_Detail(), that would read the contents of the
file EMP.DAT and display the details of those employees whose salary is below
25000.
def disp_Detail():
try:
with open("EMP.DAT","rb") as F:
Page 23/26
357
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
Data=pickle.load(F)
for D in Data:
if D[2]<25000:
print(D)
except:
print("File Not Found!!!")
OR
def disp_Detail():
try:
with open("EMP.DAT","rb") as F:
try:
while True:
Data=pickle.load(F)
if Data[2]<25000:
print(Data)
except:
print("File ended")
except:
print("File Not Found!!!")
OR
def disp_Detail():
try:
with open("EMP.DAT","rb") as F:
try:
while True:
Data=pickle.load(F)
for D in Data:
if D[2]<25000:
print(D)
except:
print("File ended")
except:
print("File Not Found!!!")
OR
Any other correct variation of the code
358
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
(ii) Sunil wants to write a program in Python to update the quantity to 20 of the
records whose item code is 111 in the table named shop in MySQL database named
Keeper.
The table shop in MySQL contains the following attributes :
● Item_code: Item code (Integer)
● Item_narne: Name of item (String)
● Qty: Quantity of item (Integer)
● Price: Price of item (Integer)
Consider the following to establish connectivity between Python and MySQL:
Username: admin
Password : Shopping
Host: localhost
OR
Ans ( ½ Mark each for the any two correct feature as mentioned above or any
other correct feature)
(ii) Sumit wants to write a code in Python to display all the details of the passengers
from the table flight in MySQL database, Travel. The table contains the
following attributes:
F_ code : Flight code (String)
Page 25/26
359
CBSE AISSCE 2024 Marking Scheme for Computer Science
(Series &RQPS Sub Code: 083 Q.P. Code 91) SET-4
F_name: Name of flight (String)
Source: Departure city of flight (String)
Destination: Destination city of flight (String)
Consider the following to establish connectivity between Python and MySQL:
● Username : root
● Password : airplane
● Host : localhost
DB=pm.connect(host="localhost",user="root",\
password="airplane",database="Travel")
MyCursor=DB.cursor()
MyCursor.execute("SELECT * FROM Flight ")
Rec=MyCursor.fetchall()
for R in Rec:
print (R)
OR
Any other correct variation of the code
Note:
Full 4 mark should be awarded if the examinee has mentioned that there is no
mention of the task in the question
Page 26/26
360
Answer keys
Chapter 1 : Python Revision Tour
Part A
PART B
361
3
a.
b.
5 (i) L1.insert(3,200)
(ii) message.endswith(‘.’)
Chapter 2:Functions
1. b 2. b 3. a 4. d 5. a 6. a 7. a 8. d
9. d 10. b 11. c 12. a 13. d 14. c 15. c 16. b
17. d 18. b 19. d 20. c 21. d 22. b 23. b 24. d
25. b 26. b 27. b 28. d 29. b 30. (i). b 30. (ii) b 30. (iii). c
31. (i). a 31. (ii) a 31. (iii) d 31.(iv) c 31 (v) a
362
32. None
33. 50 @
50 #
75 @
75 #
34. Inside func1: 10
Outside any function: 10 After
func2: 20
35. 10.0$20
36.
40. i. 65#70@
40. ii. 5#8#5#4#
41. 355
42.
43. i.
363
45. iii. 9
45. iv. 26
45. v. 30
45. vi. 1
46. -1
47. i. 3
47. ii. 33
32
53
47. iii. Hello, Anuj
None
47. iv. 5
48. 20#50@20
49. 10.0 Division Successful
You can't divide any number by Zero Division Successful
50. i. 17
4
17
19
19
50. ii. 0 @6 @7 @8 @9 @25 @11 @
0 @6 @7 @8 @9 @
0 @6 @7 @
50. iii. Hi
50. iv. 150
PART A
11. TRUE
364
12.
13.
15.
16. (c)
17. (c)
365
3. 12
4. 5
5. 2
6. 100
7. 12
8. 7
9. pickle.dump(tup1, myfile)
10. 3
11. i. Text file
ii. File.write(“ABC”)
12. i. Text file
ii. content = File.read() # Blank1
366
3. a. csv
b. ’w’or ’w+’ or ‘a’or ‘a+’
c. reader
d. close()
e. Arjun 123@456
Arunima aru@nima
Frieda myname@FRD
4. i. bin_file=open(“Cust_file.dat”,”wb”)
ii. if qty<10 :
iii. pickle.dump(c_detail,bin_file) #statement 3 break #statement 4
iv. bin_file.close() #statement 5
v. write_bin() #statement 6
5. i. pickle
ii. fout=open(“temp.dat”,”wb”)#statement 2
iii. rec=pickle.load(fin) #statement 3 pickle.dump(rec,fout)#statement 4
PART B
367
2.
3.
4.
368
5.
6.
369
COMPUTER NETWORK SOLUTIONS
Multiple Choice Questions
1. Star
2. The entire network becomes inoperative
3. Mesh
4. Bridges
5. Star
6. High installation cost
7. Star
8. The entire network becomes inoperative
9. Ring
10. Bus
11. Twisted-pair cable
12. Fiber-Optic Cable
13. Light Pulses
14. Shielded Twisted Pair (STP)
15. Twisted-Pair Cable
16. Wi-Fi
17. Coaxial cable
18. Fiber-Optic Cable
19. Twisted-pair Cable
20. Infrared Transmission
21. MAN (Metropolitan Area Network)
22. LAN (Local Area Network)
23. WLAN (Wireless Local Area Network)
24. PAN (Personal Area Network)
25. MAN (Metropolitan Area Network)
26. WAN (Wide Area Network)
27. WLAN (Wireless Local Area Network)
28. LAN (Local Area Network)
1. Network topology is how different parts of a computer network, like computers and cables, are
connected and arranged.
2. A star network topology is a type of network setup where all the devices (like computers) are
connected to a central device (such as a switch or hub), forming a shape like a star. All data
passes through this central device, which helps manage and control the network.
3. A bus topology is a type of network setup where all devices are connected to a single central
cable, called the "bus." Data is sent along this bus, and each device checks the data to see if it's
for them.
370
4. A point-to-point network is a simple type of network connection where two devices are directly
connected to each other with a dedicated link, allowing them to communicate without any
other devices interfering.
5. The most commonly used topology in Ethernet LANs (Local Area Networks) is the star topology.
6. The advantages of mesh topology in terms of reliability include:
a. Redundancy: Each device is connected to multiple other devices, so if one link fails,
data can still travel through alternate paths.
b. Fault Tolerance: The network can continue to operate smoothly even if some
connections fail, reducing the risk of complete network downtime.
c. Robustness: It is resilient against failures because each device has multiple connections,
ensuring consistent network performance and stability.
7. The topology commonly used in wireless networks is the mesh topology. In a wireless mesh
network, each node connects directly, dynamically, and non-hierarchically to as many other
nodes as possible, collaborating to route data efficiently.
8. The advantage of a bi-directional ring over a uni-directional ring is increased reliability and fault
tolerance. In a bi-directional ring, data can travel in both directions around the ring, so if there
is a break or failure in one direction, data can still be transmitted in the opposite direction. This
ensures continuous network operation and reduces the risk of network downtime.
9. The tree topology offers several advantages over the bus topology:
a. Scalability: Tree topology allows for the expansion of the network by adding more
branches or levels, whereas bus topology may become limited in scalability due to the
linear nature of the bus.
b. Fault Isolation: In tree topology, if one branch fails, it does not affect the entire
network. However, in bus topology, if the main bus line is damaged or faulty, the entire
network can be disrupted.
c. Performance: Tree topology can potentially offer better performance as data does not
have to contend with other devices on a shared bus, reducing the likelihood of data
collisions and improving overall network efficiency.
d. Organizational Structure: Tree topology can mirror organizational structures more
effectively, allowing for better management and organization of network resources,
whereas bus topology may not align as well with hierarchical structures.
Overall, the tree topology provides more flexibility, fault tolerance, and performance
advantages compared to the bus topology.
10. A hybrid topology combines two or more different basic network topologies into a single
network. For example, a common hybrid topology is a combination of star and bus topologies,
where smaller star networks are interconnected via a central bus backbone. This approach
allows for flexibility in designing networks to meet specific requirements, combining the
advantages of different topologies while mitigating their individual limitations. Hybrid
topologies are often used in larger networks where multiple types of connectivity are needed
to support diverse network requirements.
11. Transmission media are the physical pathways or mediums through which data is transmitted
from one location to another in a telecommunications or computer network. These media
facilitate the transmission of signals, electromagnetic waves, or light pulses carrying
information between devices connected to the network.
12. The different types of transmission media include:
a. Twisted Pair Cable
371
b. Coaxial Cable
c. Fiber Optic Cable
d. Wireless Transmission (e.g., Radio Waves, Microwaves, Infrared)
13. Twisted pair cables offer several advantages and drawbacks:
Advantages:
1. Cost-Effective: Twisted pair cables are relatively inexpensive compared to other types of
cables like fiber optics, making them a cost-effective choice for many networking
applications.
2. Flexibility: They are flexible and easy to install, making them suitable for various network
layouts and configurations.
3. Widely Available: Twisted pair cables are widely available and compatible with most
network devices, making them easy to procure and use.
4. Suitable for Short to Medium Distances: They are suitable for transmitting data over short
to medium distances, making them ideal for local area networks (LANs) and telephone
systems.
5. Resistance to Electromagnetic Interference (EMI): Twisted pair cables are less susceptible
to EMI compared to unshielded cables, especially when properly installed and shielded.
Drawbacks:
1. Limited Bandwidth: Twisted pair cables have limited bandwidth compared to fiber optic
cables, which can restrict the speed and amount of data that can be transmitted over long
distances.
2. Susceptible to Crosstalk: Crosstalk can occur when signals from adjacent pairs interfere
with each other, potentially degrading signal quality and causing data errors.
3. Limited Distance: Twisted pair cables have a limited transmission distance compared to
fiber optic cables, which may require additional equipment like repeaters to extend the
reach of the network.
4. Security Concerns: Twisted pair cables can be vulnerable to eavesdropping and
wiretapping if not adequately secured or encrypted, posing potential security risks to the
network.
5. Signal Degradation: Signal degradation can occur over long distances or in noisy
environments, leading to reduced signal quality and potential data loss.
14. The main drawbacks of coaxial cables include:
1. Limited Bandwidth: Coaxial cables have a limited bandwidth compared to fiber optic cables,
which can restrict the speed and amount of data that can be transmitted over long
distances.
2. Susceptibility to Signal Attenuation: Coaxial cables can experience signal attenuation,
especially over long distances or at higher frequencies, leading to signal degradation and
potential data loss.
3. Difficulty in Installation: Coaxial cables are thicker and less flexible than twisted pair cables,
making them more challenging to install, especially in tight spaces or over long distances.
4. Limited Transmission Distance: Coaxial cables have a limited transmission distance
compared to fiber-optic cables, which may require additional equipment like repeaters to
extend the reach of the network.
5. Vulnerability to Electromagnetic Interference (EMI): Coaxial cables can be susceptible to
EMI from external sources, such as power lines or electronic devices, which can degrade
signal quality and cause data errors.
372
6. Cost: Coaxial cables can be more expensive than twisted pair cables, especially for higher-
quality or specialized types, which can impact the overall cost of network installation and
maintenance.
15. Fiber optic cables have several advantages over coaxial cables such as higher bandwidth, faster
speeds. Longer distance, better signal quality, lightweight and thin, greater security and
durability.
16. Several devices use the Infra-Red technology. Some common devices include: remote controls,
IR blasters, security systems, healthcare devices, computers and peripherals, toys.
17. Guided transmission media offer more security as compared to un-guided transmission media
since they offer limited signal propagation, higher encryption, resistance to interference and
enhanced physical control over the signals.
18. Twisted pair cables, coaxial cables, fiber optic cables, Wi-Fi, Bluetooth, and Infra-Red
Communication (NFC) are commonly used transmission media for short distances.
19. Fiber optic cables, Microwaves, Satellite Communication, and Radio Waves are commonly used
transmission media for long distances.
20. Distance, Bandwidth requirement, cost, Installation and maintenance, environmental factors,
security, scalability, and application specific (mobility/fixed infrastructure) requirements,
Industry specific compliance are some important factors that influence the choice of
transmission media in a network.
21. A Local Area Network (LAN) is a network that connects computers and other devices within a
relatively small and specific geographic area, such as a home, office, or building.
22. A Personal Area Network (PAN) is a network that connects devices within the immediate
vicinity of a single user, typically within a range of a few meters. PANs are designed for personal
use.
23. A Metropolitan Area Network (MAN) is a network that connects multiple local area networks
(LANs) within a metropolitan area, such as a city or a large campus. MANs are designed to
extend the reach of a LAN, enabling efficient communication and resource sharing over a larger
geographic area than a LAN.
24. A Wide Area Network (WAN) is a telecommunications network that extends over a large
geographic area, often encompassing cities, countries, or even continents. WANs are used to
connect multiple smaller networks, such as local area networks (LANs) and metropolitan area
networks (MANs).
25. A Virtual Private Network (VPN) is a technology that creates a secure, encrypted connection
over a public network such as the internet. It allows users to access and transmit data securely
over an untrusted network as if they were directly connected to a private network.
26. Domain Name Service (DNS) is a hierarchical decentralized naming system for computers,
services, or any resource connected to the Internet or a private network. It translates human-
readable domain names (e.g., www.example.com) into numeric IP addresses (e.g., 192.0.2.1)
needed for locating and identifying devices and services on the network.
27. Web hosting refers to the service provided by companies or individuals to store and make
websites accessible on the internet. It involves renting space on a server where website files,
databases, and other resources are stored, allowing individuals and organizations to publish
their websites online. Web hosting providers offer various hosting plans and services to meet
the needs of different websites, ranging from small personal blogs to large e-commerce
platforms and corporate websites.
373
OR Web hosting is like renting space on a big computer called a server. This space is where all
the stuff needed for a website, like files and databases, is kept. Web hosting companies offer
different plans to suit different kinds of websites, whether they're small blogs or big online
stores. They help people and businesses put their websites on the internet so others can see
them.
28. Website: A website is a collection of related web pages and digital content that are typically
accessed through a web browser.
Web Link: A web link, also known as a hyperlink or URL (Uniform Resource Locator), is a
reference to a specific web page or resource on the internet.
Web Server: A web server is a computer system or software application that stores and
delivers web content to client devices over the internet.
29. Hypertext:
Hypertext is a system of organizing and presenting information in a non-linear format,
where text is interconnected through hyperlinks.
Characteristics:
o Allows users to navigate between different pieces of information by clicking on
hyperlinks embedded within the text.
o Provides a dynamic and interactive way to access and explore related content within a
document or across multiple documents.
o Enables non-linear reading and exploration, allowing users to choose their own path
through the information.
Example: In a hypertext document about programming languages, clicking on a hyperlink
within the text might lead you to additional information about a specific programming
language.
Hyperlink:
Definition: A hyperlink, also known as a link or web link, is a reference to a specific location or
resource on the internet that, when clicked, directs the user to that location or resource.
Characteristics:
o Consists of clickable text, an image, or another element that serves as a navigation cue.
o Typically appears as blue, underlined text in web browsers, although its appearance can
be customized using HTML or CSS.
o Can point to various types of resources, including web pages, images, documents,
videos, or other media.
Example: In a web page about travel destinations, clicking on a hyperlink labeled "Paris" might
take you to a webpage with information about the city of Paris.
30. The various protocols used over the internet are as follows
a. Internet Protocol (IP)
b. Transmission Control Protocol (TCP)
c. User Datagram Protocol (UDP)
d. Hypertext Transfer Protocol (HTTP)
e. Hypertext Transfer Protocol Secure (HTTPS)
f. File Transfer Protocol (FTP)
g. Simple Mail Transfer Protocol (SMTP)
h. Post Office Protocol (POP) and Internet Message Access Protocol (IMAP)
i. Domai Name System (DNS)
j. Dynamic Host Configuration Protocol (DHCP)
k. Secure Shell Protocol (SSH)
374
31. Simple Mail Transfer Protocol:
SMTP is a protocol used for sending email messages between email servers over the
internet. It defines the rules and procedures for how email messages are routed and
delivered to their intended recipients.
Post Office Protocol (POP):
POP is a protocol used by email clients to retrieve email messages from a remote email
server. It allows users to download email messages from their email server to their
local computer or device.
File Transfer Protocol (FTP):
FTP is a protocol used for transferring files between a client and a server on a network. It
provides a standardized way for users to upload, download, and manage files stored
on remote servers.
32. The term "WWW" stands for "World Wide Web". It refers to an information system on the
internet that allows users to access and interact with various resources, such as web pages,
documents, multimedia content, and applications.
33. XML stands for eXtensible Markup Language. It is a markup language that defines a set of rules
for encoding documents in a format that is both human-readable and machine-readable. XML
is designed to be self-descriptive, making it suitable for representing structured data in a wide
variety of applications and contexts.
34. HTML stands for Hypertext Markup Language. It is the standard markup language used for
creating and structuring documents on the World Wide Web. HTML provides a set of
predefined tags and elements that define the structure and content of web pages, allowing
developers to create interactive and visually appealing documents.
375
Case Study Based Questions
Question Answer
No.
1. a. Computer system
b. Both b and c
c. Hypertext Transfer Protocol
d. Domain name system
e. Client
f. Domain Name System
g. 32 bit
2. i. National Science Foundation Network
ii. Advanced Research Project Agency Network
iii. Interconnection of wide area networks
iv. Internet Service Provider
v. Digital subscriber line
vi. Hyperlink
3. 1. All of the above
2. Internet relay chat
3. IP
4. HSP
5. Communication between computers on a network
6. Session layer
7. Station
4. i. Blogging
ii. E-commerce websites
iii. Search engine
iv. X
v. WordPress
vi. E-mail
5. i. Spam
ii. [email protected]
iii. multipurpose internet mail extensions
iv. mail server
v. user agents
vi. network virtual terminal
6. a. All of the above
b. both is same every time whenever it displays and generates on demand by
a program or a request from browser
c. uniform resource locator
d. asynchronous java script and xml
e. scripting language
f. VBScript
g. sent from a website and stored in user’s web browser while a user is
browsing a website
7. 1. All of the above
2. B2C
3. Reinvention
376
4. B2C
5. Venture capital funds
6. Small products
7. Universal standards
8. 1. same as internet governance
2. individuals in society
3. Tax Deduction and Collection Account Number
4. Having the ability to access and contribute to forum topics
5. E-mail
9. 1. All of the above
2. All of the above
3. Search engine result pages
4. All of the above
5. Getting cached files
10. 1. Administrative Office
2. The suitable layout is
2. Switch
3. Admin, since it has the highest number of computers and workload.
4. Satellite Communication
5. Not required as the farthest office is the Hyderabad Office and it is
connected via satellite communication.
12. 1. Administrative building
2.
3. LAN
377
4. Satellite communication
5. Satellite communication is a type of wireless communication to connect
computers around the world. It is a type of WAN (Wide Area Network).
13. 1. Administrative office
2.
3. Switch
4. Bus topology, ethernet cable
14. a.
b. Admin
c. Switch can be placed in all the buildings easily, but, the repeater must be
placed in the Main building to connect with the Finance building as these
are farthest as compared to other buildings.
d. Coaxial cable must be used due to its low cost of installation and
maintenance, and Data Security.
15. 1. Circulation Unit
2.
3. Modem should be placed in the circulation unit, and the internet should be
provided to all the units via installing Sub-Modem in teachers and student’s
unit, thereby distributing using the ethernet LAN cable.
4. Coaxial Ethernet cable.
5. LAN should be established using the Coaxial cable as the range of LAN is up
to 100 meters and Coaxial cables provide reduced installation and
maintenance cost with comparatively high data security and durability in all
weather conditions.
16. a. The server must be placed in the technology unit for ease of maintenance.
b.
378
c. Switch can be installed using the Ethernet Coaxial Cables in a bi-directional
ring.
d. The repeater must be installed in the Law Block while establishing
connection with the HR block as the HR block is located at the farthest
distance and it needs the most accurate data for decision making.
e. WAN must be set-up using Satellite Communication due to long range
distance.
379
DBMS1 - ANSWERS DATABASE CONCEPT
4 Relational Model
380
· VARCHAR(n): Variable-length character string with maximum length of n
· TEXT Type : Variable-length character string with no specified maximum length
13 Clause in SQL
14 1. create database class12;
2. show databases;
3. use class12;
4. show tables;
5. create table student12(
student_id int,
student_name char(30),
age int,
phone int,
address varchar(50));
6. desc student12 or describe student12
7. insert into student12(1,’Rohit’,9874563210,25,’Delhi’);
8. insert into <table name> values (<value>, <value> , <value> …);
9. select * from student12;
381
10. drop table student12;
15 Constraints in SQL are a set of rules that are applied to the data in a relation/table.
Constraints are used to ensure the accuracy and reliability of the data.
Types of constraints:
1. Primary key
2. Unique
3. Not Null
4. Foreign Key
16 DDL commands are used to make any changes in the structure of the table/database.
These commands don’t change the data of the table.
Example: create table, alter table, drop table, create database, create view etc.
17 DML commands are used to make any changes in the data of the table.
Example: Insert, delete, update, select etc.
18 Aliasing in SQL
19 Drop table command is used to delete data as well as structure of a table, drop
command is used but Delete Command used to delete the existing rows in a table that
matches the condition.
20 Distinct clause
21 Where clause
22 Char
23 Primary Key
24 Candidate Key
25 Order by Clause
26 Like operator
27 Primary key constraints
28 NOT NULL Constraints
29 Alter table
30 having
382
13 D 26 C 39 B
1. SQL stands for structured query language, is a standard programming language used for
managing and manipulating relational databases.
2. DML is used for managing data within existing databases. DML commands are SELECT,
INSERT, UPDATE AND DELETE. DDL command is used for defining and modifying database
structures. DDL Commands are CREATE, ALTER AND DROP.
3. Datatype in SQL:
1. Numeric Type:
· INT: Integer type
· FLOAT: Floating-point number
· DECIMAL or NUMERIC: Fixed-point number
2. Character String Type:
· CHAR(n): Fixed-length character string with maximum length of n
· VARCHAR(n): Variable-length character string with maximum length of n
· TEXT Type: Variable-length character string with no specified maximum length
3. Data and Time Type:
· DATE: for date only
· TIME: for time only
· DATETIME or TIMESTAMP: for date and time combined
4. Other Data type:
· NULL: to represent a missing/unknown/empty value
· ENUM: An enumeration type for a set of predefined values
4. The WHERE statement in SQL is used to filter the results of a SELECT statement by
specifying one or more conditions. Having statement is used to filter the result set of group
by clause in select statement.
5. Primary Key is a unique identifier which identify unique record in a particular table. It must
contain unique values for each record. And Primary key attribute/column/field can’t be NULL.
A table can have only ONE primary key
6. Database table is a structured collection of data organized into rows and columns.
Database record in a single, complete set of related data items in a table, representing a single
entity. Each record is a row in a table which consists of one value for each column.
7. A Foreign key is a column or group of columns in a table that provides a link between two
tables. Foreign key are essential for defining relationships between tables in a relational
databases, which help in maintaining integrity and accuracy of data
383
8. Domain is a set of possible values or range of valid values or set of all unique values that
an attribute/column can hold.
9. Clause are built in functions which is use to deal with data inside the table that help SQL
to filter and analyses data quickly.
10. Aliasing in SQL is the process of assigning a nick name or a temporary name to a table or
column. We create aliases to make queries more readable and easier to use. Alias created
using as keyword. Creating aliases don’t change name of any table or column permanently.
12. Candidate key are those key which are eligible for primary key and can be used as primary
key in a table. After selecting primary key from candidate key, the remaining keys (which are
also eligible for primary key) are called Alternate Key.
Primary Key: Primary Key is a unique identifier which identify unique record in a particular
table.
Candidate Key: Candidate key are those key which are eligible for primary key and can be
used as primary key in a table.
384
Alternate Key: After selecting primary key from candidate key, the remaining keys (which are
also eligible for primary key) are called Alternate Key.
15. Constraints in SQL are set of rules that are applied to the data in a relation/table.
Constraints are used to ensure the accuracy and reliability of the data.
Types of constraints:
1. Primary key
2. Unique
3. Not Null
4. Foreign Key
16. Like operator is used to match a pattern. The like operator is used with were clause. Like
operator has 2 wildcards:
1. _ (underscore): It is used to match one character.
2. % (percentage sign): It is used to match zero or more characters.
18. Equi Join- It joins the tables based on one common column. However, final result will
consists of common column from both the tables.
Natural Join-It joins the tables based on one common column. However, final result will
consists of common column only once.
19. Aggregate functions are those functions that operates on a list of values and returns a
single digit value or we can summarize the data using aggregate functions.
Max(): It is used to find out the maximum value from a column.
Min(): It is used to find out the minimum value from a column.
20. A cursor is SQL is database object used to retrieve, manipulate and navigate through a
result set tow by row. It is a pointer or iterator which points towards the resultset of the SQL
query. Whenever a SQL query runs, It give the entire result set in one go.
21. Commit(): Whenever we perform update, delete or insert query, commit() function must
be run before closing the connection.
22. Cartesian product gives all possible combinations from more than one table. It combines
every row from one table with every row from another table.
Total number of row after applying cartesian product is 90.
23. This is a DDL command and it is used to modify a table. This command can be used to
add, delete, or modify columns, add or drop constraints etc.
385
24. fetchall(): It returns all the records from resultset. Each individual record will be in the
form of a tuple whereas the entire resultset will be in the form of a list.
Syntax: <variable name>=<cursor>.fetchall()
fetchmany(): It returns n number of records from resultset in the form of a list where each
individual record is in the form of a tuple. It returns empty tuple, if no more records are there.
Syntax: <variable name>=<cursor>.fetchmany(n)
25. In SQL, Define aggregate function and write the name of the aggregate function which
will display the cardinality of a table.
Aggregate functions are those functions that operates on a list of values and returns a single
digit value or we can summarize the data using aggregate functions.
count(*) is often used to count all rows in a table.
Example: select count(*) as cardinality from employees;
1. create table Employee (Emp_ID int(20) primary key, Emp_Name char(100) not null, salary int(20)
not null, Department char(30), Age int(15) not null, Address varchar(200) unique);
2. (i) create table Student (Student_ID varchar(20) primary key, Student_Name char(80) not null,
Gender char(20) not null, Class varchar(30), Age int(20) not null, Address varchar(150) unique,
Phone int(15) not null unique);
(ii) create table Activities (Student_ID varchar(20), Activity_Name char(80) not null, Position
char(30) not null, foreign key(Student_ID) references Student(Student_ID));
3. (a) Degree – 5 and Cardinality – 6
(b) MID
(c) insert into PHARMA values (MID ,MNAME, PRICE, EXPIRY) values (‘M7’, ’SUCRALFATE’, 17,
’2022-03-20’);
(d) IV
(e) I
4. RAVI KUMAR
386
NISHANT JAIN
DEEPAK PRAKASH
6. (1) E_NO
(2) D_CODE
(3) Degree – 7 and Cardinality – 6
(4) Degree – 3 and Cardinality – 5
(5) (a) insert into employee values (1006, ’Rahul’, ‘2019-11-06’, ‘1992-01-04’, ‘MALE’, ‘D003’,
156000);
(b) insert into employee values (1008, ’Sonam’, ‘2022-01-06’, ‘1991-04-06’, ‘FEMALE’
, ‘D005’, 167000);
(6) select name from employee where name like ‘R%’;
(7) select name from employee where name like ‘%n%’;
(8) select name from employee where name like ‘_ _ _ _ _’;
(9) select d_name, city from dept where d_name like ‘%G’ and city=’delhi’;
(10) select max(salary) from employee;
(11) delete from employee where age<25;
(12) update employee set salary=230000 where e_no=1004;
(13) alter table employee modify dob date after name;
(14) alter table employee add column mobile int(20) after d_code;
(15) update employee set salary=300000 where age is null;
(16) update employee set salary=salary+30000;
(17) select avg(salary) from employee;
(18) select name from employee where salary>200000 order by name;
(19) select d_name, avg(salary) from employee, dept group by d_name;
(20) select count(d_name) from dept;
(21) delete from employee where d_code != ’d001’;
(22) select e_no, name, salary from employee where city not in (‘delhi’);
(23) alter table dept change column city d_city char(20);
(24) drop table employee;
(25) alter table dept drop column d_name;
387
(i)
(ii)
(iii)
(iv)
(v)
(vi)
388
(vii)
(viii)
(ix)
(x)
(xi)
(xii)
389
(xiii)
(xiv)
(xv)
8. Queries
(i)
(ii)
(iii)
(iv)
(v)
390
(vi)
(vii)
(viii)
(ix)
(x)
9. Statement 1 = mysql.connector
Statement 2 = a.cursor()
Statement 3 = select * from employee where city not in (‘delhi’);
Statement 4 = b.execute(query)
Statement 5 = print(z)
10. Statement 1 = mysql.connector
Statement 2 = mysql.connect
Statement 3 = a.cursor()
Statement 4 = delete from employee where e_id=’a101’ and e_name like ‘D%’;
Statement 5 = b.commit()
391
11.
12.
392