Notes For All Chapters With Answer
Notes For All Chapters With Answer
2. Keywords: Keywords are the reserved words and have special meaning for Python
Interpreters. Each keyword can be used only for that purpose which it has been
assigned. Examples: and, while, del, with, True, None, False, return, try etc.
3. Identifiers: These are the names given to variables, objects, classes or functions etc.
there are some predefined rules for forming identifiers which should be followed
else the program will raise Syntax Error.
2|Page
4. Literals: The data items that have a fixed value are called Literals. If a data item holds
numeric values it will be known as Numeric Literal, if it contains String values it will
be known as String Literal and so on. It means the type of value stored by the data
item will decide the type of Literal. Python has one special literal which is None to
indicate absence of value.
5. Operators: These are the symbols that perform specific operations on some
variables. Operators operate on operands. Some operators require two operands
and some require only one operand to operate. The operator precedence in Python
is as follows:
NOTE: When we compare two variables pointing to same value, then both Equality
(==) and identity (is) will return True. But when same value is assigned to different
objects, then == operator will return True and is operator will return False.
6. Punctuators: These are the symbols that are used to organize sentence structure in
programming languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () , .
7. Variables: In Python, variables are not storage containers like other programming
languages. These are the temporary memory locations used to store values which
will be used in the program further. Each time we assign a new value to a variable it
will point to a new memory location where the assigned value is stored. In Python
we do not specify the size and type of variable, besides these are decided as per the
value we assign to that variable.
8. Data Type: It specifies the type of data we will store in the variable according to
which memory will be allocated to that variable and it will also specify the type of
operations that can be performed on that variable. Examples: integer, string, float,
3|Page
list etc.
4|Page
9. Dynamic Typing: It means that it will be decided at the run time that which type of
value the variable will store. It is also called implicit conversion. For example,
Here, we need not to specify the type of value a will store besides we can assign any
type of value to a directly. Similarly, the data type of c will be decided at run time on
the basis of value of a and b.
10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly
by using some built-in functions. Here, we can say that we force the variable by
applying a built-in function to change the data type and it is not done at run time.
Some common type casting functions are int(), float(), str(), list(), tuple(), dict() etc.
5|Page
Above data types are classified in two basic categories: Mutable data types and Immutable
data types. Mutable data types are those data types whose value can be changed without
creating a new object. It means mutable data types hold a specific memory location and
changes are made directly to that memory location. Immutable data types are those data
types whose value cannot be changed after they are created. It means that if we make any
change in the immutable data object then it will be assigned a new memory location.
1. In Numeric data types, Integers allow storing whole numbers only which can be
positive or negative. Floating point numbers are used for storing numbers having
fractional parts like temperature, area etc. In Python, Floating point numbers
represent double precision i.e. 15-digit precision. Complex numbers are stored in
python in the form of A + Bj where A is the real part and B is the imaginary part of
complex numbers.
3. Boolean allows to store only two values True and False where True means 1 and
False means 0 internally.
A. STRING:
● In Python, string is a sequence having Unicode characters. Any value
written/assigned in “ “ or ‘ ‘ is considered as a string in python.
● Each character is at a particular place called Index having starting value 0 if
traversing forward. Indexing can also be done in backward direction starting from
the last element/character of string where starting value will be -1 in backward
direction.
● Strings are immutable.
● 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 string from the main string using unique
index positions starting from 0. In slicing we can specify start, stop and step
values to extract substring from the given string.
6|Page
B. LIST:
● Lists can hold multiple elements of the same or different data types.
● Lists are mutable in nature which means the values can be updated without
assigning a new memory location. It is denoted by square brackets [].
● ‘for’ loop can be used to traverse a list.
● 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 ‘*’.
● Slicing means extracting a part of list. Slicing in a list is done in same way as in
String.
C. TUPLE:
● Tuples can also hold multiple elements of the same or different data types like
lists but tuples are immutable in nature. 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 same way as Strings using ‘for’ loop.
● Slicing, Concatenation (Replication) and Joining operations can also be
performed on Tuples in same way as of Strings.
7|Page
WIDELY USED BUILT-IN FUNCTIONS IN PYTHON:
STRING FUNCTIONS:
len (string) It returns the number of characters in any string including spaces.
capitalize() It is used to convert the first letter of sentences in capital letter.
title() It is used to convert first letter of every word in string in capital letters.
upper() It is used to convert the entire string in capital case letters.
lower() It is used to convert entire string in small case letters.
count(substring, It is used to find the number of occurrences of substring in a string.
[start], [end]) We can also specify starting and ending index to specify a range for
searching substring.
find(substring, This function returns the starting index position of substring in the
[start],[end]) given string. Like count(), we can specify the range for searching using
starting and ending index. It returns -1 if substring not found.
index(substring) It returns the starting index position of substring. If substring not
found then it will return an error “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.
islower() It returns True if all the elements in string are in lower case, otherwise
returns False.
isupper() It returns True if all the elements in string are in upper case, otherwise
returns False.
isspace() It returns True if all the elements in string are spaces, otherwise
returns False.
isalpha() It returns True if all the elements in string are alphabets, otherwise
returns False.
isdigit() It returns True if all the elements in string are digits, otherwise returns
False.
split([sep]) This function is used to split the string based on 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.
partition(sep) It divides the string in 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 2nd element of tuple in the output.
replace(old, It is used to replace old substring inside the string with a new value.
new)
strip([chars]) It returns a copy of 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 is given then all possible
combination of given characters will be checked and removed.
lstrip([chars]) It returns a copy of string after removing leading white spaces. If chars
value is given then characters will be removed.
rstrip([chars]) It returns a copy of string after removing trailing white spaces. If chars
value is given then characters will be removed.
8|Page
LIST FUNCTIONS:
index() Used to get the index of first matched item from the list. It returns
index value of item to search. If item not found, it will return
ValueError: n is not in the list.
append() Used to add items to the end of the list. It will add the new item but not
return any value
extend() Used for adding multiple items. With extend we can add multiple
elements but only in form of a list to any list. Even if we want to add
single element it will be passed as an element of a list.
insert() Used to add elements to list at position of our choice i.e. we can add
new element anywhere in the list.
pop() Used to remove item from list. It raises an exception if the list is already
empty. By default, last item will be deleted from list. If index is provided
then the given indexed value will be deleted.
remove() Used to remove an element when index is not known and we want to
delete by provided the element value itself. It will remove first
occurrence of given item from list and return error if there is no such
item in the list. It will not return any value.
clear() Use to remove all the items of a list at once and list will become empty.
TUPLE FUNCTIONS:
len() Returns number of elements in a tuple
index() Returns index value of given element in the tuple. It item doesn’t exist,
it will raise ValueError exception.
count() It returns the number of occurrences of the item passed as an
argument.
If not found, it returns Zero.
9|Page
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 reverse argument
as True to sort in decreasing order.
Dictionary Functions:
clear() Used to remove all items from dictionary
get() Used to access the value of given key, if key not found it raises an
exception.
items() Used to return all the items of a dictionary in form of tuples.
keys() Used to return all the keys in the dictionary as a sequence of keys.
values() Used to return all the values in the dictionary as a sequence of values.
update() Merges the key:value pair from the new dictionary into 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.
fromkeys() Returns new dictionary with the given set of elements as the keys of the
dictionary.
copy() It will create a copy of dictionary.
popitem() Used to remove the last added dictionary item (key:value pair)
max() Used to return highest value in dictionary, this will work only if all the
values in dictionary are of numeric type.
min() Used to return lowest value in dictionary, this will work only if all the
values in dictionary are of numeric type.
sorted() Used to sort the key:value pair of dictionary in either ascending or
descending order based on the keys.
Statements in Python:
Instructions given to computer to perform any task are called Statements. In Python, we
have 3 type 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 pass keyword.
Whenever pass is encountered, python interpreter will do nothing and control will
move to the
next statement in 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 has a Header which begins with a
10 | P a g
e
keyword and ends with colon (:). There can be at least one or more statements in the
body of the compound statement, all indented at same level.
10 | P a g e
for loop in python is used when we know the number of iterations.
for loop is used to create loop where we are working on sequence data types.
To repeat the loop n number of times in for loop we use range function in which we
can specify lower limit and upper limit.
range function will generate set of values from lower limit to upper limit. We can
also specify the step value which is +1 by default.
Step value can be in -ve also to generate set of numbers in reverse orders.
while loop in python is also called as entry-controlled loop in which entry is loop is
allowed only if the condition is true.
There are 4 main elements of while loop:
● Initialization: In while loop, we cannot use a variable in test condition without
initializing it with a starting value. So, we will specify the starting value to the
variable to be used in loop.
● Test Condition: We will specify a test condition in the header of the loop. If this
condition will be True then only the body of the loop will be executed else the
loop will not get executed at all.
● Body of loop: We will write the statements to be executed if the test condition
will be True.
● Update Statement: In while loop, we have to increase and decrease the value of
variable used in test condition else the loop will result in infinite loop.
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 next iteration..
11 | P a g e
MULTIPLE CHOICE QUESTION
1 Find the invalid identifier from the following
a) None
b) address
c) Name
d) pass
9 One of the following statements will raise error. Identify the statement that will
raise the error.
12 | P a g e
a)
b)
c)
d) None of above will raise error
14 Which of the following operator cannot be used with string data type?
a) +
b) In
c) *
d) /
15 Consider a tuple tup1 = (10, 15, 25, and 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))
13 | P a g e
c) .py
d) .p
17 Which of the following symbol is used in Python for single line comment?
a) /
b) /*
c) //
d) #
14 | P a g e
24 Identify the output of the following Python statements.
x=2
while x < 9:
print(x, end='')
x=x+1
a) 12345678
b) 123456789
c) 2345678
d) 23456789
15 | P a g e
30 Which of the following will delete key-value pair for key = “Red” from a dictionary
D1?
a) delete D1("Red")
b) del D1["Red"]
c) del.D1["Red"]
d) D1.del["Red"]
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?
name="ComputerSciencewithPython"
print(name[3:10])
34 Which of the following statement(s) would give an error during 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:
pride="#G20 Presidency"
print(pride[-2:2:-2])
a) ndsr
b) ceieP0
c) ceieP
d) yndsr
16 | P a g e
Write the output of:
print (Listofnames [-1:-4:-1])
a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is –Fun
42 Which of the following statement(s) would give an error after executing the
following code?
Stud={"Murugan":100,"Mithu":95} # Statement 1
print (Stud [95]) # Statement 2
Stud ["Murugan"]=99 # Statement 3
print (Stud.pop()) # Statement 4
17 | P a g e
print (Stud) # Statement 5
a) Statement 2
b) Statement 4
c) Statement 3
d) Statements 2 and 4
a) False
b) True
c) Error
d) None
18 | P a g e
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
Weightage : 2 marks
1 Rewrite the following code in python after removing all syntax error(s). Underline
each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
2 Rewrite the following code after removing all syntax error(s) and underline each
correction done:
Runs=(10,5,0,2,4,3)
for I in Runs:
if I=0:
print(Maiden Over)
else:
print(Not Maiden)
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 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.
19 | P a g e
Weightage : 3 marks
1 Find the output of the following code:
Name="PythoN3.1"
R=""
for x in range(len(Name)):
if Name[x].isupper():
R=R+Name[x].lower()
elif Name[x].islower():
R=R+Name[x].upper()
elif Name[x].isdigit():
R=R+Name[x-1]
else:
R=R+"#"
print(R)
Programming Practice
1 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)
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
20 | P a g e
Data of the list
Arr= [ 10,20,30,40,12,11],
n=2
Output:
Arr = [30,40,12,11,10,20]
21 | P a g e
Topics to be covered
1.Introduction
2.Types of Functions
3.Create User Defined
Function 4.Arguments And
Parameters
5.Default Parameters
6.Positional Parameters
7.Function Returning Values
8.Flow of Execution
9.Scope of Variable
22 | P a g e
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 actually performs the specified actions with the indicated
parameters
23 | P a g e
● Actual Parameters (Arguments) are values supplied to the function when it is
invoked/called
● Formal Parameters are variables declared by the function that get values
when the function is called.
Example 1:
Observe the following code:
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:
“first call to function “ passed in first call
“second call to function” passed in second call
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.
24 | P a g e
The basic syntax for using the `return` statement is as follows:
3. Returning None:
If a function doesn't have a `return` statement or has a `return` statement
without any value, it implicitly returns `None`.
`None` is a special constant in Python that represents the absence of a value.
25 | P a g e
4. Early Exit with Return:
You can use the `return` statement to exit a function early if certain conditions
are met. This is useful when you want to terminate the function before
reaching the end.
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:
● Variables defined outside of any function or block have a global scope.
● They are accessible from anywhere in the code, including inside functions.
● To create a global variable, you define it at the top level of your Python script
or module.
Local Scope:
● Variables defined inside a function have a 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.
26 | P a g e
Points to be noted:
● When local variable and global variable have different names: global
variable can be accessed inside the function
● When local and global variable have same name : priority is given to local
copy of variable
Lifetime of a variable:
The lifetime of a variable in Python depends on its scope. Global variables persist
throughout the program's execution, local variables within functions exist only during
the function's execution.
Study the following programs:
Example 1:
27 | P a g e
Example 2:
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.
28 | P a g e
Output:
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
from within a function, you must use the global keyword to specify that you want to
work with the global variable instead.
Here's the basic syntax for using the global keyword:
For example:
29 | P a g e
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.
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:
30 | P a g e
● 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. Study the following examples:
Example 1:
31 | P a g e
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:
32 | P a g e
Example 2:
random module
● The random module in Python is another built-in module that provides
functions for generating random numbers, 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:
● random.random(): Generates a random float number in the range [0.0, 1.0).
● random.uniform(a, b): Generates a random float number in the range [a, b).
● random.randint(a, b): Generates a random integer in the range [a, b]
(inclusive).
● random.choice(sequence): Picks a random element from a sequence (list,
tuple, string, etc.).
● random.shuffle(sequence): Shuffles the elements of a sequence randomly (in-
place).
Example 1:
What is the possible outcome/s of following code?
Possible options:
a) green
b) yellow
33 | P a g e
c) blue
d) orange
Solution:
Here, the possible values for variable random-sample are 3, 4 and 5. Hence, the
possible Outputs of above code are b) Yellow and d) orange.
Example 2:
What are the possible output/s for the following code?
Output Options:
i. 29: 26:25 :28 : ii. 24: 28:25:26:
iii. 29: 26:24 :28 : iv. 29: 26:25:26:
Solution:
Option iv
Example 3:
What are the possible outcome/s for the following code:
Output Options:
i. 103#102#101#100# ii. 100#101#102#103#
iii. 100#101#102#103#104# iv. 4#103#102#101#100#
Solution:
Option i and option iv
34 | P a g e
1. What will be the output of the following code?
a) 10
b) 30
c) error
d) 20
2. Name the Python Library modules which need to be imported to invoke the
following functions:
a) sin()
b) randint()
35 | P a g e
8. The values being passed through a function call statements are called
a) Actual parameter
b) Formal parameter
c) default parameter
d) None of these
a) global a
b) global b=100
c) global b
d) global a=100
13. What will be the output?
36 | P a g e
a) 5
b) 6
c) 4
d) This code will raise an error.
14. A function is defined as below, the function call parameters can be:
a) Two tuples
b) Two numbers
c) One number
d) All of the above
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.
a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
17. What will be the output of the Python code?
>>> def testify(a,b):
return a-b
>>> sum=testify(22,55)
>>> sum+30
a) 33
b) -33
c) 3
37 | P a g e
d) -3
21. Look at the function definition and the function call and determine the correct
output
>>> def test(a):
if(a>10):
a += 10
if(a>20):
a += 20
if(a>30):
38 | P a g e
a +=30
print(a)
>>> test(11)
a) 21
b) 72
c) 61
d) 71
a) [1, 2, 3, 4, 5, 6]
b) [100, 2, 3, 4, 5, 6]
c) [100, 2, 3, 4, 5]
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.
24. 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.
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
39 | P a g e
25. What will be the output of the following Python
code? def add (num1, num2):
sum = num1 + num2
sum = add(20,30)
print(sum)
26. Find and write the output of following python code:
def Alter(M,N=45):
M = M+N
N = M-N
print(M,"@",)
return M
A=Alter(20,30)
print(A,"#")
B=Alter(30)
print(B,"#")
27. 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#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
40 | P a g e
29. Predict output:
30. Rewrite the following code after removing the syntactical errors (if any).
Underline each correction.
a) Delhi#Mumbai#Chennai#Kolkata#
b) Mumbai#Chennai#Kolkata#Mumbai#
c) Mumbai# Mumbai #Mumbai # Delhi#
d) Mumbai# Mumbai #Chennai # Mumbai
41 | P a g e
34. What will be the output of the following code?
i. ii.
42 | P a g e
Display('Fun@Python3.0')
38. Find and write the output of the following python code:
I ii
39. What are the possible outcome/(s) for the following code.Also specify the
maximum and minimum value of R when K is assigned value as 2:
a) Stop # Wait # Go
b) Wait # Stop #
c) Go # Wait #
d) Go # Stop #
43 | P a g e
41. Explain the positional parameters in Python function with the help of
suitable example.
42. Predict the output of following:
i. ii.
iii. iv.
v vi
44. What possible outputs(s) will be obtained when the following code is
executed?
Options:
a) RED* b) WHITE*
WHITE* BLACK*
BLACK*
c) WHITE* WHITE* d) YELLOW*
BLACK* BLACK* WHITE*WHITE*
BLACK* BLACK* BLACK*
44 | P a g e
45. 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 BEGIN and
END.
a) 60#35#
b) 60#35#70#50#
c) 35#70#50#
d) 40#55#60#
46. 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.
a) 10#40#70#
b) 30#40#50#
c) 50#60#70#
d) 40#50#70#
47. What are the possible outcome/s for the following code:
Options:
a) 34:31:30:33:
b) 29:33:30:31:
c) 34:31:30:31:
45 | P a g e
d) 34:31:29:33:
46 | P a g e
48. What are the possible outcome/s :
1 Guess=65
for I in range(1,5):
New=Guess+random.randint(0,I)
print(chr(New),end=' ')
Output Options:
a) A B B C
b) A C B A
c) B C D A
d) C A B D
Output Options :
a) 25
b) 34
c) 20
d) None of the above
Output Options :
a) 99
b) 94
c) 96
d) None of the above
4 Disp=22
Rnd=random.randint(0,Disp)+15
N=1
for I in range(3,Rnd,4):
print(N,end=" ")
N+=1
print()
Output Options:
a) 1
b) 1 2 3 4
c) 1 2
d) 1 2 3
47 | P a g e
5 Area=["NORTH","SOUTH","EAST","WEST"]
for I in range(3):
ToGo=random.randint(0,1) + 1
print(Area[ToGo],end=":")
print()
Output Options:
a) SOUTH : EAST : SOUTH :
b) NORTH : SOUTH : EAST :
c) SOUTH : EAST : WEST :
d) SOUTH : EAST : EAST :
6 MIN = 25
SCORE = 10
for i in range (1,5):
Num = MIN + random.randint(0,SCORE)
print(Num,end=":")
SCORE-=1;
print()
Output Options:
a) 34:31:30:33:
b) 29:33:30:31:
c) 34:31:30:31:
d) 34:31:29:33:
49. Ms. Sana wants to increase the value of variable x by 1 through function
modify(). However this code raises error .Help sana to rectify the code:
i. ii.
48 | P a g e
iii. iv.
i. ii.
iii. iv.
49 | P a g e
54. Predict output:
i. ii.
iii. iv.
Practical 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.
410 | P a g
e
Topics to be covered
Introduction
Types of errors
Handling Exceptions Using Try – Except – Finally
Blocks
50 | P a g e
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.
EXCEPTIONS:
11. Run time errors are known as Exceptions.
12. When an Exception is generated, the program execution is stopped.
13. Removing errors from a code is referred to as EXCEPTION HANDLING.
14. Commonly occurring exceptions are usually defined in the Interpreter. These are
known as Built-in Exceptions.
51 | P a g e
Some Built-in Exceptions are listed as 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: p = a*b/c then it will result
in ‘NameError’ when one or more variables are not assigned values.
TypeError It is raised when variables used in any expression have values of
different data types. For example: p=(a+b)/c then it will result in
‘TypeError’ when the variables a, b and c are of different data types.
Value Error It is raised when given value of a variable is of right data type but not
appropriate according to the expression.
IOError It is raised when the file specified in a program statement cannot be
opened.
IndexError It is raised when index of a sequence is out of the range.
KeyError It is raised when a key doesn’t exist or not found in a dictionary.
EXCEPTION HANDLING:
Every exception has to be handled by the programmer for 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.
52 | P a g e
STEPS FOR EXCEPTION HANDLING:
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 try-except-finally
block. While writing a code, programmer might doubt a particular part of code to raise an
exception. Such suspicious lines of code are considered inside a try block which will always
be followed by an except block. The code to handle every possible exception, that may raise
in try block, will be written inside the except block.
If no exception occurred during execution of program, the program produces 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:
53 | P a g e
The output will be:
Example 2:
In above example, the user entered a wrong value that raised ValueError. We can handle
this exception by using ValueError exception.
Result:
Example 1:
54 | P a g e
The output will be:
Example 2:
Default exception messages can also be displayed when we are not handling exceptions by
name.
55 | P a g e
The output will be:
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 exceptions will be
raised in the try block. But if there is no error then except blocks will not be executed. In this
case, else clause will be executed.
56 | P a g e
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 finally block, it should always be placed at the end of the clause i.e. after all except blocks and
the else block.
57 | P a g e
Exercise
1 In a try-except block, can there be multiple 'except' clauses?
a) No, there can be only one 'except' clause.
b) Yes, but only if the exceptions are of the same type.
c) Yes, it allows handling different exceptions separately.
d) No, 'except' clauses are not allowed in a try-except block.
a) Division by zero!
b) Arithmetic error occurred!
c) No error!
d) This code will raise a syntax error.
58 | P a g e
b) KeyError
c) CustomError
d) IndexError
8 Assertion (A): In Python, the "try" block is used to enclose code that might raise an
exception.
Reasoning (R): The "try" block is where the program attempts to execute code
that might result in an exception. If an exception occurs, it is handled in the
corresponding "except" block.
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
10 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
11 Code snippet:
12 State whether the following statement is True or False: An exception may be raised
even if the program is syntactically correct.
13 What will be the output of the following code if the input is “e”:
59 | P a g e
try:
value = int("abc")
result = 10 / 0
except ValueError:
print("Error: Invalid value conversion")
except ZeroDivisionError:
print("Error: Division by zero")
14 What will be the output of the following code if the input is:
i. 2 ii. 2.2
try:
num = int(input("Enter a number: "))
except ValueError:
print("Error: Invalid input")
else:
print("Entered number: ",num)
17 Code snippet:
60 | P a g e
b) The user enters "5" for the first number and "0" for the second number.
c) The user enters "abc" for both numbers.
19 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')
2 Build 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.
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.
61 | P a g e
Topics to be covered
1.Introduction
2.Types of files
3.Access specifiers in the file
4.File object methods seek() and tell()
5.Text files and its methods
6.Binary file and its methods
7.CSV files and its methods
8.Absolute and Relative path
62 | P a g e
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. Read/Write
3. Close File
Open Files: open( ) function is used to open files in python.
There are two ways to open files in python:
1. file_object = open(“file name”, “ access specifier”)
a. i.e. f=open(“test.txt”,”r”) #here our test file exists in the same directory
of python.
b. i.e.
f=open(r”C:\Users\anujd\AppData\Local\Programs\Python\Python311\test.t
xt”,”r”)
Use ‘r’ before path indicates the data within quotes will be read as raw string
and no special meaning attached with any character.
Or
f=open(”C:\\Users\\anujd\\AppData\\Local\\Programs\\Python\\Python311\
\test.txt”,”r”)
The slash in the path has to be doubled.
63 | P a g e
b. i.e. with
open(r”C:\Users\anujd\AppData\Local\Programs\Python\Python311\test.txt
”,”r”) as f:
Or
with
open(”C:\\Users\\anujd\\AppData\\Local\\Programs\\Python\\Python311\\t
est.txt”,”r”) as f:
c. In this there is no need to close the file. It will automatically close the file.
a. file_object.close( )
b. i.e. f.close( )
64 | P a g e
a Ab a The a mode opens the file for End of File
appending. In this the new content is
added after the existing content. If the
file does not exist, it creates the new
file.
a+ ab+ The a+ mode opens the file for both End of File
appending and reading. In this the new
content is added after the existing
content. If the file does not exist, it is
created.
Default mode for file opening in “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.
65 | P a g e
I.e. method takes no parameters and
returns an integer value. Initially the
position=f.tell( )
file pointer points to the beginning
Here, position will hold the integer value of the of the file(if not opened in append
file pointer returned by tell function. mode). So, the initial value of tell()
is zero.
f is the file handle.
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
read( ) : It is used in text files to read a specified number of data bytes from the file. It
returns the result in the form of a string.
Syntax: file_object.read( )
66 | P a g e
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.
f.readline( ) #it will read one complete line in one go.
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.
File Content
Code Output
67 | P a g e
Result is in the form of a list.
68 | P a g e
Tips on writing text file code in exam:
● Let the file name be “abc.txt”.
● Read the question carefully and find out what has to be read from the
file. Follow the below flow chart to write the code.
69 | P a g e
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.
70 | P a g e
Writing data into Files
If the file doesn’t exist then it will create the file.
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 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
71 | P a g e
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
72 | P a g e
Output
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:
73 | P a g e
74 | P a g e
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 and development.”
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’.
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.
75 | P a g e
4. pickle module is used for working with binary files
a. import pickle
5. File extension will be .dat
6. There is no delimiter to end the file.
76 | P a g e
File Content
77 | P a g e
Question: Write a menu based program in python which contain student details in binary file and shou
Writing student details.
Display all students’ details
Search particular student details
Update any student details
Delete any student details
Exit
78 | P a g e
79 | P a g e
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
a. import csv
3. File extension for csv file will be .csv
4. CSV module provides two main classes for working with csv files are:
80 | P a g e
a. reader
b. writer
5. CSV reader object can be used to iterate through the rows of the CSV file.
6. CSV writer object that can be used to write row(s) to the CSV file.
a. writerow(): This method is used to write a single row to the CSV file.
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.
1. Reader Function:
a. For reading data from csv file we require csv. reader( ) function.
2. Writer Function:
a. For writing data to the csv file we take a file object as input and write the
data into the file.
b. writerow( ): It writes a single row of data to the CSV file.
c. writerows( ): It writes a list of rows of data to the CSV file.
81 | P a g e
Code: Output in IDLE:
82 | P a g e
READING FROM CSV FILES
File Content:
83 | P a g e
84 | P a g e
Questions
1. 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)
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
4. If the csv file 'item.csv' has a header and 3 records in 3 rows and we want to display only
the header after opening the file with open() function, we should write
a). print(file.readlines())
b). print(file.read())
c) print(file.readline())
d). print(file.header())
5. 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()
7. 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)
8. myfile.txt is a file stored in the working directory. Total number of characters including
spaces are 106 and there are 5 lines. What will be the output of len(file.readlines())
after the file was opened as file=open('myfile.txt')
a). 4 b). 106 c). 5 d). 1
85 | P a g e
c. if we try to write on a text file that does not exist, no error occurs.
d. if we try to write on a text file that does not exist, the file gets Created.
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()
a). String b). Tuple c). List d). None of the above
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. 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
13. 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
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.
i. myfile = open('student.txt','rb')
ii. myfile = open('student.txt','w')
iii. myfile = open('student.txt','r')
iv. myfile = open('student.txt')
86 | P a g e
a). only i b). both i and iv c). both iii and iv d). both i and iii
17. Which of the following statement 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 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()
19. Which of the following statement 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
22. Which of the following character acts as default delimiter in a csv file?
a) (colon) : b) (hyphen) - c) (comma) , d) (vertical line) |
87 | P a g e
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 statement 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 and returns its new
position?
a) flush() b) tell() c) seek() d) offset()
myfile = open("Myfile.txt")
data = myfile.readlines()
print(len(data))
myfile.close()
a) 3 b) 4 c) 5 d) 6
29. 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()
31. If the csv file 'item.csv' has a header and 3 records in 3 rows and we want to display only
the header after opening the file with open() function, we should write
a). print(file.readlines())
b). print(file.read())
c). print(file.readline())
d). print(file.header())
89 | P a g e
e) Write the output he will obtain while executing Line 5.
35. Roshni 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.
36. Rohit, a student of class 12, is learning CSV File Module in Python. During the
examination, he has been assigned an incomplete python code (shown below)
to create a CSV File 'Student.csv' (content shown below). Help him in
completing the code which creates the desired CSV File.
90 | P a g e
37. Write the definition of a function Change Gender() in Python, which reads the contents
of a text file "BIOPIC. TXT" and displays the content of the file with every occurrence of
the word 'he replaced by 'she. For example, if the content of the file "BIOPIC. TXT" is as
follows:
Last time he went to Agra, there was too much crowd, which he did not like. So this time
he decided to visit some hill station.
The function should read the file content and display the output as follows:
Last time she went to Agra, there was too much crowd, which she did not like. So this
time she decided to visit some hill station.
38. Ranjan Kumar of class 12 is writing a program to create a CSV file “user.csv” which will
contain user name and password for some entries. He has written the following code.
As a programmer, help him to successfully execute the given task.
import # Line 1
def addCsvFile(UserName,PassWord): # to write / add data into the CSV
file f=open(' user.csv',' ') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file
with open(' user.csv','r') as newFile:
newFileReader = csv. (newFile)# Line 3
for row in newFileReader:
print (row[0],row[1])
newFile. # Line 4
addCsvFile(“Arjun”,”123@456”)
addCsvFile(“Arunima”,”aru@nima”)
addCsvFile(“Frieda”,”myname@FRD”)
readCsvFile() #Line 5
91 | P a g e
(a) Name the module he should import in Line 1.
(b) In which mode, Ranjan should open the file to add data into the file in line 2.
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.
39. Which of the following modes is used for both writing and reading from a binary file?
a) wb+ b) w c) wb d) w+
40. The correct syntax of read() function from text files is:
a) file_object.read() b. file_object(read) c. read(file_object) d.
file_object().read
41. 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
48. Which method is used to move the file pointer to a specific position in a file in Python?
a. read() b. write() c. seek() d. close()
51. How do you read a specific number of bytes from a binary file in Python?
a. read() b. read_bytes() c. read(n) d. readlines(n)
92 | P a g e
52. What is the difference between a text file and a binary file?
a. Text files contain characters, while binary files contain arbitrary data.
b. Text files are human-readable, while binary files are not.
c. Text files are encoded using a character set, while binary files are not.
d. All of the above
53. 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
54. What is the 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
55. What is the difference between the seek() and tell() methods in Python?
a. The seek() method moves the file pointer to a specific position in a file, while the
tell() method returns the current position of the file pointer.
b. The seek() method takes an offset and a mode as arguments, while the tell() method
does not.
c. The seek() method can move the file pointer to a position before the beginning of the
file, while the tell() method cannot.
d. All of the above
57. What happens if you try to open a file in 'w' mode that already exists?
a. It overwrites the existing file.
b. It raises a FileNotFoundError.
c. It appends data to the existing file.
d. It creates a backup of the existing file.
93 | P a g e
c. It is used for reading binary files.
d. It is used for appending data to files.
63. 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
64. How can you check if a file exists in Python before trying to open it?
a. Using the os module
b. Using the file.exists() method
c. Using the file.exist() method
d. Using the file.open() method
65. 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
c. 'rb' is for reading, 'r' is for writing
d. 'rb' and 'r' are the same
94 | P a g e
68. Which module in Python is used to read and write CSV files?
a. os
b. csv
c. fileio
d. csvio
69. How can you read a CSV file in Python using the `csv` module?
a. csv.read(file)
b. csv.reader(file)
c. csv.load(file)
d. csv.load_csv(file)
70. What function is used to write data to a CSV file using the `csv` module in Python?
a. csv.write()
b. csv.writer()
c. csv.write_csv()
d. csv.write_to_file()
72. How can you write a dictionary to a CSV file using the `csv` module in Python?
a. csv.write_dict()
b. csv.writerows()
c. csv.writer_dict()
d. csv.DictWriter()
73. Which of the following statements is true about reading a CSV file with the `csv` module
in Python?
a. Each row is returned as a list of strings
b. Each row is returned as a dictionary
c. Each column is returned as a separate value
d. CSV files cannot be read using the `csv` module
74. 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.
import pickle
tup1 = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle. #Statement 1
myfile.close() Write the missing code in
Statement 1
75. A binary file employee.dat has following data
95 | P a g e
def display(eno):
f=open("employee.dat","rb")
totSum=0
try:
while True:
R=pickle.load(f)
if R[0]==eno:
#Line1
totSum=totSum+R[2]
except:
f.close()
print(totSum)
When the above mentioned function, display (103) is executed, the output displayed is
190000. Write appropriate jump statement from the following to obtain the above
output.
myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()
96 | P a g e
All the king's horses and all the king's men
Couldn't put Humpty together again
Suppose 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
82. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. i. Write a
user defined function CreateFile() to input data for a record and add to Book.dat . ii. Write
97 | P a g e
a function CountRec(Author) in Python which accepts the Author name as parameter and
count and return number of books by the given Author are stored in the binary file
“Book.dat”
83. 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.
84. Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurance of alphabets A and M (including
small cases a and m too).
Example: If the file content is as follows:
85. Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which is
starting with an alphabet ‘A’ .
86. 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.
87. 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:
Write the definition of a function WRITEREC () in Python, to input data for records from
the user and write them to the file PLANTS.dat.
Write the definition of a function SHOWHIGH () in Python, which reads the records of
PLANTS. dat and displays those records for which the PRICE is more than 500.
89. Write the definition of a Python function named LongLines ( ) which reads the contents
98 | P a g e
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:
90. 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:
Write the definition of a function countrec () in Python that would read contents of the
file "PATIENTS.dat" and display the details of those patients who have the DISEASE as
'COVID-19'. The function should also display the total number of such patients whose
DISEASE is 'COVID-19'.
92. Devender Singh, the Principal in GSV school, is developing a school teachers data using
the csv module in Python. He has partially developed the code as follows leaving out
statements about which he is not very confident. The code also contains error in certain
statements. Help him in completing the code to read the code the desired CSV File
named “Teachers.csv”
#CSV File Content
ENO, NAME, SUBJECT
E1, R.S. Hooda, Maths
E2, Sumit Beniwal, Chemistry
E3, Neetu Grover, Shorthand
E4, Jitender Meena, Social Science
E5, Samta Devi, Sanskrit
E6, Preeti Saini, Domestic Science
E7, Mayank, Computer Science
99 | P a g e
E8, Sanjiv Kala, Hindi
Q1. Devender Singh gets an Error for the module name used in Statement 1. What
should he write in place of CSV to import the correct module?
a) File b) csv c) csv d) pickle
Q2. Identify the missing code for blank spaces in the line marked as Statement-2 to
open the mentioned file.
a.) “Teacher.csv”,”r” b) “Teacher.csv”,”w” c) “Teacher.csv”,”rb” d)“Teacher.csv”,”wb”
Q3 Choose the function name (with parameter) that should be used in the line marked
as Statement-3 .
a) reader(File) b) readrows(File) c) writer(File) d)”writerows(File)
Q4. Devender Singh gets an Error in Statement-4. What should he write to correct the
statement?
a) For R in ER: b) while R in range(ER): c) for R = ER: d) while R = = ER:
Q5. Identify the suitable code for blank space in statement-5 to match every row’s 3rd
property with “Maths”.
a) ER[3] b) ER[2] c) R[2] d) R[3]
Q6. Identify the suitable code for blank space in Statement-6 to display every
Employee’s Name and corresponding Department?
a) ER[1],R[2] b) R[1], ER[2] c) R[1],R[2] d) ER[1],ER[2]
93. Shreyas 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.
100 | P a g e
100 | P a g e
i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the
customer.
(ii) Which statement should Shreyas fill in Statement 2 to check whether quantity is less
than 10.
(iii) Which statement should Shreyas 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 Shreyas 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?
101 | P a g e
Topics to be covered
1.Stack
2.Operations on stack (push, pop, peek, display)
3.Implementation of stack using
list 4.Applications of stack
102 | P a g e
DATA STRUCTURE
Data structure can be defined as a set of rules and operations to organize and store data in
an efficient manner. 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
also.
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.
STACK:
A Stack is a Linear data structure which works in 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 List data
103 | P a g e
structure to implement Stack.
103 | P a g e
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:
1. Push: It adds an element to the TOP of the Stack.
2. Pop: It removes an element from the TOP of the Stack.
3. Peek: It is used to know/display the value of TOP without removing it.
4. isEmpty: It is used to check whether Stack is empty.
OVERFLOW: It refers to the condition in which we try to PUSH an item in a Stack which is already FULL.
UNDERFLOW: It refers to the condition in which we are trying to POP an item from an empty Stack.
104 | P a g e
Implementation of Stack:
In Python, List data structure is used to implement Stack. For PUSH operation we use append()
method of List while for POP operation we use pop() method of List.
PROGRAM: To illustrate the basic operations of Stack:
105 | P a g e
named “Hotel”:
i. Push_Cust() - To Push customer’s names of those customers who are staying in ‘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 are as follows:
[“Siddarth”, “Delux”]
[“Rahul”, ”Standard”]
[“Jerry”, “Delux”]
The stack should contain:
Jerry
Siddharth
The output should be:
Jerry
Siiddharth
Underflow
3. Write a function, Push (Vehicle) where, Vehicle is a dictionary containing details of vehicles
– {Car_Name: Maker}. The function should push the name of car manufactured by ‘TATA’
(including all the possible cases like Tata, TaTa, etc.) to the stack. For example:
Safari
106 | P a g e
QUES: A list, NList, contains following record as list elements:
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=[[“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]
107 | P a g e
Ques: Write a function in Python, Push(SItem) where, SItem is a dictionary containing
the details of stationary items—{Sname:price}. The function should Push the names of
those items in the stack who have price greater than 75. Also display the count of
elements pushed into the stack.
For example:
If th 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]
108 | P a g e
Assignment
1 Sanya wants to remove an element from empty stack. Which of the following term is related
to this?
(a) Empty Stack (b) Overflow (c) Underflow (d) Clear Stack
109 | P a g e
ASSERTION (A): A data structure is a named group of data types.
REASON(R): A data structure has a well-defined operations, behaviour and
properties.
● ASSERTION (A): A Stack is a Linear Data Structure, that stores the elements in FIFO
order.
REASON(R): New element is added at one end and element is removed from that end
only.
● ASSERTION (A): An error occurs when one tries to delete an element from an empty
stack.
REASON(R): This situation is called an Inspection.
8 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.
110 | P a g e
10 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 who have 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
The output should be:
11 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 person above
age 20
- Implement a `pop_dict` method to pop the top dictionary from the stack.
- Implement a `push_student` method to push student records onto the stack that GPA
above 60.
- Implement a `pop_student` method to pop the top student record from the stack.
13 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}....}
- Implement a `pop_nested_dict` method to pop the top element from the stack.
for example :
after implementing push_nested_dict() , the stack becomes:
{‘y’:100,’z’:200}
{‘x’:10}
{‘a’:’one,’b’:’two}
111 | P a g e
14 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 value of N passed 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".
16 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 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"}
Safari
Nexon
112 | P a g e
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
113 | P a g e
What is Network?
It is a collection of Inter-connected computers and other devices that are able to
communicate with each other i.e. it is a collection of hardware and software components
that are connected together for effective information interchange wherein, one
system/device is the sender and the other is the receiver.
Evolution of Networking
Network Communication dates back to the earliest times since the evolution of human race
on earth. All the living organisms communicate with each other on one way or the other.
The early man used to communicate using the symbolic language, then with the
development of modern languages and intelligence, the communication media came into
picture. And, with the advent of computer systems, the data communication became
important so as to take necessary decisions and pass the messages quickly.
In year 1967, the very first network came into existence, namely-ARPANET.
ARPANET
(Advanced Research Project Agency Network) that was designed to survive any nuclear
threat. It was the first system to implement the TCP/IP protocol suite and was based on
Client-Server architecture.
NSFNet
National Science Foundation Network, was started in 1980 with a view to enhance Academic
and Scientific Research. It connected its server with the ARPANET in year 1986.
In the year 1990, the NSFNet, ARPANET and other smaller networks clubbed together to
form the INTERNET (Interconnected Networks) and hence the foundation of modern
INTERNET was laid down.
114 | P a g e
Internet:
It is the global network of interconnected devices that may/may not follow same set of
rules, and connect together for sharing information and establishing communication. It is
made up of two parts:
a. IntraNet:
The word Intra means inside or within. Therefore,
Intranet means the network within an organization. It is
created using the protocols of LANs and PANs. Example:
Wipro uses internal network for business development
b. Extranet:
It is the network that lies outside the limits of the
IntraNet. Dell and Intel use network for business related
operation.
c. Interspace:
It is the client-server software program that allows multiple users to communicate
with each other using real-time audio, video and text in a dynamic 3D environment.
Data Communication
Data:
It is raw facts and figures that are yet to get a defined meaning. Examples: 11, A123x@r67Y,
etc.
Information:
The processed form of data that had a defined meaning is known as the information.
Examples: Roll No. 11, Password: A123x@r67Y, etc.
Data Channel:
It is a medium to carry information or data from one point to another.
Baud:
It is the measurement of the data transfer rate in a communication channel.
Bits per Second:
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.
115 | P a g e
Bandwidth:
It is the difference between the highest and lowest frequencies in a channel. The high
bandwidth channels are known as Broadband Channels, and the low bandwidth channels
are called as the Narrowband Channels.
Switching Techniques:
These are used for transmitting data across the networks. The various switching techniques
are:
a. Circuit Switching:
Here, the connection between the sender and receiver is established first, and then the
data is transmitted from the source computer to destination computer. Before
transferring the data, a call setup is required for establishing connection between
sender and receiver. It is best for connections that require consistent bit rate for
communication.
b. Message Switching:
In this technique, the message is sent to the switching office first that stores the data in
the buffer, and then the switching office finds the free link to the receiver, and then
sends the data to the receiver. There is no limit to the size of the message block to be
transmitted over the network.
c. Packet Switching:
It is the most efficient data communication technique used to send and receive data
over the internet. Instead of using the dedicated circuit for data communication, the
data is independently routed through the network and reassembled at the destination
computer system. Data is divided into fixed size packets before transmission. Each
packet contains a fraction of data along with addressing information.
116 | P a g e
Transmission Medias
A 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.
117 | P a g e
C. Fiber Optic Cable:
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.
In computer networks, wireless transmission media refers to the means of transmitting data
between devices without the use of physical cables. Wireless communication relies on
electromagnetic waves to carry information. Some common types of wireless transmission
media used in computer networks include:
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
118 | P a g e
operates in the 2.4 GHz frequency band and supports relatively low data transfer rates
compared to Wi-Fi.
C. Infrared (IR):
Infrared communication uses infrared light to transmit data between
devices. It is commonly found in remote controls for TVs, audio systems, and
other consumer electronics.
D. Microwaves:
These are high frequency waves that can be used to transmit data
over long distances, in a straight line, but these can not penetrate
through solid objects. It consists of a transmitter, receiver, and air.
F. 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.
H. 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.
119 | P a g e
Wireless transmission media offer the advantage of mobility and flexibility, allowing devices
to connect without the constraint of physical cables. However, they may be susceptible to
interference, have limited range, and typically offer lower data transfer rates compared to
wired media. The choice of wireless media depends on factors such as the required
coverage area, data transfer speed, power consumption, and potential interference in the
operating environment.
Sink Node:
It is a node with no outward connections to other nodes. In other words, it sends
information to other nodes, but cannot receive the information by itself.
Network Devices:
For smooth functioning of computer network, other than computers and wirings, many
devices play an important role. These devices are known as the Network Devices.
A. Modem:
Modulator-Demodulator allows us to reach the global network with ease. It is used
to send and receive the data over the telephone lines or cable connections. Since,
the ordinary telephone lines cannot carry the digital information, a modem changes
the data from analog to digital format and vice versa.
Modems are of two types:
1. Internal modems: The modems that are fixed in the computer systems are
Internal Modems.
2. External Modems: The modems that are connected externally are called External
Modems.
120 | P a g e
C. NIC:
Network Interface Card (NIC) is a device used to connect the network with the
Internet. It is sometimes called ad the TAP (Terminal Access Point). Since different
manufacturers give different names to this device, hence, it is sometimes referred to
as NIU (Network Interface Unit).
The NIC has a unique physical address to each card, and it is known as MAC (Media
Access Control) Address.
D. MAC Address:
It is a b-byte address assigned to each NIC card and is separated by a colon. Example:
10 : E8 : 05 : 67 : 2A : GS
Manufacturer ID Card No.
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 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. 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.
H. Switch:
It is a device that is used to divide network into smaller
networks called subnets or LAN segments. This helps to
avoid network traffic as it divides the traffic into smaller
parts. It is responsible for filtering of data packets and then
transmission over the network.
I. Repeaters:
A repeater is a network device that amplifies, restores and re-broadcasts signals for
long-distance transmission.
121 | P a g e
J. Bridge:
It is a device that links two networks. It is smart system that knows which system lies
on which side and in which network. These can handle the networks that follow
different protocols.
K. Gateway:
It connects two dissimilar networks and establishes an intelligent connection
between local and external networks with completely different architecture. It is also
known as protocol translator.
L. Wi-Fi Card:
It is the LAN adapter whether external or internal with a built-in
antenna and wireless radio. Its main benefit is that it allows a
computer to setup the system as workstation without considering the
availability of hard- line access.
Network Topologies
The term topology means the way of connecting different systems to form a network. Some
of the commonly used topologies are as follows:
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 simultaneously.
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.
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.
122 | P a g e
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 redundant paths
for data transmission, ensuring high reliability and fault
tolerance.
2. Mesh topologies are commonly used in critical applications
where network uptime is crucial. However, the extensive
cabling and complex connections can be expensive and
challenging to manage.
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 in scenarios 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.
123 | P a g e
1. The root node acts as the central hub, and devices are connected to it directly or
through intermediary devices like switches or hubs.
Types of Networks:
124 | P a g e
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
125 | P a g e
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 measure such as
Firewalls, access controls, and encryption to
protect data and unauthorized access to the
network at a much cheaper cost.
126 | P a g e
c. These allow the efficient transfer of data, voice, and videos between different nodes
thereby enabling communication and resource sharing between devices at far away
distances.
d. These are designed with redundancy and backup links to
ensure high fault tolerance thereby minimizing
disruptions and maintaining connectivity even if some
network segment fails.
e. Data Security becomes the key issue as it becomes
essential to protect data from unauthorized access and
cyber threats. Thus encryption, firewalls and virtual
private Networks (VPNs) play an important role in ensuring data security.
f. These may have varying speeds and bandwidth depending upon the technology used
and the distance between network nodes.
Note:
Virtual Private Network: It is used to access the public network as a private network. It
ensures enhances security, and safety of data.
Network Protocols:
These are the set of rules that are required to run the internet keeping in mind the security
of data for sake of users.
127 | P a g e
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).
128 | P a g e
12. ICMP (Internet Control Message Protocol):
Used for error reporting and diagnostics in IP networks.
Commonly associated with tools like ping to test network connectivity.
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 on the basis of hypertext links which allows the users
to navigate between different documents and multimedia content.
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 the resource on the web can be accessed using the unique
address called as 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 as Web Browser. There are many web browsers available on the
internet like Google Chrome, Microsoft Edge, and 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.
129 | P a g e
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 with a view to structure and
organize the static web pages. These are the symbols and codes that allow the used
to develop web pages that can run over the internet. These define the layout,
format, and linking of text, multimedia, and other elements within a web page. It
uses tags for presentation of content.
8. XML:
Extensible Markup Language (XML) is designed to carry and store data in a
structured and platform-independent format. These use the user-defined custom
tags to represent specific data fields and structures. These are self-descriptive and
make it easier for different applications to understand and interpret data.
9. Websites:
These are the collections of various web pages and data that are accessible for all,
and are available on the internet. Many types of restrictions such as screenshot
protections, copying of data can be implemented on the websites for data
protection.
10.Web Hosting:
This refers to the service of providing storage space, server resources, and internet
connectivity to make websites and web applications accessible to users over the
internet. It allows individuals, businesses, and organizations to publish their websites
on the World Wide Web, making them available to visitors and users worldwide.
a. Web hosting companies maintain powerful servers designed to store website
files, databases, and other contents required for website operations.
b. These typically handle the maintenance tasks of the registered websites.
c. These ensure proper backup and recovery of the lost data (if any) while accessing
it, and cope up with potential threats that can destroy data.
130 | P a g e
a. IPv4:
These are the addresses that consist of 32-bit addressing scheme. Example:
192.168.0.24
b. IPv6:
This uses 128 bit addressing scheme represented by eight groups of hexadecimal
digits separated by colons. Example: 2001:0db8:85a3:0f00:00a0:8a2e:0370:7334.
131 | P a g e
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 expansion of the network by simply adding more
devices to the central hub?
a) Bus
b) Star
c) Ring
d) Mesh
132 | P a g e
b) Star
c) Ring
d) Mesh
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
133 | P a g e
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
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
134 | P a g e
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) together?
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:
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)
135 | P a g e
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)
136 | P a g e
28. Differentiate between website, web link, and web server.
29. Differentiate between hypertext, and hyperlink.
30. What are the different internet protocols?
31. Differentiate between SMTP, POP, and FTP.
32. Define WWW.
33. Define XML.
34. Define HTML.
137 | P a g e
c) Webpages of a site
d) A medium to carry data from one computer to another
2. 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
5. Computer that requests the resources or data from other computer is called as
computer
a) Server
b) Client
c) None of the above
d) a and b
B. 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 own networks, named private networks, which were later (in 1990’s)
connected with ARPANET and NSFnet to form the Internet. The Internet really
became popular in 1990’s after the development of World Wide Web.
138 | P a g e
1. What does NSFnet stand for?
a) National Senior Foundation Network
b) National Science Framework Network
c) National Science Foundation Network
d) National Science Formation Network
3. What is internet?
a) A single network
b) A vast collection of different networks
c) Interconnection of local area networks
d) Interconnection of wide area networks
5. Internet access by transmitting digital data over the wires of a local telephone
network is provided by:
a) Leased line
b) Digital subscriber line
c) Digital signal line
d) Digital leased line
6. A piece of icon or image on a web page associated with another webpage is called
a) URL
b) Hyperlink
c) Plugin
d) Extension
2. Which one of the following is not an application layer protocol used in internet?
a) Remote procedure call
b) Internet relay chat
c) Resource reservation protocol
d) Local procedure call
7. Network layer at source is responsible for creating a packet from data coming from
another
a) station
b) link
c) node
d) protocol
140 | P a g e
D. A blog is a publication of personal views, thoughts, and experience 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, it 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 post by the blogger. In most cases, celebrities,
business tycoons, famous politicians, social workers, speakers, etc are the successful
blogger because people follow them to know about their success stories and ideas.
1. Using websites for building network with friends and relatives is called as
a. social networking
b. blogging
c. netbanking
d. e-commerce
3. Google is an example of
a. social network
b. entertainment
c. search engine
d. none of these
6. 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
141 | P a g e
E. 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 mails 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
4. Mail access starts with client when user needs to download e-mail from the
a. mail box
b. mail server
c. IP server
d. Internet
5. When sender and receiver of an email are on same system, we need only two
a. IP
b. domain
c. servers
d. user agents
F. In 1989, Tim Berners Lee, a researcher, proposed the idea of 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
142 | P a g e
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.
1. 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 internet
d. All of the above
5. 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
143 | P a g e
G. 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 the products and services over the internet. In this kind of
transaction, the seller does not have to face the buyer to communicate. Few
examples of e-commerce are online shopping, online ticket booking, online banking,
social networking, etc.
1. Which of the following describes e-commerce?
a. doing business
b. sale of goods
c. doing business electronically
d. all of the above
5. The primary source of financing during the early years of e-commerce was
a. bank loans
b. large retail films
c. venture capital funds
d. initial public offerings
144 | P a g e
a. value proposition
b. competitive advantage
c. market strategy
d. universal standards
H. 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 saves huge costs. E-Group is a feature
provided by many social network services which helps you create, post, comment to
and read from their “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 behavior” within the group.
1. 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
145 | P a g e
6. Which of the following has E-groups?
a. Instagram
b. Twitter
c. Yahoo!
d. WhatsApp
I. Coursera has partnered with museums, universities, and other institutions to offer
students free classes on an astounding variety of topics. Students can browse the list
of available topics or simply answer the question “What would you like to learn
about?”, then when they answer that question, they are led to a list of available
courses on that topic. Students who are nervous about getting in over their heads
can relax.
1. What do MOOCs stand for?
a. Mobile Online Open Courses
b. Massive Online Open Courses
c. Mobile Open Online Courses
d. Massive Open Online Courses
3. What type involves allowing participants to complete training in their own time via
web-based training i.e. email, blackboard, intranets, and where there is no help from
instructors and participants can use internet as a support tool?
a. Blended learning
b. Asynchronous learning
c. Distance learning
d. Synchronous learning
4. Which of the following training scenarios would e-learning be most suitable and
efficient for?
a. Induction to the company for new employees
b. Microsoft excel training
c. Team-building exercise
d. Building your assertiveness skills at work
146 | P a g e
a. edX
b. MasterClass
c. Flipkart
d. SimplyCoding
J. 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, easy-to-use interface, and 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
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
147 | P a g e
b. Web manager
c. Ink directory
d. Search optimizer
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 server with all the other buildings.
148 | P a g e
III. Suggest the devices to be installed in each of these buildings for
connecting computers installed within the building out of the following:
Gateway Modem 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
L. M/S Adco Informatics Services is an educational service organization. It is planning to
setup its India campus in Chennai with its head office at Hyderabad. The Chennai
campus has 4 buildings- ADMIN, MEDIA, ENGINEERING, and BUSINESS.
Head Office
From To Distance
Admin Engineering 45 m
Admin Business 80 m
Engineering Business 25 m
Admin Media 60 m
Engineering Media 60 m
Business Media 75 m
Hyderabad Head Office Chennai Campus 692 Km
149 | P a g e
v. Is there a requirement of a repeater in the given cable layout? Why/Why not?
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 connection?
N. Ayurveda Training Educational Institute is setting up its centre in Hyderabad with four
specialised departments for Orthopedics, Neurology and Pediatrics along with an
administrative office in separate buildings. The physical distances between these
department buildings and the number of computers to be installed in these
departments and administrative office are given as follows. You, as a network expert,
have to answer the queries as raised by them.
Shortest distances between various locations in metres :
Administrative Office to Orthopedics Unit 76
Neurology unit to Administrative Office 25
Orthopedics Unit to Neurology Unit 50
Pediatrics Unit to Neurology Unit 40
Pediatrics Unit to Administrative Office 65
150 | P a g e
Pediatrics Unit to Orthopedics Unit 150
Number of Computers installed at various locations are as follows:
Pediatrics Unit 45
Administrative Office 190
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 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.
Number of Computers:
Building No. 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:
151 | P a g e
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
P. 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
Q. M/S Sunny Shinde and sons Training Inc. Ltd. Is a Mumbai based organization which is
expanding its office in Ahmedabad? At Ahmedabad compound, they are planning to
have
152 | P a g e
3 different blocks for Admin, Training, and Accounts related activities. Each block has a
number of computers, which are required to be connected in a network for
communication, data and resource sharing. As a network consultant, you have to
suggest the best network related solutions for them for issues/problems raised by them
as per the distances between various blocks/locations and other given parameters.
Accounts Block HQ
Mumbai
Training Block
153 | P a g e
Number of Computers
Black A 25
Block B 50
Block C 125
Block D 10
Suggest a cable layout of connections between the blocks.
Suggest the most suitable place (i.e. block) to house the server of organization with a
suitable reason.
Suggest the placement of the following devices with justification
Repeater
Hub/Switch
The organization is planning to link its front office situated in the city in a hilly
region where cable connection is not feasible, suggest an economic way to
connect it with reasonably high speed?
S. Richard Middleton Fashion is planning to expand their network in India, starting with
two cities in India to provide infrastructure for distribution of their product. The
company has planned to set up their main office units in Chennai at three locations and
have named their offices as “Production Unit”, “Finance Unit” and “Media Unit”. The
company has its corporate unit in New Delhi.
A rough layout of the same is as follows:
154 | P a g e
the following office units:
• Production Unit and Media Unit
• Production Unit and Finance Unit
ii) Which one of the following devices will you suggest for connecting all the computers
within each of their office units?
• Switch/Hub
• Modem
• Telephone
iii) Which of the following communication media, will you suggest to be procured by
the company for connecting their local offices in Chennai for very effective (High Speed
communication?
• Ethernet cable
• Optical fiber
• Telephone cable
iv) Suggest an effective method/technology for connecting the company’s office unit
located in Delhi.
T. MyPace University is setting up its academic blocks at Naya Raipur and is planning to set
up a network. The University has 3 academics blocks and one Human Resource Centre
as shown in the diagram below:
155 | P a g e
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 university. Which type of network out of LAN, MAN or WAN will be
formed? Justify your answer.
156 | P a g e
Topics to be covered
1.Database concepts
2.Relational data model
3.Structured Query Language
4.Interface of python with an sql database
157 | P a g e
UNIT-III
DATABASE MANAGEMENT:
Database Concept:
Introduction of Database:
Database is a word which composed of two words Data and Base. Data means raw facts and
figures and base is place or location where data is being stored.
Or we can say that Database is collection of interrelated data or record in organized form so
it can easily be accessed, managed and updated. Interrelated data means that the data is
related or connected to each other with respect to the given attributes or column.
Database uses various fields to manage and store large amounts of information in organized
and structured format
Need of Database:
Centralized Storage: Storage of data in a single location or central database.
Data Integrity: Enforces data integrity rules which ensures that information stored is
accurate, valid and consistent.
Data Security: Control access to sensitive data and protecting data from unauthorized access.
Data Retrieval: Authorized User/Application can access and retrieve the information as per
their need.
158 | P a g e
Efficient Data Retrieval: Database helps user to retrieve data in an efficient way.
DBMS Model:
DBMS refers to that architecture/approach for how data is stored, organized and
manipulated in a database. There are several types of DBMS Model.
1. Relational Model:
Data organized into tables with rows and columns.
2. Hierarchical Model:
Data organized in Tree like structure with parent child relationship
3. Network Model:
Similar to hierarchical model. It uses pointers to navigate through data.
4. Object Oriented Model:
Data is represented as object. This model uses object oriented databases.
Now as per you CBSE syllabus we will discuss about Relational Data Model in detail.
159 | P a g e
Relational Data Model:
Relation Data Model is proposed by E.F. Codd in 1970.
In simple words, we can say that Relational data model is a model which uses relation to
organize their data. Here, Relation means table and table is composed of rows and
columns.
After creating conceptual data model using ER Diagram we need to convert it into Relational
Data Model so that we can implement using any RDBMS language like MySQL, Oracle SQL.
Before we proceed further, let’s discuss about some aspects of 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 Diagram and Object Oriented
Diagram
160 | P a g e
Relation/Table:
Relation is also known table. And table is a collection of related data and information in row
and column. Relation is composed of rows and columns.
Row/Tuple/Record:
Row represent horizontal form of Table/Relation. Row is also known as tuple/record.
Column/Attributes:
Column represent vertical form of Table/Relation. Column is also known as attributes.
Cardinality:
Total number of row/record/tuple in a relation is called as Cardinality.
Degree:
Total number of column/attributes in a relation is called as Degree.
Domain:
Domain is set of possible value or range of valid values or set of all unique values that an
attribute/column can hold.
A Domain of database is set of atomic value (which can’t further be distributed) of a particular
attribute/column.
161 | P a g e
For example:
In table Employee, Attribute/column gender may have only M, F and T Domain. Only these
value valid for that column.
Domain of S.No. Contain set of all possible roll numbers.
Domain of Martial Status contain set of all possible values like Married, Widow, Unmarried
and Divorce.
In the below diagram 4, Table Employee contain S.No, Name, Address, Gender and Marital
status. Two domain is showing name gender and marital status which contain 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 datatype of
column/attribute:
We need to assign datatype when we are declaring any column/attributes. Every column
required name and datatype. This datatypes is used to declare what type of data that will be
stored in particular column. There are lots of datatypes available in SQL we will discuss some
important datatype.
162 | P a g e
Commonly used 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: A enumeration type for a set of predefined
values Now let’s learn datatype in detailed as per your syllabus
163 | P a g e
DATE AND DATE AS THE NAME SUGGEST IT IS USED TO STORE
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 database, keys is column/attribute which is used to fetch/extract/retrieve row in a table.
Or we can say that Keys are used to uniquely identify records in a table through column or
combination of column. To extract any particular row/record from a table, we need a key
attribute which contain unique values.
164 | P a g e
Primary Key:
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
Note: A Primary key must be a candidate key but not all candidate key are Primary key
Candidate Key:
Candidate key are those key which are eligible for primary key and can be used as primary
key in a table.
Candidate key is a set of one or more column that could be used as primary key and from
the set of these candidate key, one column is selected as primary key.
From Diagram 5, Candidate key can have more than one attribute like Emp_ID, Name, and
Address etc.
Alternate Key:
After selecting primary key from candidate key, the remaining keys (which are also eligible
for 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.
Let’s see how actually foreign key work in table.
165 | P a g e
It is an attribute whose values can be derived from primary key of some other table.
It ensure referential integrity. Referential Integrity is protocol which is used to ensure that
relationship between record/row is valid and can’t change in related data.
User may get information from a database file from required query. Query is a request in
the form of SQL command to retrieve information with some condition. You will see lots of
query performing different type of operations. SQL is query language (Query based
language) which works on structured data (data in structured form).
Now let’s discuss all the SQL Commands in categorized way.
166 | P a g e
SQL perform following operation:
Create a database
Create a table
Create view
Insert data
Update data
Delete data
Execute Query
Set Permission or Constraints in table
SQL Commands:
SQL commands are predefined set of commands which are already defined in SQL.
Commands are basically combination of keyword and statement you want to execute.
Keywords are reserved words that has special meaning for SQL, you don’t need to define
they are already defined in SQL. All you need to use these keywords with you particular
statements.
CLAUSE IN SQL:
Clause: Clause are built in functions which is use to deal with data inside the table that help
SQL to filter and analyses data quickly.
167 | P a g e
Any SQL statements is composed of two or more clause.
These clause are used with your SQL statements to filter commands you may learn in detail
in further section. Some mainly used clause are discussed below.
NOTE: All SQL statements are terminated with (;) semicolon
SQL statements are not case sensitive means SQL treats both upper and lower case
commands as same.
168 | P a g e
We are going to use these above clauses in our all types of commands in SQL.
Show databases:
To view the list of available/created databases in SQL, show databases command is used.
SQL Syntax:
show databases;
Use database:
To select a database among available databases, use database command is used.
SQL Syntax:
use <database_name>;
Show tables:
To view the list of available/created databases in SQL, show tables command is used.
SQL Syntax:
show tables;
169 | P a g e
Create table:
To create a new table in the selected database. For example, if I want to create a table
Student with following attributes and data types:
SQL Syntax:
create table <table name>(<attribute name> <data type> (size),
<attribute name> <data type> (size) … );
Describe table:
To view the structure of table (like attributes and its data types, keys, constraints, default
values), desc command is used.
SQL Syntax:
desc <table name>; OR describe <table name>;
170 | P a g e
Insert command:
To insert data in table, insert command is used (one row at a time). Here in this example,
data of 4 students are inserted in table student.
SQL Syntax:
insert into <table name> values (<value>, <value> , <value> …);
Select command:
To show the data of a table, select command is used. Let’s show the data of 4 students in
student table that was inserted in the previous command.
SQL Syntax:
select * from <table name>;
171 | P a g e
Drop database command:
To delete a database along with all the tables present in the database, drop command is used.
SQL Syntax:
drop database <database name>;
Constraints:
Constraints in SQL are set of rules that are applied to the data in a relation/table.
Types of constraints:
1. Primary key
2. Unique
3. Not Null
4. Foreign Key
172 | P a g e
Let’s discuss in Details:
SQL Syntax:
create table <table_name>(<column_name> <datatype> <size> <constraint>);
Command:
create table student_demo(roll_no int(10) primary key,name varchar(20),subject
varchar(20));
2. Unique Constraints :
NULL VALUES or (NOT NULL VALUES+UNIQUE) =UNIQUE
Unique constraint make sure that all values present or inserted in a column are different.
And this constraints follows all property of primary key constraints except that Primary
key can’t contain NULL values but unique constraints allows NULL values. It ensures that
values in the column are unique across all rows.
NOTE: You can have more than one unique key but only one primary key
173 | P a g e
As you can see Unique Key constraints assigned to attribute/Field named standard. Which
means standard column hold unique value.
Now as we know standard attribute can only hold unique value. If we attempt to insert
duplicate values in standard attribute. This may occur an error. Let’s see how
Now we are going to enter a valid entry in student table. Let’s see
As you can see all entry are clearly affected in table student. Now we need to check that
standard attribute allows NULL values. Let’s understand with SQL command.
174 | P a g e
3. NOT NULL Constraints : Which never accept NULL values
NOT NULL constraints ensures that columns in table does not contain any NULL values.
NULL values means missing or unknown values. If you enforce this NOT NULL constraints
to any attribute than you are not able to insert any NULL values in it. Let’s see how.
In student table, only two attribute assigned with NOT NULL constraint, first one is
roll_no and std_name which means that these column can’t accept NULL values
Now we enforce NOT NULL constraint to another column named subject in existing table
student.
As you can command is successfully executed. Let’s see the schema of the table to check
NOT NULL constraint successfully applied on subject column.
In below diagram it is clearly shows that subject NULL Type is set to NO means you can’t
insert NULL value.
After that we have to check by insert a command with NULL values whether the subject
column is accepting NULL value or not. Let’s see
175 | P a g e
As you can there is error occur that column ‘subject’ cannot be null
Now we try to insert a another command in the student table and check whether the
insertion is successful or not
4. Foreign Key:
In Foreign Key constraints, unique, not null and primary key constraint applies to a single
table where as foreign key constraint applies to two tables.
176 | P a g e
(a) Column ID of Student table must be its primary key.
(b) Column ID of Awards table may or may not be primary key of Awards table.
Foreign key constraint ensures that only that data can be inserted in column ID of
Awards table which is present in column ID of Student table.
Example: We will create two tables. Student table as parent table and Awards table as
child table. Now we will establish foreign key constraint on column ID of student table
and column id of awards table.
Now let’s check how foreign key constraint works. We have already added data in
Student table.
Now let’s check how foreign key constraint enforces referential integrity.
Here we can see that ID 5 is not present in parent table (Student). So, ID 5 can’t be added
in child table (Awards).
177 | P a g e
We have already covered few DDL Commands like create database, create table, drop
database, drop table. Few more DDL commands like alter table will be discussed now.
Alter Table:
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.
SQL Syntax:
alter table <table name> [alter option];
SQL Syntax:
alter table <table name> add <column name><data type> [constraint];
Example: If we want to add a column class with data type varchar and size 50 and nulls are
not allowed.
178 | P a g e
Modifying column of a table: We have different ways to modify a table like
column name, data type, default value, size, order of column, constraints.
1. Changing column name: We can change the column name of a table using alter
command. For example, in table student, we are going to change column name
Student_ID to ID.
SQL Syntax:
alter table <table name> change column <old column name> <new column name>
<data type>;
2. Changing column data type: We can change the column data type from varchar to
char or int to varchar etc. of a table using alter command. For example, in table
student, we are going to change datatype of column ID from int to varchar.
SQL Syntax:
alter table <table name> change column <column name><new data type>;
179 | P a g e
3. Changing maximum size of the data in a column: We can change the maximum size
of the data in a column of a table using alter command. For example, in table
student, we are going to change size of column ID from varchar(50) to varchar(40).
SQL Syntax:
alter table <table name> change column <column name> <data type with size>;
4. Changing order of the column: We can change the order of the column of a table
using alter command. For example, in table student, we are going to place column ID
after column Age.
SQL Syntax:
alter table <table name> modify <column name> <data type with size>[first|after
<column name>];
180 | P a g e
Now we are going to put column ID back to first position.
181 | P a g e
Dropping primary key: We are going to remove primary key at column ID which
we added in the previous section.
Command: alter table <table name> drop primary key;
Adding a new column: We are going to add a column country with data type
char of size 50 to the table student using alter command.
Command: alter table <table name> add column <column name> <data type
with size>;
182 | P a g e
DML (Data Manipulation Language) Commands:
These commands are used to make any changes in the data of the table.
Delete command:
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 satisfies the condition will be deleted from
the table.
SQL Syntax:
delete from <table name> where <condition>;
Now let’s delete data of all those students from student table whose ID is greater than 5.
183 | P a g e
Update command: 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 satisfies the condition
will be update from the table.
SQL Syntax:
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’.
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. Alias created
using as keyword. Creating aliases don’t change name of any table or column permanently.
184 | P a g e
Distinct clause:
Distinct clause is used to remove duplicate values from the table. As we studied earlier,
changes in data of a table is done using delete and update command. So, removing
duplicate values using distinct clause is temporary and only reflected during output. Distinct
clause can be used for more than one column.
Here in student table, two duplicate ID’s 1 and 3 are present. Now using distinct clause we
can get only unique values.
As we can see that all duplicate ID’s are removed but it is temporary. Duplicate values are
not removed and still present in the table.
185 | P a g e
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 meets 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.
186 | P a g e
2. To filter the result based on multiple condition:
Example of not in clause: if we want to find the data of those students who don’t lives in
delhi or Jaipur or gurugram.
187 | P a g e
Between Clause:
It is used to filter the rows in output based on the range of values.
SQL Syntax:
where <column name> between <starting value> and <ending value>;
Note: The final result of between clause filters the rows of the table based on range of
values including starting and ending value.
Order by Clause: It is used to sort the output of the select statement in ascending or
descending order.
SQL Syntax:
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 to mention the order of sorting.
188 | P a g e
We can sort multiple columns together in ASC and DESC order.
NULL:
In SQL, null is a special value which means absence of value or a field doesn’t has 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, so we can store NULL
instead of zero or make it empty.
189 | P a g e
IS NULL Clause:
IS NULL clause is used to check that value in particular column is NULL value
Example: To find out name of students whose phone number is NULL.
Like operator:
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.
190 | P a g e
2. % (percentage sign): It is used to match zero or more characters.
Example 1: To match a string that starts with ‘s’, its pattern will be ‘s%’. As we don’t know
how many characters are there after ‘s’, so ‘%’ sign is used after ’s’.
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 with ‘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 letter ‘a’ at second position, its pattern will be ‘_a%’.
As we know there must be exact one character before ‘a’ and we don’t know how many
characters are there after ‘a’, so ‘_’ sign is used before ‘a’ and ‘%’ sign is used after ’a’.
191 | P a g e
Example 5: To match a string that has exactly 5 character, its pattern will be ‘_______’. As we
know there must be exact 5 character, so ‘_’ sign is used 5 times.
Example 6: To match a string that has exactly 7 character and ends with ‘t’, its pattern will
be ‘_______t’. As we know there must be exact 7 character, so ‘_’ sign is used 6 times before
‘t’.
Update Command:
It is used to update the existing data in a table.
SQL Syntax:
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.
192 | P a g e
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.
SQL Syntax:
delete from <table name> where <condition>;
193 | P a g e
Example 1: Let’s delete data of those students whose ID is 1 but age is not 18.
Example 2: Let’s delete all data of student table. For doing those, we needs to give a
condition that matches with all the records. As ID’s are greater than 0, so let’s delete all
those records where ID is greater than 0.
194 | P a g e
Aggregate Functions:
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.
1. Max():
It is used to find out the maximum value from a column.
2. Min():
It is used to find out the minimum value from a column.
195 | P a g e
3. Avg():
It is used to find out the average value from a column.
4. Sum():
It is used to find out the sum of all values of a column.
Note: Distinct keyword can be used with aggregate functions to find out max, min, sum, avg,
count of only unique values.
Example: Let’s find out total number of cities from where student came for study. Here
more than one student is from same city. So we needs to use distinct keyword along with
count function.
196 | P a g e
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.
It can be used with or without where clause in select statement.
It is applied only on numeric values.
It can’t be applied with distinct keyword.
SQL Syntax:
group by <column name>
Example 1: Let’s count number of students having same age in student table.
197 | P a g e
Example 2: Let’s city wise find out the minimum value of ID.
Having clause:
It is used to filter the result set of group by clause in select statement.
Note: To filter the result set of group by clause, only having clause can be used whereas for
all other queries where clause is used.
Joins:
Joins are used to combine rows from multiple tables.
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 5 rows in first
table and 4 rows in second table then the total number of rows in Cartesian product
of these two tables will be 20 rows.
Cardinality of final table of Cartesian product = cardinality of first table *
cardinality of second table
Example: we have two tables’ student and awards. Let’s apply Cartesian product on
these two tables.
198 | P a g e
2. Equi join:
It joins the tables based on one common column. However, final result will consists
of common column from both the tables.
Example: we have two tables’ student and awards. Let’s apply equi join on these two
tables.
Here both the tables has common column ID. So, to avoid ambiguity (confusion), we
needs to mention table name before column name.
199 | P a g e
3. Natural Join:
It joins the tables based on one common column. However, final result will consists
of common column only once.
Example: we have two tables’ student and awards. Let’s apply natural join on these
two tables.
Here both the tables has common column ID. But there is no ambiguity arises on
name of common column.
200 | P a g e
Password: It should be same as we set during MySQL installation.
Example: Let’s create a connection of python with MySQL and test it.
Python Code:
Output:
Here in above example, I had not set any database password, so, passwd option is not
mentioned in connection string. Is_connected() function checks whether connection string is
able to connect python with MySQL. If connection string is able to make connect 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 give 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>)
5. Extract data from result set
As we know that, Data from database is retrieved using select query. After running the
select query, we get the resultset. Now to fetch the data from resultset, following
functions are used:
a) 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()
201 | P a g e
b) fetchone():It returns one row from resultset in the form of a tuple. It returns None, if
no more records are there. To get multiple rows, we needs to run fetchone()
multiple times.
Syntax: <variable name>=<cursor>.fetchone()
c) fetchmany():
*It returns n number of records from resultset in the form of a list
* 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)
Python Code:
202 | P a g e
Output :
Format specifier:
We need format specifier to write SQL query based on user input. For doing this we have
two ways:
1. Using %s formatting:
Whenever we needs to complete SQL query based on user input, we write a placeholder
%s on that place.
Example: Let’s fetch all the data from student table where age is ‘x’ and city is ‘y’. (Here,
Output:
203 | P a g e
Example: Let’s fetch all the data from student table where age is ‘x’ and city is ‘y’. (Here,
value of x and y will be given by the user during run time).
Python Code:
Output:
Commit() : Whenever we perform update, delete or insert query, commit() function must be
run before closing the connection.
Syntax: <connection object>.commit()
Example 1: Insert data in student table which will be given by the user during run
time. Data in student table before insertion
Python code:
204 | P a g e
Output:
Example 2: Delete data of those students whose ID is given by the user during run time in
student table.
In the previous example, after inserting a record in student table, we have 8 records in the
student table. (Kindly refer previous example for current state of student table).
Python code:
205 | P a g e
Output:
Example 3: Update name of those students whose name and ID is given by the user during
run time in student table.
In the previous example, after deleting a record in student table, we have 7 records in the
student table. (Kindly refer previous example for current state of student table).
Python code:
Output:
206 | P a g e
Data in student table after updating
207 | P a g e
MULTIPLE CHOICE QUESTIONS (MCQ)
6. What is domain in
database?
a. The alternate key of a table
b. The primary key of a table
c. The set of all possible values in column
d. The number of rows in table
9. Which key is used to uniquely identify record in table and doesn’t allow NULL values?
a. Alternate key
b. Primary key
c. Super key
d. Foreign key
10. A column that could potentially be used as the primary key and it should also contain
unique values?
a. Alternate key
b. Primary key
c. Candidate key
d. Surrogate key
11. A candidate key that is not selected as primary key which can serve as a unique identifier.
a. Alternate key
b. Primary key
c. Candidate key
d. Surrogate key
13. A column or set of column in table that refers to the primary key of another table.
a. Alternate key
b. Primary key
c. Candidate key
d. Foreign key
14. Which of the following SQL commands is used to view list of all database?
a. select databases
b. show databases
c. view databases
d. project databases
15. Which of the following SQL commands is used to use/select a particular database?
209 | P a g e
a. use
b. select
c. view
d. project
16. Which SQL command is used to define and maintain physical structure or schema of
table in database like creating, altering and deleting database object such as table and
constraints?
a. DDL
b. DML
c. DCL
d. TCL
17. Which SQL command used to change or modify any attribute/column like addition and
deletion of column in database?
a. create
b. alter
c. delete
d. update
21. Which commands is used to show all table in current using database?
a. display tables;
b. show tables;
c. view tables;
d. select all tables;
210 | P a g e
22. Which command is used in 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 row in database table?
a. count
b. count(*)
c. max
d. min
26. In relational database, a key that established 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 row and column in relational data
model?
a. Relation
b. View
c. Tuple
d. Database
28. Which SQL clause is used to filter the result of SELECT statement in Relational Database?
a. from
b. where
c. join
d. having
211 | P a g e
a. To retrieve a set of statement
b. To add new row of data to a table
c. To change already existing data in table
d. To delete any existing row in table
30. How many candidate key can a relation/table have in relational database
a. One
b. Two
c. Multiple
d. None
31. What is the main difference between candidate key and primary key?
a. A candidate key can contain NULL value but primary key can’t contain NULL value
b. A primary key can contain unique value but it is not necessary for the candidate key
to have unique value
c. Candidate key is chosen by database system while primary key is chosen by the
designer
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
b. DROP TABLE
c. REMOVE TABLE
d. ERASE TABLE
34. Which constraint enforce data integrity by ensuring that a column always contain a
values?
a. NULL
b. NOT NULL
c. CHECK
d. DEFAULT
35. What is primary difference between candidate key and primary key in database?
a. Primary key is chosen by the end user/designer while candidate key is generated by
database system
b. A candidate key uniquely identifies each row in a table, while primary key is not unique
c. A primary key can have NULL values while a candidate key can’t
212 | P a g e
d. A candidate key can become a primary key, but a primary key can’t become a
candidate key
36. Which key is used to enforce referential integrity between tables in database system
a. Primary key
b. Candidate key
c. Foreign key
d. Alternate key
37. What is the main difference between CHAR and VARCHAR datatype in SQL?
a. CHAR is case-sensitive while VARCHAR is non case sensitive
b. CHAR store variable length strings while VARCHAR stores fixed length string
c. CHAR store fixed length strings while VARCHAR stores variable length string
d. CHAR is used storing numeric data while VARCHAR is used for text data
38. What is the primary purpose of unique key constraints in a relational databases?
a. To ensure that values in a column are NULL
b. To ensure that values in a column are unique
c. To define 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 database
a. PRIMARY KEY
b. UNIQUE KEY
c. NOT NULL
d. CHECK
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 database table to eliminate duplicate rows from the query
result?
a. group by
213 | P a g e
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. FLOAT
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 number of results from a SQL query?
a. fetchall()
b. fetchone()
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 database in python.
a. fetchmany()
b. fetchone()
214 | P a g e
c. fetchmulti()
d. fetchall()
50. To get all the records from result set, you may use .
a. cursor.fetchmany()
b. cursor.fetchall()
c. cursor.fetchone()
d. cursor.execute()
215 | P a g e
Assertion-and-Reason Type
In the following questions, Assertion (A) and Reason (R).
Choose the correct choice as:
(a) Both Assertion (A) and Reason (R) are the true and Reason (R) is a correct explanation of
Assertion (A).
(b) Both Assertion (A) and Reason (R) are the true but Reason (R) is not a correct
explanation of Assertion (A).
(c) Assertion (A) is true and Reason (R) is false.
(d) Assertion (A) is false and Reason (R) is true.
2. Assertion (A): HAVING clause can only be used with GROUP BY statement.
Reason (R): WHERE clause can be used in place of HAVING clause in GROUP
BY statement.
3. Assertion (A): LIKE operator is used for pattern matching in WHERE clause.
Reason (R): % and _ wildcard is used in LIKE operator for making a pattern.
8. Assertion (A): The HAVING clause is used to filter aggregated data in SQL queries.
Reason (R): The HAVING clause is used to group rows with similar values in one
or more column into result sets.
9. Assertion (A): Inner Join retrieves rows that have matching values in both tables
being joined.
Reason (R): Inner join excludes row with no matching values
10. Assertion (A): Between operator is used to filter data within a specified range.
Reason (R): Where clause works exactly same as between operator
216 | P a g e
Long Answer Type Questions:
1. Write MySQL command to create the table ‘Employee’ with the following structure and
constraint. Table: Employee
2. Write MySQL command 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
table
Activity_Name char(80) Not Null
Position char(30) Not Null
3. Anmol maintain that 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
217 | P a g e
Table: PHARMA
MID MNAME PRICE UNITS EXPIRY
M1 PARACETAMOL 12 120 2022-12-25
M2 CETRIZINE 6 125 2022-10-12
M3 METFORMIN 14 150 2022-05-23
M4 VITAMIN B-6 12 120 2022-07-01
M5 VITAMIN D3 25 150 2022-06-30
M6 TELMISARTAN 22 115 2022-02-25
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
218 | P a g e
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
ACNO NAME GENDER BALANCE
C1 RISHABH M 15000
C2 AAKASH M 12500
C3 INDIRA F 9750
C4 TUSHAR M 14600
C5 ANKITA F 22000
Table: TRANSACTION
ACNO TDATE AMOUNT TYPE
C1 2020-07-21 1000 DEBIT
C5 2019-12-31 1500 CREDIT
C3 2020-01-01 2000 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 EMPLOYEE table and 5 rows in 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
219 | P a g e
Table: EMPLOYEE
E_NO NAME DOJ DOB GENDER D_CODE Salary
1001 Vinay 2013-09-02 1991-09-01 MALE D001 250000
1002 Ruby 2012-12-11 1990-12-15 FEMALE D003 270000
1003 Anuj 2013-02-03 1987-09-04 MALE D005 240000
1007 Sunny 2014-01-17 1988-10-19 MALE D004 250000
1004 Rohit 2012-12-09 1986-11-14 MALE D001 270000
1005 Preeti 2013-11-18 1989-03-31 FEMALE D002 NULL
Note: DOJ refers to date of joining and DOB refers to date of Birth of employees.
Based on the above data, answer the following questions:
1. Identify the column which can be consider as primary key in EMPLOYEE table.
2. Identify the column which can be consider as primary key in DEPT table
3. What is the degree and cardinality of EMPLOYEE table?
4. What is the degree and cardinality of DEPT table?
5. Write SQL queries for the following:
1) Insert two new row in Employee table with following data:
1006 Rahul 2019-11-06 1992-01-04 MALE D003 156000
1008 Sonam 2022-01-06 1991-04-06 FEMALE D005 167000
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 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 letter ‘R’.
7) To display NAME of those employees whose name contains letter ‘n’.
8) To display NAME of those employees whose name has exact 5 letters.
9) To display D_NAME and CITY from table DEPT where D_NAME ends with letter ‘G’
and CITY is ‘DELHI’.
10) To display the maximum SALARY of EMPLOYEE table.
11) To delete data of all those employees whose age is less than 25.
12) To update SALARY to 230000 of those employee whose E_NO is 1004.
13) To change the sequence of DOB column in employee table and move it before DOJ
column.
14) To add a new column MOBILE int(20) before column SALARY in 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 EMPLOYEE table.
17) To display the average SALARY of EMPLOYEE table.
18) To display name of employees who have SALARY more than 200000 in ascending
order of NAME.
19) To display department wise average salary of employees.
20) To display 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’.
220 | P a g e
23) To change column name CITY to D_CITY in DEPT table.
24) To delete EMPLOYEE table.
25) To delete D_NAME column from DEPT table.
7. A garment store is considering to maintain their 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
Table: GARMENT
GCODE DESCRIPTION PRICE FCODE
10023 JEANS 1150 F01
10001 SHIRT 750 F02
10044 SHORTS 600 F05
10005 TIE 400 F04
10002 JACKET 5000 F01
10022 SOCKS 150 NULL
221 | P a g e
(viii) SELECT SUM(PRICE) FROM GARMENT;
(ix) SELECT * FROM GARMENT WHERE DESCRIPTION LIKE ‘%T%’ AND FCODE!
=’F02’;
(x) SELECT * FROM GARMENT ORDER BY PRICE DESC;
(xi) SELECT PRICE*10 FROM GARMENT;
(xii) SELECT COUNT(DISTINCT FCODE) FROM GARMENT;
(xiii) SELECT * FROM GARMENT WHERE FCODE NOT IN (‘F01’,’F02’) AND
PRICE<500;
(xiv) SELECT GCODE, PRICE FROM GARMENT WHERE FCODE IS NULL;
(xv) SELECT * FROM GARMENT WHERE PRICE >500 AND PRICE <1000;
8. Write the output of the following SQL queries based on table TRANSACTION given below:
Table: TRANSACTION
T_NO M_NO AMOUNT CARD_TYPE DATE STATUS
1 11 5000 CREDIT 2019-10-11 SUCCESS
2 11 170 CREDIT 2019-10-14 FAILURE
3 13 800 DEBIT 201-10-24 FAILURE
4 12 90 CREDIT 2019-11-10 SUCCESS
5 13 1400 DEBIT 2019-11-11 SUCCESS
6 11 500 DEBIT 2019-11-18 SUCCESS
7 13 1600 DEBIT 2019-11-27 FAILURE
Table: COMPANY
T_NO QTY_ISSUED COMPANY
1 15 SBI
3 50 ICICI
4 34 HDFC
222 | P a g e
9. The code given below reads the records from the table employee and displays only
those records of employee table who don’t lives in 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
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
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).
223 | P a g e
Statement 3- to create a cursor
Statement 4- to write a query that deletes the record with E_ID=’A101’ and E_Name
starts with letter ‘D’.
Statement 5- to remove the record permanently from the database.
11. Write a python program to delete all the tuples from 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 Employee table. Take these 5 records as
an 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 name of employee in Employee table whose
employee id is ‘E1001’ (Take updates name as an 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)
224 | P a g e
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]
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, 1
and 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]
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]
RED*
WHITE*
BLACK*
b.
WHITE*
BLACK*
c.
WHITE* WHITE*
BLACK* BLACK*
d.
YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*
[4]
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]
(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]
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]
[8]
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
[9]
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.
[10]
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
[11]
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],
[12]
["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
[13]
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
[14]
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.
[15]
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.
[16]
[17]
(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.
[18]
Sartaj, now wants to display the records of students whose fee is more than
5000. Help Sartaj to write the program in Python.
[19]
Class XII
Marking Scheme
SECTION A
1 False 1 mark for 1
correct
answer
[1]
ceieP0
BLACK*
[2]
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
a given transmission medium. / The amount of correct
definition
information that can be transmitted over a network.
[3]
(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]
½ 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]
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
ADD TypeSport char(10) NOT NULL; command
with ADD
25 10.0$20 1 mark for 2
each correct
10.0$2.0###
line of output
SECTION C
26 ND-*34 ½ mark for 3
each correct
character
27
[6]
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]
½ 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]
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]
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]
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]
[12]
½ 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)
[13]
Note: Any other correct logic may be marked
35 (i) Domain is a set of values from which an attribute ½ mark for 1+4=5
correct
can take value in each row. For example, roll no
definition
field can have only integer values and so its domain
½ mark for
is a set of 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
[14]
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
[15]
displaying
data
[16]
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.
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
segment T= min(1,6,0,-3,100)
(a) 1
(b) -3
(c) 0
(d) None of 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
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?
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)
32. Write a program in Python to get student details (Rollno, Name and marks) for 4
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. 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
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())
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 1
and 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 1
unique 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:
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
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
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
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
M1 PARACETAMOL 12 120 2022-12-25
M2 CETRIZINE 6 125 2022-10-12
M3 METFORMIN 14 150 2022-05-23
M4 VITAMIN B-6 12 120 2022-07-01
M5 VITAMIN D3 25 150 2022-06-30
M6 TELMISARTAN 22 115 2022-02-25
(a) Identify the attribute best suitable to be declared as a primary key.
(b) Anmol has received a new medicine to be added into 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:
MID MNAME PRICE EXPIRY
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.
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 followingset 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 suitablereason 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
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