[go: up one dir, main page]

0% found this document useful (0 votes)
87 views300 pages

Notes For All Chapters With Answer

Uploaded by

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

Notes For All Chapters With Answer

Uploaded by

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

LIST OF GROUP LEADER AND SUBJECT –

EXPERTS FOR PREPARATION OF SUPPORT


MATERIAL

CLASS – XII (2023-24)


SUBJECT: COMPUTER SCIENCE

1. MR. RAVI KANT PRINCIPAL


GBSSS ,HASTS
AL ,
DELHI(161805
8)
2. MS. PREETI DALAL LECTURER COMPUTER
SCIENCE GOVT. CO-ED SSS,
SEC 2 DWARKA(1821029)

3. MS. RUBY RANA LECTURER COMPUTER


SCIENCE, SBV ASHOK
NAGAR (1515002)

4. MR. ANUJ LECTURER COMPUTER


KUMAR DAGAR SCIENCE, G CO.ED
SV,JAFFARPUR KALAN
(1822055)
5. MR. ROHIT LECTURER COMPUTER
AHLAWAT SCIENCE, GBSSS ,HASTSAL
(1618058)
6. MR. SUNNY DAGAR LECTURER COMPUTER
SCIENCE GBSSS NO 3,
NAJAFGARH (1822057)

7. MR. VINAY GAHLOT LECTURER COMPUTER


SCIENCE GBSSS NO 1,
NAJAFGARH
( 1822063)
S.No Chapters Page No.
1 Python revision tour 1-21
2 Functions 22-49
3 Exception Handing 50-61
4 File Handling 62-101
5 Data Structures 102-112
6 Computer Networks 113-156
7 Database Management system 157-224
8 CBSE Previous Year Question Paper 2023 225-239
9 CBSE Sample paper 2023-24 239-270
10 Practice set 1 (unsolved) 271-278

11 Practice set 2 ( unsolved) 279-287


1|Page
CHAPTER- 1
PYTHON REVISION TOUR
ABOUT PYTHON:
1. Python is a high-level programming language developed by
Guido Van Rossum. The language was released in February 1991
and got its name from a BBC comedy series “Monty Python’s
Flying Circus”.
2. It is an interpreted and platform independent language i.e. the
same code can run on any operating system.
3. It can be used to follow both procedural and object-oriented
approaches to programming.
4. It is free to use and based on two programming languages: ABC language and Modula-3.

BASIC TERMS USED IN PYTHON:


1. Token / Lexical Unit: The smallest individual unit in a python program is known as
Token or Lexical Unit. A token has a specific meaning for a python interpreter.
Examples of tokens are: Keywords, Identifiers, Literals, Operators and Punctuators.

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.

DATA TYPES IN PYTHON:

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.

2. Dictionary is an unordered set of comma separated values where each value is a


key:value pair. We represent the dictionary using curly brackets {}. Keys in the
dictionary should be unique and they cannot be changed while values of the keys
can be changed.

3. Boolean allows to store only two values True and False where True means 1 and
False means 0 internally.

4. Sequence data types store a collection or set of values in an ordered manner. We


can traverse the values/elements using indexing. The sequence data types are:

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.

Del del statement is used to delete the structure of existing list.

count() Used to count the number of occurrences of the item we passed as


argument.
If item does not exist in list, it returns Zero.
reverse() Used to reverse the items of a list. It made the changes in the original
list
and does not return anything.
sort() Used to sort the items of a list. It made the changes in the original list
and sort the items in increasing order by default. We can specify reverse
argument as True to sort in decreasing order.
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.

TUPLE FUNCTIONS:
len() Returns number of elements in a tuple

max() Returns the element having maximum value in the tuple

min() Returns the element having minimum value

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.

Conditional statements in Python:


When the execution of any statement depends on some condition then such statements are
considered as Conditional Statements. In Python, we use if keyword for Conditional
statements.

It must contain valid condition which evaluates to either True or False.


Condition must follow by Colon (:), it is mandatory.
Statement inside if must be at same indentation level.
if statement can be of many forms:
 if without false statement
 if with else
 if with elif
 Nested if

Iterative statements in Python:


In Python, to perform repetition we have two keywords, for (Counting Loop) and while
(Conditional Loop)

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

2 Write the type of tokens from the following:


a) If -keywords
b) roll_no -identifiers

3 Consider a declaration L = (1, 'Python', '3.14').


Which of the following represents the data type of L?
a) List
b) Tuple
c) Dictionary
d) String

4 Identify the valid arithmetic operator in Python from the following.


a) ?
b) <
c) **
d) And

5 Which of the following statements is/are not python keywords?


a) False
b) Math
c) WHILE
d) Break

6 Which of the following is a valid keyword in Python?


a) False
b) return
c) non_local
d) none

7 State True or False.


"Identifiers are names used to identify a variable, function in a program".

8 Identify the invalid identifier out of the options given below.


a) Qwer_12
b) IF
c) Play123
d) Turn.over

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

10 Given the following Tuple


Tup (10, 20, 30, 50)
Which of the following statements will result in an error?
a) print (Tup [0])
b) print (Tup [1:2])
c) Tup.insert (2,3)
d) print(len (Tup))

11 Consider the given expression : 5<10 and 12>7 or not 7>4


Which of the following will be the correct output, if the given expression is
evaluated?
a) True
b) False
c) NULL
d) NONE

12 Which of the following will give output as [5,14,6] if lst=[1,5,9,14,2,6]?


a) print(lst[0::2])
b) print(lst[1::2])
c) print(lst[1:5:2])
d) print(lst[0:6:2])

13 The return type of the input() function is


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

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))

16 Which one of the following is the default extension of a Python file?


a) .exe
b) .p++

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) #

18 Which of these about a dictionary is false?


a) The values of a dictionary can be accessed using keys
b) The keys of a dictionary can be accessed using values
c) Dictionaries aren’t ordered
d) Dictionaries are mutable

19 Which is the correct form of declaration of dictionary?


a) Day={1:’monday’,2:’tuesday’,3:’wednesday’}
b) Day=(1;’monday’,2;’tuesday’,3;’wednesday’)
c) Day=[1:’monday’,2:’tuesday’,3:’wednesday’]
d) Day={1’monday’,2’tuesday’,3’wednesday’]

20 What will be the output of the following statement:


print(3-2**2**3+99/11)
a) 244
b) 244.0
c) -244.0
d) Error

21 What is the output of following code:


T=(100) print(T*2)
a) Syntax error
b) (200,)
c) 200
d) (100,100)

22 Identify the output of the following Python statements:


x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]] y = x[1][2] print(y)
a) 12.0
b) 13.0
c) 14.0
d) 15.0

23 Select the correct output of the code :


S= "Amrit Mahotsav @ 75" A=S.partition (" ") print (a)
a) ('Amrit Mahotsav', '@', '75')
b) ['Amrit', 'Mahotsav', '@', '75']
c) ('Amrit', 'Mahotsav @ 75')
d) ('Amrit', '', 'Mahotsav @ 75')

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

25 Identify the output of the following Python statements.


b=1
for a in range(1, 10, 2):
b += a + 2
print(b)
a) 31
b) 33
c) 36
d) 39

26 A tuple is declared as T = (2,5,6,9,8). What will be the value of sum(T)?

27 Identify the output of the following Python statements.


lst1 = [10, 15, 20, 25, 30]
lst1.insert( 3, 4)
lst1.insert( 2, 3)
print (lst1[-5])
a) 2
b) 3
c) 4
d) 20

28 Evaluate the following expression and identify the correct answer.


16 - (4 + 2) * 5 + 2**3 * 4
a) 54
b) 46
c) 18
d) 32

29 Fill in the blank.


function is used to arrange the elements of a list in ascending
order.
a) sort()
b) ascending()
c) arrange()
d) asort()

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"]

31 Identify the valid declaration of L: L = [‘Mon’, ‘23’, ‘hello’, ’60.5’]


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

32 Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90).
What will be the output of print (tup1 [3:7:2])?
a) (40,50,60,70,80)
b) (40,50,60,70)
c) [40,60]
d) (40,60)

33 If the following code is executed, what will be the output of the following code?
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

36 Given is a Python list declaration :


Listofnames=["Aman", "Ankit", "Ashish", "Rajan", "Rajat"]

16 | P a g e
Write the output of:
print (Listofnames [-1:-4:-1])

37 What will be the output of the following code:


Cities=[‘Delhi’,’Mumbai’]
Cities[0],Cities[1]=Cities[1],Cities[0]
print(Cities)

38 What will be the output of the following code?


tup1 = (1,2,[1,2],3)
tup1[2][1]=3.14
print(tup1)
a) (1,2,[3.14,2],3)
b) (1,2,[1,3.14],3)
c) (1,2,[1,2],3.14)
d) Error Message

39 Select the correct output of the code:

a) PYTHON-IS-Fun
b) PYTHON-is-Fun
c) Python-is-fun
d) PYTHON-Is –Fun

40 What will be the result of following python code?

41 For a string S declared as S=”PYTHON”, Which of the following is incorrect:


a) N=len(s)
b) T=S
c) “T” in S
d) S[0]=”M”

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

43 What will be the output of following Python code?

a) False
b) True
c) Error
d) None

44 Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and


values are Monday, Tuesday and Wednesday respectively.

45 Assertion(A): List is an immutable data type


Reasoning(R): When an attempt is made to update the value of an immutable
variable, the old variable is destroyed and a new variable is created by the same
name in memory
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

46 Assertion (A): Python Standard Library consists of various modules.


Reasoning(R): A function in a module is used to simplify the code and avoids
repetition.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

47 Assertion(A): List is an immutable data type


Reasoning(R): When an attempt is made to update the value of an immutable
variable, the old variable is destroyed and a new variable is created by the same
name in memory.
a) Both A and R are true and R is the correct explanation for A
b) Both A and R are true and R is not the correct explanation for A
c) A is True but R is False
d) A is false but R is True

48 Assertion (A) : List can not become key in a dictionary.


Reasoning(R) : Only integers can be keys in a dictionary.

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)

3 Evaluate the following Python expression:


a) 2*3+4**2-5//2
b) 6<12 and not (20>15) or (10>5)

4 Predict the output of the following code:


S="LOST"
L=[10,21,33,4]
D={}
for I in range(len(S)):
if I%2==0:
D[L.pop()]=S[I]
else:
D[L.pop()]=I+3
for K,V in D.items():
print(K,V,sep="*")

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)

2 Predict the output of the Python code given below:

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)

2 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES


as an argument and displays the names (in uppercase)of the places whose names
are longer than 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
3 Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n
is a numeric value by which all elements of the list are shifted to left. Sample Input

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

Defining a function in Python:


Name the function and specifies what to do when the function is called. Python
interpreter ignores the function definition until the function is called.

Calling a function:
Calling the function actually performs the specified actions with the indicated
parameters

Function Definition in Python


In Python a function is defined using the def keyword

 Arguments: Information can be passed into functions as arguments.


Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

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:

Here's what you need to know about the `return` statement:


1. Returning a Value:
When you want to return a specific value from the function, you can use the
`return` statement followed by the value you want to return.
Note: The function will stop executing immediately after the `return`
statement is encountered, and the value will be passed back to the caller.

2. Returning Multiple Values:


Python allows you to return multiple values from a function as a tuple. You
can simply separate the values with commas after the `return` statement.

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.

The `return` statement is a powerful tool that enables functions to produce


results and pass data back to the calling code. Understanding how to use it
correctly will help you design and implement effective functions in Python.

Scope of a variable:
In Python, the scope of a variable refers to the region of the program where the
variable is accessible. The scope determines where a variable is created, modified, and
used.

Global Scope:
● 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:

Passing list as argument to the function:


Please note that when a list if passed as arguments , the original copy of list is passed
to the function i.e if any change is made at any index in the list inside the function , it
is reflected in original list . That is because list is a mutable datatype and in Python,
when you pass a list as an argument to a function, you are actually passing a reference
to the list rather than a copy of the list. This means that the function parameter will
point to the same memory location as the original list. As a result, any changes made
to the list within the function will be reflected in the original list outside the function.

However, if you assign a different list to a variable inside a function in Python, it will
create a new local variable that is separate from any variables outside the function.
This local variable will only exist within the scope of the function, and changes made
to it won't affect the original list outside the function.

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:

Types of arguments passed to a function:


Positional Arguments:
● These are the most common type of arguments and are matched to the
function parameters based on their positions. The first argument corresponds
to the first parameter, the second argument corresponds to the second
parameter, and so on.
● The number and order of positional arguments must match the function's
parameter list.

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()

3. What is the scope of a variable defined inside a function?


a) Global scope
b) Local scope
c) Universal scope
d) Function scope

4. In Python, can a function return multiple values simultaneously?


a) Yes
b) No

5. What is the purpose of the "return" statement in a function?


a) It specifies the type of the function.
b) It defines the input parameters of the function.
c) It indicates the end of a function.
d) It returns a value from the function to the caller.

6. Which of the following module functions generates an integer?


a) randint()
b) uniform()
c) random()
d) all of these

7. The return type of the input() function is


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

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

9. Which of the following components are part of a function header in Python?


a) Function Name
b) Return Statement
c) Parameter List
d) Both a and c

10. Which of the following function header is correct?


a) def cal_si(p=100, r, t=2)
b) def cal_si(p=100, r=8, t)
c) def cal_si(p, r=8, t)
d) def cal_si(p, r=8, t=2)
11. Which of the following is the correct way to call a function?
a) my_func()
b) def my_func()
c) return my_func
d) call my_func()
12. Consider the code given below:
Which of the following statements should be given in the blank for #Missing
Statement, if the output produced is 110?

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

15. Statistics.mode([10,10,11,12,14,11,11,15,15,16,15]) will return


(consider module is imported)
a) 10
b) 15
c) 11
d) Error

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

18. What will be the output of the following code?


>>> def a(b=11, c=21):
b += 13
c -= 13
return b+c 0.77
>>> print(a(25), a(35))
a) 15 18
b) 46 56
c) 25 35
d) 13 12

19. What will be the output of the following code?


num=100
def showval(X):
global num
num = 85
if(X%2==0):
num += X
else:
num -= X
print(num,end="#")
showval(33)
print(num)
a) 100#52
b) 85#52
c) 85#33
d) 185#52

20. Find the impossible option from the following


>>> import random
>>> L=[i for i in
range(random.randint(3,5))] a) [0, 1, 2, 3]
b) [0, 1, 2, 3, 4]
c) [0, 1, 2, 3, 4, 5]
d) [0, 1, 2]

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

22. Predict output:

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]

23. Predict output:

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#

28. Predict output:

40 | P a g e
29. Predict output:

30. Rewrite the following code after removing the syntactical errors (if any).
Underline each correction.

31. What will be the output of the following code?


def my_func(var1=100, var2=200):
var1+=10
var2 = var2 - 10
return var1+var2
print(my_func(50),my_func())
32. What will be the output of the following code?

33. What will be the possible outcomes:

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?

35. What is the output of the following code snippet?

i. ii.

36. What will be the output of the following code?

37. Find and write the output of the following Python


code: def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#" print(m)

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 #

40. Write the output of the following Python code:

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

43. Predict output :

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

2 Score=[ 25,20,34,56, 72, 63]


Myscore = Score[2 + random.randint(0,2)]
print(Myscore)

Output Options :
a) 25
b) 34
c) 20
d) None of the above

3 Marks = [99, 92, 94, 96, 93, 95]


MyMarks = Marks [1 + random.randint(0,2) ]
print(MyMarks)

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:

50. Predict output :

i. ii.

48 | P a g e
iii. iv.

51. What will be the output of the following code fragments:

i. ii.

iii. iv.

52. What will be the output of the following Python Code?

53. Predict output:

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.

3 Write a function update_list(L) that receives a list as arguments and


increases the value of even elements by 2.
For example: if the list is [2,4,6,7,9]
after execution of function, the list should be : [4,6,8,7,9]

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.

SYNTAX ERROR SEMANTIC ERROR LOGICAL ERROR RUN TIME ERROR


It occurs when we put It occurs when the code It may occur when It occurs at the time of
some incorrect is correct according to there may be some program execution.
punctuation, incorrect syntax but it is not improper sequence of Such errors produce
word sequence or there meaningful. The code statements or incorrect output for
are some undefined will not behave as incorrect use of specific values of input.
terms or missing expected. operator. It will not These errors are also
parenthesis. For example: stop a program from called Exceptions,
Syntax errors are also A = 10 executing but will which occur when
called as Parsing errors. B = ”hello” produce incorrect something unexpected
For example: Result = A + B output. It will happens leading to stop
>>> p=2(num1+num2) Here, The code will generate incorrect the program execution.
This statement is execute as it has correct output for every value For example:
mathematically correct syntax but will not of input. 5. Division by zero
but python interpreter generate expected For example: 6. Finding square
will raise SYNTAX error output. If we want to find sum root of negative
as there is no sign of two numbers and number.
present between 2 and write the following 7. Insufficient
parenthesis. The correct code: memory available
statement will be: A, B = 10, 15 on computer.
>>> p=2*(num1+num2) C=A*B 8. Trying to open a
print (“Sum is: “, C) file that does not
Here, the code will exist.
generate A * B but we
wanted to find Sum.
Hence it is a logical
error.

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:

Use of multiple “except” block:


Sometimes, it may happen that a single piece of code in a program might have more than
one type of error. If such an event happens, we can use multiple except blocks for a single
try block.

Example 1:

54 | P a g e
The output will be:

Example 2:

We can also handle exceptions without naming them.

The output will be:

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.

The output will be:

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.

The output will be:

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.

2 When might you use the 'finally' block in exception handling?


a) To handle exceptions that are expected to occur frequently.
b) To provide a resolution for every possible error.
c) To close resources that were opened in the 'try' block, regardless of whether an
exception occurred or not.
d) To avoid having to use 'except' blocks.

3 What will be the output of the following code snippet?

a) Division by zero!
b) Arithmetic error occurred!
c) No error!
d) This code will raise a syntax error.

4 Which of the following is NOT a standard built-in exception in Python?


a) ValueError
b) IndexError
c) NullPointerException
d) KeyError

5 What is an exception in programming?


a) An error that occurs during runtime
b) A warning message from the compiler
c) A comment in the code
d) A statement that terminates the program

6 What is the purpose of the "try" block in a try-except construct?


a) To handle the exception by executing specific code
b) To specify the type of exception to be thrown
c) To define a custom exception class
d) To ensure a specific block of code always executes

7 Which of the following exceptions in Python is not a built-in exception?


a) ValueError

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

9 Assertion (A): The "finally" block in Python is always executed, regardless of


whether an exception is raised or not.
Reasoning (R): The "finally" block contains code that is guaranteed to execute,
whether an exception occurs within the "try" block or not.
A. Both A and R are true and R is correct explanation of A
B. Both A and R are true but R is not correct explanation of A
C. A is True but R is False
D. R is True but A is False

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:

Predict the output when:


a) The user enters "0" .
b) The user enters "5".
c) The user enters "abc".

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)

15 Rewrite the following code after handling all possible exceptions.


num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)

16 Consider the code given below:


L = [‘s’, 45,23]
Result = 0
for x in L:
print (“The element is “, x)
Result += x
print(“The addition of all elements of L is: “, Result)
Which of the following error will be raised by the given Python code?
a) NameError
b) ValueError
c) TypeError
d) IOError

17 Code snippet:

Predict the output when:


a) The user enters "10" for both numbers.

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.

18 Which of the following statements is true?


a). The standard exceptions are automatically imported in Python programs.
b). All raised standard exceptions must be handled in Python.
c). When there is deviation from the rules of a programming language, a semantic
error is thrown.
d). If any exception is thrown in try block, else block is executed.

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')

Programming based question:


1 Create a simple calculator program that takes two numbers and an operator (+, -,
*, /) as input. Implement exception handling to handle cases like division by zero
and invalid operators.

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

3 Create a program that connects to a database and performs database operations


(e.g., insert, update, delete). Use exception handling to deal with database-related
exceptions, such as connection errors or SQL syntax error.

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.

c. In this we need to close the file.


d. In this mode if we are writing into a file then we have to close the file
otherwise our data will not be written into the file till now the file is not
closed. The data remains in the output buffer and when we close the file then
data is shifted from the output buffer to the file.
e. flush( ): It forces the data waiting in the buffer immediately written into the
file without waiting for closing of file.

2. with open(“file name”,”access specifier”) as file_object:


a. i.e. with open(“test.txt”,”r”) as f:

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.

Close Files: close( ) function is used to close files in python.

a. file_object.close( )
b. i.e. f.close( )

Access Specifiers in Files:


Access Access Access Description File Pointer
Mode Mode Mode for Position
for Text for CSV Files
Files Binary
Files

r Rb r Read mode. Opens a file for reading.If Beginning of


the file does not exist, open() raises a File
FileNotFoundError.

r+ rb+ It opens the file for both reading and Beginning of


writing. If the file does not exist, open() File
raises a FileNotFoundError.

w Wb w Write mode. It opens the file for writing Beginning of


only. If the file exists, the content of File
the file will be removed. If the file does
not exist, it is created.

w+ wb+ The w+ mode opens the file for both Beginning of


writing and reading. Like w, if the file File
exists, then the content of the file will
be removed. If the file does not exist, it
is created.

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.

File Object Methods (seek( ) & tell( ))


Method Prototype Description

seek( ) Syntax: seek() function is used to change


<file_object>.seek(<offset>,<from_where>) the position of the File Handle to a
given specific position. File handle is
where:
like a cursor, which defines from
offset: number of positions to be more forward where the data has to be read or
written in the file.
from_where: it defines to reference point
Then it returns the new absolute position.
i.e.
0: sets the reference point at the
f.seek(10,0) beginning of the file. (default)
Here, f is the file handle, 10 is the offset (it 1: sets the reference point at the
moves the cursor 10 bytes forward), 0 means current file position.
reference point at the beginning of file.
2: sets the reference point at the
end of the file

Note: In the case of a text file we


can use only ‘0’ as a reference
point.

tell( ) Syntax: <file_object>.tell( ) tell() function returns the current


position of the file object. This

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

Working with Text Files:


1. Reading data from a file.
2. Writing data into a file.

Reading data from files


There are three ways to read data from text file:

1. read function i.e. read( )


2. readline function i.e. readline( )
3. readlines function i.e. readlines( )

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( )

file_pointer.read(n): It will read the maximum n bytes/characters from the file.


f.read(7) # it will read 7 bytes/characters from the position of file pointer.

file_pointer.read( ): It will read the entire content of the file.


f.read( ) # it will read all the data of the file from the position of file pointer.

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

Content in “Topper.txt” file

But, we want these names in separate lines.

71 | P a g e
Output:

Content of “Topper.txt” File:

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

Content of “Toppers.txt” file:

Write a program in python to count vowels, consonants, digits, spaces, special characters,
spaces, words and lines from a text file named “student.txt”.
Content of File:

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.

Working in Binary files:


Pickle module: pickle module is used in binary file for load( ) and dump( ) methods which
are used for reading and writing into binary file respectively.
Pickling: It is the process of converting python object into byte stream. Pickling is done at
the time of writing into a binary file.
Unpickling: It is the process of converting a byte stream into python object. Unpickling is
done at the time reading from a binary file.

dump( ): it is used to write data into binary file.


Syntax: identifier = pickle.dump(data , file_pointer)
Example: a= “My name is Anuj”
pickle.dump(a,f) #here ‘a’ contains data and ‘f’ is a file pointer.

Program Code Input Details

76 | P a g e
File Content

load( ): it is used to read data from binary file.


Syntax: identifier = pickle.load(file_pointer)
Example: data = pickle.load(f) #Here ‘data’ is an identifier and ‘f’ is a file pointer.

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.

WRITING INTO CSV FILES


Code: Output in IDLE:

Result in Notepad: Result in Excel:

81 | P a g e
Code: Output in IDLE:

Result in Notepad: Result in Excel:

Code: Output in IDLE:

Result in Notepad: Result in Excel:

82 | P a g e
READING FROM CSV FILES

File Content:

Code: To read all records of csv file Output:

Code: To display all the records in which Output:


name starts with ‘A’

ABSOLUTE AND RELATIVE PATH:


1. Absolute path is a path that starts from the root directory of the file system or we can
say that it describes how to access a given file or directory, from the starting of the file
system.
2. Relative path is a path that is relative to the current working directory or we can say
that is interpreted from the perspective of the current working directory.

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)

2. Which function is used to open a file in Python?


a. open() b. read() c. write() d. close()

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()

6. Which of the following statements are True


(a) When you open a file for reading, if the file does not exist, an error occurs
(b) When you open a file for writing, if the file does not exist, a new file is created
(c) When you open a file for writing, if the file exists, the existing file is
overwritten with the new file
(d) All of the mentioned

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

9. Which of the following option is not correct?


a. if we try to read a text file that does not exist, an error occurs.
b. if we try to read a text file that does not exist, the file gets created.

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

20. Which of the following statement is true?


a) pickling creates an object from a sequence of bytes
b) pickling is used for object serialization
c) pickling is used for object deserialization
d) pickling is used to manage all types of files in Python

21. Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is


the file object. What is the default value of reference_point?
a) 0 b) 1 c) 2 d) 3

22. Which of the following character acts as default delimiter in a csv file?
a) (colon) : b) (hyphen) - c) (comma) , d) (vertical line) |

23. Syntax for opening a Student.csv file in write mode is myfile =


open("Student.csv","w",newline=''). What is the importance of newline=''?
a) A newline gets added to the file
b) Empty string gets appended to the first line.
c) Empty string gets appended to all lines.
d) EOL translation is suppressed

24. What is the correct expansion of CSV files?


a) Comma Separable Values
b) Comma Separated Values
c) Comma Split Values

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()

28. Suppose content of 'Myfile.txt' is:

Twinkle twinkle little star


How I wonder what you
are Up above the world so
high Like a diamond in the
sky

What will be the output of the following code?

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()

30. What is the significance of the tell() method?


a) tells the path of file
88 | P a g e
b) tells the current position of the file pointer within the file
c) tells the end position within the file
d) checks the existence of a file at the desired location

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())

32. The syntax of seek() is :


file_object.seek(offset [, reference_point]) What is the default value of
reference_point? a) 0 b) 1 c) 2 d) 3

33. Assume the content of text file, 'student.txt' is:


Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran

What will be the data type of


data_rec? myfile = open("Myfile.txt")
data_rec =
myfile.readlines()
myfile.close()

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


34. Mr. Manish Kumar is writing a program to create a CSV file “user.csv” which will contain
user name and password for some entries. He has written the following code. As a
programmer, help him to successfully execute the given task.

a) Name the module he should import in Line 1.


b) In which mode, Manish should open the file to add data into the file
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.

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.

Help him complete the below code:

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

42. What mode should be used to open a file for reading


only? a). r b.) w c.) a d.) r+

43. What mode should be used to open a file for writing


only? a.) r b.) w c.) a d.) w+

44. What mode should be used to open a file for appending


data? a.) r b.) w c.) a d.) a+

45. Which mode is used for both reading and writing in a


file? a) . r+ b.) w+ c.) a+ d.) x+

46. Which method is used to read data from a file in Python?


a. read() b. write() c. seek() d. close()

47. Which method is used to write data to a file in Python?


a. read() b. write() c. seek() d. close()

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()

49. Which method is used to close a file in Python?


a. read() b. write() c. seek() d. close()

50. What is the default mode in which a file is opened in Python?


a. r b. w c. a d. None of the above

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

56. What is the purpose of file handling in Python?


a. To store data permanently
b. To perform mathematical operations on files
c. To create graphical user interfaces
d. To handle network connections

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.

58. What is the purpose of the 'with' statement in file handling?


a. It is used for creating new files.
b. It automatically closes the file when done.

93 | P a g e
c. It is used for reading binary files.
d. It is used for appending data to files.

59. What is the purpose of the 'tell()' method in file handling?


a. It tells you the size of the file.
b. It returns the current cursor position.
c. It tells you the number of lines in the file.
d. It returns the file's modification time.

60. What is the purpose of the 'os' module in file handling?


a. It provides functions for file operations.
b. It is used for performing mathematical operations.
c. It handles network connections.
d. It creates graphical user interfaces.

61. Which method is used to delete a file in Python?


a. os.delete() b. os.remove() c. file.delete() d. file.remove()

62. Which method is used to rename a file in Python?


a. os.delete() b. os.remove() c. file.delete() d. file.remove()

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

66. Which character is used as the path separator in


Python? a. / b. \ c. : d. ,

67. What does CSV stand for?


a. Comma-Separated Values
b. Computer System Variables
c. Centralized Storage Values
d. Common String Values

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()

71. In a CSV file, how are values typically separated?


a. By commas (`,`)
b. By spaces (``)
c. By semicolons (`;`)
d. By tabs (`\t`)

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.

76. Suppose content of 'Myfile.txt' is:


Honesty is the best policy.
What will be the output of the following code?
myfile = open("Myfile.txt")
x = myfile.read()
print(len(x))
myfile.close()

77. Suppose content of 'Myfile.txt' is


Culture is the widening of the mind and of the spirit.
What will be the output of the following code?

myfile = open("Myfile.txt")
x = myfile.read()
y = x.count('the')
print(y)
myfile.close()

78. Suppose content of 'Myfile.txt' is

Humpty Dumpty sat on a wall


Humpty Dumpty had a great fall

96 | P a g e
All the king's horses and all the king's men
Couldn't put Humpty together again

What will be the output of the following code?


myfile = open("Myfile.txt")
record = myfile.read().split()
print(len(record))
myfile.close()

79. Suppose content of 'Myfile.txt' is

Ek Bharat Shreshtha Bharat


What will be the output of the following code?

80. Consider the following directory structure.

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

81. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage).


Write a function countrec() in Python that would read contents of the file
“STUDENT.DAT” and display the details of those students whose percentage is above
75. Also display number of students scoring above 75%

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.

The output of the function should be: Count of Me/My in file: 4

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:

Updated information As simplified by official


websites. The EUCount() function should display the
output as: A or a:4
M or m :2

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:

Total number of lines: 3

88. A binary file "PLANTS.dat" has structure (ID, NAME, PRICE).

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:

Once upon a time, there was a woodcutter


He lived in a little house in a beautiful, green wood.
One day, he was merrily chopping some wood.
He saw a little girl skipping through the woods, whistling happily.
The girl was followed by a big gray wolf.

Then the function should display output as :

He lived in a little house in a beautiful, green wood.


He saw a little girl skipping through the woods, whistling happily.

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:

On seat2 VIP1 will sit and


On seat1 VVIP2 will be sitting

Output will be:

Number of words ending with a digit are 4

91. A binary file "PATIENTS.dat" has structure (PID, NAME, DISEASE).

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

#incomplete Code With Errors


Import CSV #Statement-1
With open( ’ ’newline=’ ‘) as File: #Statement-2
ER=csv. #Statement-3
for R in range(ER): #Statement-4
If == ‘Chemistry’: #Statement-5
print( ’ ) #Statement-6

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.

Types of Data Structure:

Primitive Data Structures


Primitive Data Structures contain simplified data values and are directly operated by
machine level instructions. For example, integer, real, character etc. are primitive data
structures.

Non-Primitive Data Structures


Non-Primitive Data Structures are derived from the primitive data structures. These are of
two types: Linear data structures, that are single level data structures having their elements
in a sequence like stack, queue and linked list while Non-linear data structures that are
multilevel data structures like tree and graph.

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:

2. A list contains following record of customer: [CBSE EXAM 2022-23]


[Customer_name, Room_type]
Write the following user defined functions to perform given operations on the 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:

If the dictionary contains the following data:

Vehicle = {‘Santro’: ‘Hyundai’, ‘Nexon’: ‘TATA’, ‘Safari’ : ‘Tata’}

The stack should contain:

Safari

Nexon [CBSE EXAM 2022-23]

106 | P a g e
QUES: A list, NList, contains following record as list elements:

[City, Country, distance from Delhi]

Each of these records are nested together to form a nested list. Write the following user
defined functions in Python to perform the specified operations on the stack named travel.
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

2 In Stack, all operations takes place at .


1. Top
2. Front
3. Rear
4. Any

3 Insertion and Deletion operations of Stack are known as respectively.


A. Insertion and Deletion
B. Push and Pop
C. Pop and Push
D. Enqueue and Dequeue

4 When a Stack is empty, the TOP will reset to:


● NONE
● 1
● -1
● None of the above.

5 Which of the following is not an inherent application of Stack?


● Reversing a String.
● Evaluation of postfix expression.
● Implementation of recursion.
● Job Scheduling.

6 Data structures are:


● Network structures.
● Group of data
● Different types of data
● Different operations on data

ASSERTION & REASON:


(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 correct explanation for A.
(C): A is true but R is false.
(D) : A is false but R is true.
● ASSERTION (A): Using append(), many elements can be added at a time.
REASON(R): For adding more than one element, extend() method can be used.

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): LIFO is a technique to access data from queues.


REASON(R): LIFO stands for Last In First Out.

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

● ASSERTION (A): A stack is a LIFO structure.


REASON (R): Any new element pushed into the stack always gets positioned at the
index after the last existing element in the stack.

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.

9 A list contains following record of a customer:


[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named
‘status’:
(i) Push_element() - To Push an object containing name and Phone number of customers
who live in Goa to the stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display “Stack
Empty” when there are no elements in the stack.
For example: If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
he stack should contain
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”]
The output should be:
[“Ashmit”,”1010101010”]
[“Gurdas”,”9999999999”] Stack Empty

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.

12 - Create a stack to manage student records. Each student record is represented as a


dictionary containing attributes like student ID, name, and GPA.

- Implement a `push_student` method to push student records onto the stack 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}....}

Create a stack that stores dictionaries as elements.

- Implement a `push_nested_dict` method to push a values of nested dictionary onto the


stack.

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

15 A list contains following record of customer:

[Customer_name, Room Type]


Write the following user defined functions to perform given operations on the stack named
'Hotel':
(i) Push Cust() - To Push customers' 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 lists with customer details are as follows:
[["Siddarth", "Delux"] ["Rahul", "Standard"] ["Jerry", "Delux"]]
The stack should contain
Jerry
Siddharth
The output should be:
Jerry
Siddharth
Underflow

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"}

The stack should contain

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.

Advantages of Computer Network:


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

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.

Data Transfer Rate:


It is the amount of data transferred per second by a communication channel or a computing
storage device. When applied to the data transmission rate, the abbreviations like K, M, G, T
are added to the data rate that denote Kilo, Mega, Giga, and Tera respectively. They work in
the power of 1024. Example 1 GB = 1024 MB, 1 TB = 1024 GB.

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

Wired Transmission Medias


In computer networks, wired transmission media refers to the physical mediums through
which data is transmitted from one device to another. These media provide a pathway for
electrical signals to travel, facilitating communication between network devices. Some
common types of wired transmission media used in computer networks include:

A. Twisted Pair Cable:


Unshielded Twisted Pair (UTP) and Shielded Twisted Pair (STP) cables are widely used for
Ethernet networking. UTP is commonly used in home and office networks
due to its cost-effectiveness and ease of installation. STP provides
better noise immunity and is suitable for environments with higher
electromagnetic interference.

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.

E. Power Line Communication (PLC):


PLC enables data transmission over existing electrical power lines. It is sometimes used to
provide networking in situations where laying dedicated network cables is impractical.

F. Structured Cabling Systems:


Structured cabling refers to a standardized cabling infrastructure used to support various
communication technologies within a building or campus. It typically involves a combination
of twisted pair and fiber optic cables organized in a structured manner.
The choice of wired transmission media depends on factors such as data transfer speed
requirements, distance, environmental conditions, and cost considerations. Each type of
cable has its advantages and limitations, and network designers choose the most
appropriate medium based on the specific needs of the network.

Wireless Transmission Medias

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:

A. Wi-Fi (Wireless Fidelity):


Wi-Fi is a widely used wireless technology for local area networking (LAN) and internet
access. It operates in the unlicensed radio frequency bands, such as 2.4 GHz and 5 GHz,
allowing multiple devices to connect to a wireless access point (router).

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.

E. Radio Frequency Identification (RFID):


RFID uses radio waves to identify and track objects equipped with RFID tags. It
is used in various applications, including supply chain management, access
control, and asset tracking.

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.

G. Near Field Communication (NFC):


NFC enables short-range communication between devices (typically within a few
centimeters). It is commonly used for contactless payment systems and data exchange
between smartphones.

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.

I. Wireless Sensor Networks (WSNs):


WSNs consist of interconnected sensors that wirelessly communicate with each other to
gather and transmit data from the environment. They are used in various applications, such
as environmental monitoring and industrial automation.

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.

B. Registered Jack-45 (RJ-45):


Registered Jack-45 of Rj-45 is an 8-wire connector that is
commonly used on computers in a local area network. It
looks similar to a standard phone connector (RJ-11), but
is wider than the RJ-11 connector, as it uses 8 wires
instead of 4. These are used to connect computers in
Ethernet LAN.

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.

2. This creates a multi-level structure, with each level representing a different


generation of devices.
Tree topology is commonly used in wide area networks (WANs) to interconnect
different local area networks (LANs) or subnets in a hierarchical manner. It is also found
in some enterprise networks and telecommunications networks.

Advantages of Tree Topology:


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

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

PAN – Personal Area Network:


A personal area network (PAN) is designed for interconnection between devices typically
located within the range of 10 meters approx. These are used to connect personal use
devices like smartphones, laptops, tablets, wearable devices and other peripherals.
Bluetooth and Wi-Fi are the commonly used technologies for establishment of
PANs. PANs find applications in various scenarios, such as:
a. Wireless Headsets: For establishing connections between computers/smart phones
with headsets/head phones.
b. Personal health Devices: For pairing fitness related trackers/ smart phones for
monitoring health and workout timings.
c. Home automation: For connecting home use and
safety devices to a central controller such as smart
phone.
d. File Transfer: For ensuring smooth and fast transfer
of files between laptops, tablets etc.
e. Security: To enhance and implement security
protocols like encryption to ensure data privacy and
prevent unauthorized access to the connected
devices.
f. Ad-Hoc Networking: These are often used as Ad-Hoc networks for use as and when
required. These networks are established and disbanded as per the requirement.
Also, the devices can quickly connect to the network and disconnect whenever they
are in or out of range.

LAN – Local Area Network


A local area network (LAN) is designed for implementation between devices that are located
within a limited geographical area generally within the range of approximately 1 – 10 KM.
this network can be setup using wired or wireless transmission medias, and can be
controlled by an individual or an organization. It is also known as Intranet as it is a network
within an organization.
a. These can use various topologies such as star, bus, ring, or mesh. The most
commonly used topology for LANs is the Star topology, where all the devices are
connected to a central switch or hub.

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.

MAN – Metropolitan Area Network:


It is a network infrastructure that covers a larger geographical area than a Local Area
Network (LAN) but smaller than the Wide area Network (WAN). These use various
connectivity technologies including fiber-optic cables, microwave links and wireless
technologies to interconnect devices and networks within the area of a city and ranges
between 5 – 100 KMs.
a. MANs often use high speed technologies like fiber-
optic cables, microwave links to provide fast and
reliable data transmission between network
nodes.
b. These are often used by government agencies and
large educational institutions to interconnect LANs
and share resources like files, databases, and
applications.
c. They often use different Internet Service Providers
(ISPs) for effective data communication thereby strengthening the backbone of the
Internet.
d. These can be either privately owned, cooperative, or government owned to provide
services to the public.
e. These networks have grown rapidly in the past few years as the spans of cities have
increased rapidly.
f. The network security plays a crucial role in the MANs and increases the cost incurred
due to wide area coverage.
They play a significant role in interconnecting local networks within a city, enabling efficient
data exchange and facilitating communication among various entities in the metropolitan
region.

WAN – Wide Area Network:


It is a type of computer network that covers a vast geographical area spanning among cities,
countries, or even continents.
a. These use various technologies like leased lines, fiber optic cables, and satellite links.
b. Since it is the expanded form of MAN, it is considered as the backbone.

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.

Difference between LAN, MAN, and WAN

Network Protocols:
These are the set of rules that are required to run the internet keeping in mind the security
of data for sake of users.

1. TCP (Transmission Control Protocol):


a. Connection-oriented protocol for reliable data transmission.
b. Provides error checking, retransmission of lost packets, and in-order delivery.
c. Slower than UDP due to the additional overhead for reliability.

2. UDP (User Datagram Protocol):

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

4. HTTP (Hypertext Transfer Protocol):


a. Used for web page communication between a client (browser) and a web server.
b. Supports request methods like GET, POST, PUT, DELETE, etc.

5. HTTPS (Hypertext Transfer Protocol Secure):


a. Secure version of HTTP that uses encryption (TLS/SSL) to protect data during
transmission.
b. Uses port 443.

6. FTP (File Transfer Protocol):


a. Used for transferring files between a client and a server.
b. Can operate in active or passive mode.

7. SMTP (Simple Mail Transfer Protocol):


a. Used for sending email messages between servers.
b. Port 25 is used for unencrypted communication, and port 587 is used for
encrypted communication (SMTPS).

8. POP3 (Post Office Protocol version 3):


a. Used for retrieving email from a remote server to a local email client.
b. POP3 downloads emails to the client and removes them from the server.

9. IMAP (Internet Message Access Protocol):


a. Used for accessing email messages on a remote server from multiple clients.
b. IMAP keeps emails on the server and synchronizes changes across clients.

10. DNS (Domain Name System):


a. Translates human-readable domain names (e.g., www.example.com) into IP
addresses.
b. Distributed hierarchical system for domain resolution.

11. DHCP (Dynamic Host Configuration Protocol):


1. Automatically assigns IP addresses and network configuration to devices on network.
2. Simplifies network administration by managing IP allocation.

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.

13. SLIP (Serial Line Internet Protocol):


a. This is used for delivering/ relaying packets over the dial-up line.
b. It defines the encapsulation mechanism for the packets.

14. PPP (Point to Point Protocol):


a. It is the internet standard for transmission of IP packets over the serial lines.
b. It is currently the best solution for dial-up connections.

These are just some of the many network protocols that facilitate communication and data
transfer across the internet and local networks. Each one serves specific purposes and plays
a crucial role in modern networking.

Web Services:
1. World Wide Web (WWW):
It is a global system of interconnected documents and resources that are accessible
over the internet. It operates 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.

11.Domain Name Service (DNS):


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

12.Internet Protocol (IP) Address:


It is a unique serial number assigned to devices on a network, facilitating
communication and data exchange between them over the internet, and other IP
based networks. These are of two types:

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.

The potential growth of internet-connected devices led to exhaustion of available IPv4


addresses. To cope up with this problem, the IPv6 addressing scheme was introduces that
provides a significantly large pool of IP addresses to accommodate the expansion of
internet.

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

6) What is the main disadvantage of a mesh topology?


a) High installation cost
b) Difficult to set up
c) Limited scalability
d) Susceptible to data collisions

7) Which network topology is commonly used in Ethernet networks and provides


centralized management?
a) Bus

132 | P a g e
b) Star
c) Ring
d) Mesh

8) In a star topology, what happens if the central hub fails?


a) The entire network becomes inoperative
b) Only the affected segment becomes inoperative
c) Data packets are automatically rerouted through an alternative path
d) The network speed decreases but remains functional

9) Which network topology is best suited for small networks and has a simple and cost-
effective design?
a) Bus
b) Star
c) Ring
d) Mesh

10) What network topology is typically used in token ring networks to regulate data
transmission?
a) Bus
b) Star
c) Ring
d) Mesh

11) Which transmission medium uses electrical signals to transmit data over short distances
inside a computer or between devices in a local network?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Infrared transmission

12) Which transmission medium offers the highest data transmission speeds and is immune
to electromagnetic interference?
a) Coaxial cable
b) Fiber-optic cable
c) Twisted-pair cable
d) Wireless transmission

13) In fiber-optic cables, data is transmitted through:


a) Electric signals
b) Infrared waves
c) Radio waves
d) Light pulses

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)

26) What type of network is the internet?


a) LAN (Local Area Network)
b) WAN (Wide Area Network)
c) SAN (Storage Area Network)
d) MAN (Metropolitan Area Network)

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)

Short Answer Questions


1. What is a network topology?
2. What is the star network topology?
3. Explain Bus topology?
4. What is point-to-point network?
5. What is the most commonly used network topology in modern Ethernet LANs?
6. What advantage does the mesh topology offer in terms of reliability?
7. Which topology is commonly used in wireless networks?
8. What advantage does the bi-directional ring offer over the uni-directional ring?
9. What advantage does the tree topology have over bus topology?
10. Explain the hybrid topology in brief.
11. What are transmission medias?
12. Name the different types of transmission medias.
13. What are the advantages and drawbacks of twisted pair cables?
14. What are the main drawbacks of coaxial cables?
15. What advantage does fiber optic cables have over coaxial cables?
16. Name some examples of devices that use infrared signals?
17. In terms of data security, which type of transmission medias offer more security- guided
or unguided. Why?
18. Which transmission media is commonly used to transmit data over short distances?
19. Which transmission media is commonly used to transmit data over long distances?
20. What are the main factors that influence the choice of transmission medias in a network?
21. What is a Local Area Network (LAN)?
22. What is a Personal Area Network (PAN)?
23. What is a Metropolitan Area Network (MAN)?
24. What is a Wide Area Network (WAN)?
25. What is Virtual Private Network (VPN)?
26. What is domain name service?
27. What do you understand by Web Hosting?

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.

Long Answer Questions


1. Differentiate between the Circuit switching, and Packet Switching techniques with
examples.
2. Explain the Wired Transmission medias with the help of suitable examples and
diagrams. OR
Explain the guided transmission medias with the help of suitable examples.
3. Explain the unguided transmission medias with the help of suitable
examples. OR
Explain the various wireless transmission medias with the help of suitable diagrams.
4. What do you understand by network topologies. Explain in brief, the various topologies
available for establishing a successful network.
5. What are the ways by which a network can be setup in a building. Give reasons to
support your answer.
6. Differentiate between LAN, MAN, and WAN giving suitable examples.
7. Based on the geographical span, what are the various topologies used for establishing
communications? Explain giving suitable examples and diagrams.
8. Explain the concept of bus topology. How is it different from bi-directional ring topology.
9. Discuss the tree topology in detail. What are its applications and potential limitations.
10. Discuss the advantages and drawbacks of guided transmission medias.
11. What are the advantages and drawbacks of unguided transmission medias.

Case Study based questions


A. Web server is a special computer system running on HTTP through web pages. The
web page is a medium to carry data from one computer system to another. The
working of the webserver starts from the client or user. The client sends their
request through the web browser to the webserver. Web server takes this request,
processes it and then sends back processed data to the client. The server gathers all
of our web page information and sends it to the user, which we see on our computer
system in the form of a web page. When the client sends a request for processing to
the web server, a domain name and IP address are important to the webserver. The
domain name and IP address are used to identify the user on a large network.

1. Web servers are:


a) IP addresses
b) Computer systems

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

3. What is the full form of HTTP?


a) Hypertext Transfer Protocol
b) Hypertext Transfer Procedure
c) Hyperlink Transfer Protocol
d) Hyperlink Transfer Procedure

4. The translates internet domain and host names to IP address


a) Domain name system
b) Routing information protocol
c) Google
d) Network time protocol

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

6. DNS stands for:


a) Domain Name Security
b) Domain Number System
c) Document Name System
d) Domain Name System

7. What is the format of IP address?


a) 34 bit
b) 32 bit
c) 16 bit
d) 64 bit

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

2. What does ARPANET stand for?


a) Advanced Research Premium Agency NETwork
b) Advanced Research Projects Agency NETwork
c) Advanced Review Projects Agency NETwork
d) Advanced Research Protection Agency 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

4. To join the internet, the computer has to be connected to a


a) Internet architecture board
b) Internet society
c) Internet service provider
d) Different computer

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

C. TCP/IP, or the Transmission Control Protocol/Internet Protocol, is a suite of


communication protocols used to interconnect network devices on the internet.
TCP/IP can also be used as a communications protocol in a private computer
network (an intranet or an extranet). TCP defines how applications can create
channels of communication across a network. It also manages how a message is
assembled into smaller packets before they are then transmitted over the internet
and reassembled in the right order at the destination address. IP defines how to
address and route each packet to make sure it reaches the right destination. Each
gateway computer on the network checks this IP address to determine where to
forward the message. TCP/IP
139 | P a g e
uses the client-server model of communication in which a user or machine (a client)
is provided a service (like sending a web page) by another computer (a server) in the
network. Collectively, the TCP/IP suite of protocols is classified as stateless, which
means each client request is considered new because it is unrelated to previous
requests. Being stateless frees up network paths so they can be used continuously.
1. Which of the following protocols is used in the internet?
a) HTTP
b) DHCP
c) DNS
d) All of the above

2. Which one of the following is not an application layer protocol used in internet?
a) Remote procedure call
b) Internet relay chat
c) Resource reservation protocol
d) Local procedure call

3. Which protocol assigns IP address to the client connected to the internet?


a) DHCP
b) IP
c) RPC
d) RSVP

4. Several protocols for upper layers in Bluetooth use:


a) UDP
b) HSP
c) ITC
d) L2CAP

5. Internet protocols are a set of rules to govern:


a) communication between computers on a network
b) standard
c) metropolitan communication
d) bandwidth

6. Checksum is used on internet by several protocols although not at the


a) sesson layer
b) transport layer
c) network layer
d) data link layer

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

2. Websites used to buy and sell something are categorized under


a. social networking sites
b. e-commerce websites
c. search engines
d. entertainment sites

3. Google is an example of
a. social network
b. entertainment
c. search engine
d. none of these

4. Which of the following is an example of micro-blogging?


a. orkut
b. facebook
c. google +
d. twitter

5. Which of the following is not used as blogging platform?


a. TypePad
b. Blogger
c. WordPress
d. Pinterest

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

2. Which of the following is the correct format of email address?


a. name@website@info
b. name@website.info
c. www.nameofwebsite.com
d. name.website.com

3. MIME stands for


a. multipurpose internet mail extensions
b. multipurpose internet mail email
c. multipurpose internet mail end
d. multipurpose internet mail extra

4. Mail access starts with 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

6. NVT stands for


a. network virtual transmission
b. network virtual test
c. network virtual terminal
d. network virtual tell

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

2. Dynamic web page


a. is same every time whenever it displays
b. generates on demand by a program or a request from browser
c. both is same every time whenever it displays and generates on demand by a
program or a request from browser
d. is different always in a predefined order

3. URL stands for


a. unique reference label
b. uniform reference label
c. uniform resource locator
d. unique resource locator

4. AJAX stands for


a. asynchronous javascript and xml
b. advanced JSP and xml
c. asynchronous JSP and xml
d. advanced javascript and xml

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

6. An alternative to JavaScript on windows platform is


a. a) VBScript
b. b) ASP.NET
c. c) JSP
d. d) PHP

7. A web cookie is a small piece of data that is


a. a) sent from a website and stored in user’s web browser while a user is
browsing a website
b. b) sent from user and stored in the server while a user is browsing a website
c. c) sent from root server to all servers
d. d) sent from the root server to other root servers

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

2. Which of the following is not a major type of e-commerce?


a. C2B
b. B2C
c. B2B
d. C2C

3. Which of the following is not considered to be one of the three phrases of e-


commerce?
a. innovation
b. consolidation
c. preservation
d. reinvention

4. Which segment do eBay and Amazon belong to?


a. B2B
b. B2C
c. C2B
d. C2C

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

6. The best products to sell in B2C e-commerce are:


a. small products
b. digital products
c. specialty products
d. fresh products

7. Which of the following is not a key element of a business model?

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

2. Privacy law is intended to protect the personal information about:


a. Individuals in society
b. computer networks
c. Employees
d. Students

3. What does TAN stand for?


a. Tax Deduction Account Number
b. Tax Deduction and Collection Account Number
c. Taxable Account Number
d. Tax Account Number

4. An e-group is a collection of users


a. who conduct seminars
b. who get together on weekends
c. who have regular video conferences
d. having the ability to access and contribute to forum topics

5. Whenever a new comment is posted, users of the e-group receive notification


that there is a new contribution to the discussion.
a. SMS
b. E-mail
c. WhatsApp
d. Call

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

2. “A combination of both face-to-face, traditional classroom methods with e-learning


to create a hybrid approach to teaching”. What is this type of e-learning?
a. Blended learning
b. Distance learning
c. Synchronous learning
d. Asynchronous learning

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

5. What best describes a virtual classroom?


a. Learners using technology in a classroom environment lead by a tutor
b. Training course done by youtube tutorials
c. An online learning environment accessed through the internet (i.e. webinars)
d. An online learning course

6. Which of the following is not an e-learning website?

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

2. We get a list of sites after typing a word in search bar called:


a. Single word
b. Key phrase
c. Site
d. All of the above

3. The search results are shown in a line of results. This is called:


a. Search engine pages
b. Categories
c. Search engine result pages
d. Tag list

4. Search engines are able to search type of information.


a. Videos
b. Images
c. Documents
d. All of the above

5. Web search engines store information about web pages with the help of:
a. Web router
b. Web crawler
c. Web indexer
d. Web organizer

6. Web crawler is also called as:


a. Web spider

147 | P a g e
b. Web manager
c. Ink directory
d. Search optimizer

7. SEO is the process of of a website or a web page in a search engine’s search


results.
a. Generating cached files
b. Affecting the visibility
c. Getting meta tags
d. All of these

K. 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 in (i) to (iv). Shortest distances
between various locations in meters:

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

Block to block distances (in Meters)

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

Number of Computers in each of the blocks/Centre is as follows:


Admin 140
Engineering 70
Business 35
Media 20
Hyderabad 30
i. Suggest and draw the cable layout to efficiently connect various blocks of buildings
within the Chennai campus for connecting the devices.
ii. Which network device will be used to connect computers in each block to form a
local area network?
iii. Which block, in Chennai Campus should be made the server? Justify.
iv. Which fast and effective wireless transmission medium should preferably be used
to connect the head office at Hyderabad with the campus in Chennai?

149 | P a g e
v. Is there a requirement of a repeater in the given cable layout? Why/Why not?

M. Rohit Communications International (RCI) is an online corporate training provider


company for IT related courses. The company is setting up their new campus in
Bengaluru. You as a network expert have to study the physical locations of various blocks
and the number of computers to be installed. In the planning phase, provide the best
possible answers for the queries (i) to (v) raised by them.

i. Suggest the most appropriate block, where RCI should plan to install the server.
ii. Suggest the most appropriate block to block cable layout to connect all three blocks
for efficient communication.
iii. Which type of a network out of the following is formed by connecting the
computers of these three blocks? (LAN, MAN, WAN, PAN)
iv. Which wireless channel out of the following should be opted by RCI to connect to
students from all over the world? (Infrared, Microwave, Satellite)
v. What is the satellite 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.

O. Sanskar University of Uttarakhand is setting up a secured network for its campus at


Nainital for operating day to day office and web-based activities. They are planning to
have network connectivity between four buildings. Answer the questions after going
through the building positions in the campus and other details given below:
The distance between various buildings of university are given as follows:

Building 1 Building 2 Distance (in mtrs.)


Main Admin 50
Main Finance 100
Main Academics 70
Admin Finance 50
Finance Academics 70
Admin Academics 40

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

Teachers Unit Students Unit

The three units are providing the following services:


1. Teachers Unit: For the access of the Library Books by teachers
2. Students Unit: For access of the Library Books by students
3. Circulation Unit: For issue and return of the books for teachers and
students Centre to Centre distances between the 3 units are as follows:
 Circulation Unit to Teachers Unit – 30 metres
 Circulation Unit to Students Unit – 25 metres
 Teachers Unit to Students Unit – 15 metres
Number of computers in each of the units is as
follows:
 Circulation Unit 20
 Teachers Unit 15
 Students Unit 15
a. Suggest the most suitable place to install the server of this library with a suitable
reason.
b. Suggest an ideal layout for connecting these units for a wired connectivity.
c. Which device will you suggest to be installed and where should it be placed to
provide Internet connectivity to all the units.
d. Suggest the type of the most efficient and economical wired medium for connecting
all the computers in the network.
e. The university is planning to connect the library with the school Principal’s computer
which is in his office at a distance of 50 metres. Which type of network out of LAN,
MAN or WAN will be used for the network? Justify your answer.

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.

Ahmadabad Office Admin Block

Accounts Block HQ

Mumbai
Training Block

Shortest distances between various blocks/locations:


Admin Block to Accounts Block 300 metres
Admin Block to Accounts Block 200 metres
Admin Block to Accounts Block 350 metres
Mumbai Head Office to Ahmedabad Office 525 KM
a. Suggest the most appropriate block/location to house the server in Ahmedabad
office to get the best and effective connectivity. Justify your answer.
b. Suggest the best wired medium and draw the cable layout to efficiently connect
various blocks within the Ahmedabad office compound.
c. Suggest a device/software and its placement that would provide data security for
the entire network of the Ahmedabad office.
d. Suggest a device and the protocol that shall be needed to provide wireless internet
access to all smart phones/laptop users in the Ahmedabad office.
R. Knowledge Supplement Organization has set up its new centre at Mangalore for its
office and web -based activities. It has 4 blocks of buildings as shown in the diagram
below:

Center to center distances between various blocks:


Block A to Block B 50 m
Block B to Block C 150 m
Block C to Block D 25 m
Block A to Block D 170 m
Block B to Block D 125 m
Block A to Block C 90 m

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:

Approximate distances between these Units is as follows:


From To Distance
Production Unit Finance Unit 75 Mtr
Production Unit Media Unit 15 KM
Production Unit Corporate Unit 2112 KM
Finance Unit Media Unit 15 KM
In continuation of the above, the company experts have planned to install the following
number of computers in each of their office units:

Production Unit 150


Finance Unit 35
Media Unit 10
Corporate Unit 30
i) Suggest the kind of network required out of (LAN, MAN, WAN) for connecting each of

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:

Centre to Centre distances between various blocks/centre is as follows:

Law Block to Business Block 40 m


Law Block to Technology Block 80 m
Law Block to HR Block 105 m
Business Block to Technology Block 30 m
Business Block to HR Centre 35 m
Technology Block to HR Centre 15 m
Number of computers in each of the block/Centre is as follows:
Law Block: 15
Technology Block: 40
HR Centre: 115
Business Block: 25
a.) Suggest the most suitable place (i.e., Block/Centre) to install the server of this
university with a suitable reason.
b.) Suggest an ideal layout for connecting these blocks/centres for a wired connectivity.
c.) Which device will you suggest to be place/installed in each of these blocks/centres to

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

Introduction of Database Management System (DBMS):


DBMS is shorten name used for Database Management System. So, as we are aware of
database now, we need to understand what DBMS is. Let’s understand it.
DBMS is a software system which is used to manage Database. DBMS acts as an interface
between a user and database which enables the user to create, insert, retrieve, update and
delete the data.

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

Basic Terminology of ER Model:


ER stands for Entity-Relationship Model. ER Model tools are used to represent Conceptual
Data Model. Let’s see some basic tools of ER Model.

Entity Any real world object is known as entity


like person, place, object and event

Relationship Show interconnection between two or


more entity

Attribute Shows property/characteristics of an


entity/relationship type

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

NUMERIC INT/INTEGER Signed range is from -2147483648 to


2147483647. Unsigned range is from 0 to
DATATYPE 4294967295
SMALLINT(SIZE) SIGNED RANGE IS FROM -32768 TO 32767.
UNSIGNED RANGE IS FROM 0 TO 65535
TINYINT(SIZE) SIGNED RANGE IS FROM -128 TO 127.UNSINED
RANGE IS FROM 0 TO 255
MEDIUMINT(SIZE) SIGNED RANGE IS FROM -8388608 TO 8388607.
UNSIGNED RANGE IS FROM 0 TO 16777215
BIGINT(SIZE) Signed range is from -9223372036854775808
to 9223372036854775807. Unsigned range is
from 0 to 18446744073709551615
FLOAT(SZ,D) SZ IS SIZE AND D IS NO. OF DIGIT AFTER
DECIMAL
STRING CHAR(SIZE) CHAR IS FIXED SIZED STRING AS PER SIZE
DEFINED IN PARANTHESIS. SIZE OF CHAR
DATATYPE DATATYPE IN RANGE OF 0 TO 255.
BYDEFAULT SIZE OF CHAR IS 1
VARCHAR(SIZE) VARCHAR STANDS FOR VARIABLE LENGTH
CHARACTER STRING
RANGE OF VARCHAR IS 0 TO 65535

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.

CH 2: Structured Query Language:


Introduction:
SQL is shortened of Structured Query Language. And it is pronounced as See-Quell. SQL is
used to manage database. SQL was developed in 1970 in IBM Laboratory and it became a
standard of the ANSI (American National Standard Institute) in 1986.
SQL is query language not a database system. You are required to install DBMS software in
your system to perform SQL Language operation with help to query Example – Oracle,
MySQL, MongoDB, PostgreSQL, SQL Server, DB2 etc.
SQL is mainly used for maintaining the data in relational database management system. SQL
provide interaction between user and database via set of standard commands.
In simple words, SQL is language that help user to communicate with databases. SQL is not
case sensitive language means you can type your query in small or capital letter as per user.

You may write comments in SQL using “--” (Double hyphen)

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.

Few basic SQL Commands:


Create databases:
To create a new database, create databases command is used.
SQL Syntax: create database <database name>;

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) … );

Name of attribute Data Type


Student_ID int
Student_Name char(30)
Age int
Phone int
Address varchar(50)

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>;

Drop table command:


To delete data as well as structure of a table, drop command is used.
SQL Syntax:
drop table <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:

1. Primary Key Constraints:


NOT NULL+UNIQUE=Primary Key
This key applies unique and not null constraint to the column.
This constraints ensure that each column/attribute of table contain unique value for each
row.
Let’s learn with the help of example:
First we have created a table named student_demo and applying primary key constraints
on roll_no attribute.

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

SQL Syntax: alter table <table_name> add <constraints_name>(<column_name>);

Command: alter table student add unique(standard);

Let’s see table schema after applying above code:

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.

For example: we have two tables’ student and awards as follows:


Table: Student Table: Awards
ID Name Age City ID Award Sport
Here
1 we will establish
Amit 15foreign key constraint on column ID of student table and column
Delhi 1 Gold Badminton
id of
2 awards
Madhutable. 14
Here we will consider Student table as parent table and Awards
Gurugram
table
3 as child table. 15
Manoj Following rules must be2 followed:
Noida
Silver Tennis
4 Asif 15 Faridabad 1 Silver Hockey
4 Bronze Badminton

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

DDL (Data Definition Language) Commands:


These commands are used to make any changes in the structure of the table/database.
These command don’t change the data of the table.
Example: create table, alter table, drop table, create database, create view etc.

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];

Add a column to the table:


We have table student which was created in previous section.

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.

Drop a column from the table:


Let’s delete a column class from table student which we added in the previous section.
SQL Syntax:
alter table <table name> drop column<column name>;

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.

5. Add/drop constraints/column: We can add/drop constraints in a table using alter


command.
 Adding primary key: We are going to add primary key at column ID using alter
command.
Command: alter table <table name> add primary key(<column name>);

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>;

 Dropping a column: We are going to remove a column ‘country’ which we


added in the last section using alter command.
Command: alter table <table name> drop column <column name>;

182 | P a g e
DML (Data Manipulation Language) Commands:
These commands are used to make any changes in the data of the table.

DML commands: Insert, delete, update, select etc.


We have already covered few DML Commands like insert and select. Now we will discuss
delete and update command.

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.

Uses of where clause:


 Where clause can be used with select statement to filter the result.
 Where clause can be used with update statement to update the data of table that
matches with the condition.
 Where clause can be used with delete statement to delete the rows of table that
matches with the condition.
SQL Syntax:
where <condition>;
Examples:
1. To filter the result based on only one condition:

186 | P a g e
2. To filter the result based on multiple condition:

In clause and not in clause:


In sql, in clause and not in clause is used to filter the rows in output based on list of values.
Syntax for in clause:
where <column name> in (item1, item2,…);
Syntax for not in clause:
where <column name> not in (item1, item2,…);
Example of in clause: if we want to find the data of those students who lives in either delhi
or Jaipur or gurugram. Now to solve this problem, we have two ways. Either we write
multiple comparison using or keyword or we can use in clause. Now you will see that using
in clause for comparing with a list of items is an easy option.

Example of not in clause: if we want to find the data of those students who don’t 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.

Note: is keyword is used to compare values of a column with NULL.

IS NOT NULL Clause:


IS NULL clause is used to check that value in particular column is not NULL value
Example: To find out name of students whose phone number is not 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.

5. Count: it is used to count number of values in 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.

Python and MySQL Interface


In real life scenario, user interact with applications whereas data is stored in database. We
have already developed python applications and database tables. Now, we will connect
python application and MySQL database.

Steps for creating python and MySQL connectivity application:


1. Import mysql.connector
2. Create a connection
<connection object> =mysql.connector.connect (host=”localhost”, user=<username>,
passwd= <password>, database =<database name>)
Username = To know the user name, run select user(); command on your MySQL.

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 :

d) rowcount: It is cursor’s property to count the number of rows in


resultset. Syntax: <variable name>=<cursor>.rowcount
Example: Refer to the example of fetchmany()

6. Close the connection


After doing all the processing, connection should be closed.
Syntax: <connection object>.close()
Example: Refer to the example of fetchmany()

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,

value of x and y will be given by the user during run time).


Python Code:

Output:

2. Using format() function:


203 | P a g e
Whenever we needs to complete SQL query based on user input, we write a placeholder
{} on that place.

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:

Data in student table after insertion

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:

Data in student table after deletion

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)

1. What is the use of DBMS?


a. Data Retrieval
b. Data Storage
c. Data Manipulation
d. All of the above

2. What is relational data model?


a. Where data is organized in tree like structure with parent child relationship
b. Where pointer is used to navigate through data
c. Where data is represented as objects.
d. Where data is organized into tables with rows and columns

3. What is tuple is relation?


a. row
b. column
c. field
d. attribute

4. What is attribute in relation?


a. row
b. column
c. tuple
d. key

5. What is degree in database?


a. Foreign key of the table
b. Primary key of the table
c. Number of columns in the table
d. Number of rows in the table

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

7. What is cardinality in database?


a. Number of columns
b. Number of rows
c. Number of primary key
d. Number of attribute key
208 | P a g e
8. What is key in SQL?
a. Which is used to uniquely identify record
b. To maintain data integrity
c. To enable efficient data retrieval
d. All of the above

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

12. What is the use of foreign key?


a. To uniquely identify record
b. To enforce data integrity
c. To define the data type of column
d. To establish a link between two tables

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

18. A user request to retrieve data or information from database/table is called?


a. key
b. data
c. query
d. view

19. Which of the following is not a valid datatype in SQL?


a. Date
b. String
c. Decimal
d. Char

20. Which command is used to delete database permanently?


a. create database
b. delete database
c. drop database
d. use database

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

23. Wild card operator (%,_) are used with?


a. count
b. max
c. like
d. min

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

29. INSERT command is used in database to perform

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

40. Which of the following is not a valid DML command in SQL?


a. INSERT
b. UPDATE
c. ALTER
d. DELETE

41. Which keyword is used for table aliasing that involves giving a table short and
alternative name to simplify query syntax?
a. from
b. as
c. where
d. on

42. Which SQL clause is used in 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

46. Which method is used to execute a SQL query on a MySQL database?


a. execute()
b. query()
c. run()
d. None of the above

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()

Short answer type Questions:


1. What is SQL?
2. Differentiate between DML and DDL. Explain with the help of examples.
3. What are the different type of SQL data type?
4. What is the difference between where statement and having statement in SQL?
5. What is primary key?
6. Differentiate between a database table and a database record.
7. What is foreign Key? And how does it relate in a database.
8. What is Domain in database?
9. Explain the role of clause in query of SQL commands.
10. What is Aliasing?
11. Explain char, varchar and int datatype in SQL with example.
12. Differentiate between candidate key and alternate key?
13. Differentiate between degree and cardinality of a table with the help of example.
14. What are database keys? Explain all the database keys.
15. What are constraints in SQL?
16. Explain the wildcards used with like operator.
17. What are joins in SQL?
18. Differentiate between Natural Join and Equi Join.
19. Explain any two aggregate function in SQL.
20. What is a cursor?
21. What is the role of commit() function in SQL?
22. What is Cartesian product? What will be the number of rows in output table if we
apply Cartesian product on two tables T1 and T2 with 9 and 10 rows respectively?
23. Explain alter table command with the help of example.
24. Differentiate between fetchall() function and fetchmany() function in SQL.
25. In SQL, Define aggregate function and write the name of the aggregate function
which will display the cardinality of a table.

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.

1. Assertion (A): COUNT function can be work with distinct keyword.


Reason (R): DISTINCT keyword can only be used with COUNT function.

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.

4. Assertion (A): The primary key is applied on a column of a table.


Reason (R): NOT NULL constraint restricts NULL values in a column.

5. Assertion (A): SUM and COUNT are aggregate functions.


Reason (R): Aggregate functions works on multiple tuples.

6. Assertion (A): Primary key constraints allows NULL values.


Reason (R): The primary key constraints ensures that a column can contain
unique Values for each row.

7. Assertion (A): Unique key constraint allows NULL values.


Reason (R): The unique key constraints ensures that a column can contain
unique Values.

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

Column_Name DataType(size) Constraint


Emp_ID Int(20) Primary key
Emp_Name char(100) Not Null
Salary int(20) Not Null
Department char(30)
Age int(15) Not Null
Address Varchar(200) Unique

2. 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) Write the degree and cardinality of the table PHARMA.


(b) Identify the attribute best suitable to be declared as a primary key.
(c) 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.
(d) Anmol wants to change the name of the attribute UNITS to QUANTITY in the table
PHARMA. Which of the following commands will he use for the purpose?
I. UPDATE
II. DROP TABLE
III. CREATE TABLE
IV. ALTER TABLE
(e) Now Anmol wants to increase the PRICE of all medicines following commands will he use
for the purpose?
I. UPDATE SET
II. INCREASE BY
III. ALTER TABLE
IV. INSERT INTO

4. For the following SQL Table named PASSENGERS in a database TRAVEL:

TNO NAME START END


T1 RAVI KUMAR DELHI MUMBAI
T2 NISHANT JAIN DELHI KOLKATA
T3 DEEPAK PRAKASH MUMBAI PUNE

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

1. Categorize the following commands as DDL or


DML: ALTER, INSERT, UPDATE, CREATE, DROP,
DELETE
2. Identify the attribute of Garment table to be declared as primary key.
3. Write the degree and cardinality of the table GARMENT
4. Write SQL query to create database STORE.
5. Write SQL query to display list of available databases.
6. Write SQL query to use database STORE.
7. Write SQL query to display list of available tables in database STORE.
8. Write SQL query to create table GARMENT with aforementioned attributes.
9. Obtain the output of following SQL queries based on the data given in table
GARMENT:
(i) SELECT MAX(PRICE), MIN(PRICE) FROM GARMENT;
(ii) SELECT GCODE, DESCRIPTION FROM GARMENT;
(iii) SELECT FCODE,GCODE FROM GARMENT WHERE PRICE BETWEEN 500
AND 800;
(iv) SELECT * FROM GARMENT WHERE DESCRIPTION NOT IN (‘JEANS’,’TIE’);
(v) SELECT GCODE FROM GARMENT WHERE DESCRIPTION LIKE ‘%S%’;
(vi) SELECT GCODE,PRICE FROM GARMENT WHERE DESCRIPTION LIKE ‘_ _ _’;
(vii) SELECT DISTINCT FCODE FROM GARMENT;

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

(i) SELECT M_NO, MIN(AMOUNT) FROM TRANSACTION GROUP BY M_NO HAVING


COUNT(*)>2;
(ii) SELECT T_NO,AMOUNT FROM TRANSACTION WHERE CARD_TYPE=’CREDIT’;
(iii) SELECT * FROM TRANSACTION WHERE M_NO>12 AND STATUS=’FAILURE’;
(iv) SELECT CARD_TYPE, SUM(AMOUNT) FROM TRANSACTION GROUP
BY CARD_TYPE;
(v) SELECT T_NO, AMOUNT*10 AS PAYMENT FROM TRANSACTION WHERE STATUS
IN (‘SUCCESS’);
(vi) SELECT COUNT(*) FROM TRANSACTION WHERE STATUS=’SUCCESS’;
(vii) SELECT T_NO, AMOUNT, CARD_TYPE FROM TRANSACTION WHERE T_NO>5;
(viii) SELECT DISTINCT M_NO FROM TRANSACTION;
(ix) SELECT T_NO, M_NO,CARD_TYPE, COMPANY FROM TRANSACTION T, COMPANY
C WHERE T.T_NO=C.T_NO AND AMOUNT>1000;
(x) SELECT T.T_NO AS TRANS_NO FROM TRANSACTION T, COMPANY C WHERE
T.T_NO=C.T_NO;

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

Write the following statements to complete the code:


Statement 1- to import the desired
library. Statement 2- to create a cursor
Statement 3- to write a sql query that fetches records of all those employees who don’t
lives in delhi.
Statement 4- to execute the query
Statement 5- to print all the records fetched in statement 4

Import as mysql #Statement 1


def print():
a=mysql.connect (host="localhost", user "root",passwd=12345, database=
"company")
b= #Statement 2
query = #Statement 3
c= #Statement 4
for z in c:
#Statement 5

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

Write the following statements to complete the code:


Statement 1- to import the desired library.
Statement 2- to connect to the database

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.

Import as mysql #Statement 1


def del():
a= (host="localhost", user "root",passwd=12345, database= "company")
#Statement 2
b= #Statement 3
query = #Statement 4
#Statement 5
print(‘Data deleted’)

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.

Que Question Marks


s No
SECTION A
1 State True or False: 1
“In a Python program, if a break statement is given in a nested loop, it
terminates the execution of all loops in one go.”
2 In a table in MYSQL database, an attribute A of datatype varchar(20) 1
has the value “Keshav”. The attribute B of datatype char(20) has value
“Meenakshi”. How many characters are occupied by attribute A and
attribute B?
a. 20,6 b. 6,20
c. 9,6 d. 6,9

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


print(3-2**2**3+99/11)
a. 244 b. 244.0
c. -244.0 d. Error

4 Select the correct output of the code: 1

[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

9 Which of the following statement(s) would give an error during execution of 1


the following code?
tup = (20,30,40,50,80,79)
print(tup) #Statement 1
print(tup[3]+50) #Statement 2
print(max(tup)) #Statement 3
tup[4]=80 #Statement 4

Options:
a. Statement 1
b. Statement 2
c. Statement 3
d. Statement 4

10 What possible outputs(s) will be obtained when the following code is 1


executed?

Options:
a.

[3]
RED*
WHITE*
BLACK*

b.
WHITE*
BLACK*
c.
WHITE* WHITE*
BLACK* BLACK*

d.
YELLOW*
WHITE*WHITE*
BLACK* BLACK* BLACK*

11 Fill in the blank: 1


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

12 Consider the code given below: 1

[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

13 State whether the following statement is True or False: 1


An exception may be raised even if the program is syntactically correct.
14 Which of the following statements is FALSE about keys in a relational 1
database?
a. Any candidate key is eligible to become a primary key.
b. A primary key uniquely identifies the tuples in a relation.
c. A candidate key that is not a primary key is a foreign key.
d. A foreign key is an attribute whose value is derived from the primary
key of another relation.

15 Fill in the blank: 1


In case of switching, before a communication starts, a
dedicated path is identified between the sender and the receiver.
16 Which of the following functions changes the position of file pointer and 1
returns its new position?
a.flush()
b.tell()
c.seek()
d.offset()

Q17 and 18 are ASSERTION AND REASONING based questions. Mark


the correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A

[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

Zack is working in a database named SPORT, in which he has created a


table named “Sports” containing columns SportId, SportName,
no_of_players, and category.
After creating the table, he realized that the attribute, category has to be
deleted from the table and a new attribute TypeSport of data type string
has to be added. This attribute TypeSport cannot be left blank. Help Zack
write the commands to complete both the tasks.

25 Predict the output of the following code: 2

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

CID CNAME AGE GENDER SPORTS PAY DOAPP


5246 AMRITA 35 FEMALE CHESS 900 2006-
03-27

[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

(i) SELECT COUNT(DISTINCT SPORTS) FROM CLUB;


(ii) SELECT CNAME, SPORTS FROM CLUB WHERE
DOAPP<"2006-04-30" AND CNAME LIKE "%NA";
(iii) SELECT CNAME, AGE, PAY FROM CLUB WHERE
GENDER = "MALE" AND PAY BETWEEN 1000 AND
1200;
28 Write a function in Python to read a text file, Alpha.txt and displays 3
those lines which begin with the word ‘You’.
OR
Write a function, vowelCount() in Python that counts and displays the
number of vowels in the text file named Poem.txt.
29 Consider the table Personal given below: 1*3=
3
Table: Personal
P_ID Name Desig Salary Allowance

P01 Rohit Manager 89000 4800

[11]
P02 Kashish Clerk NULL 1600
P03 Mahesh Superviser 48000 NULL

P04 Salil Clerk 31000 1900


P05 Ravina Superviser NULL 2100

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

Block to Block distances (in Mtrs.)


From To Distance
ADMIN ENGINEERING 55 m
ADMIN BUSINESS 90 m
ADMIN MEDIA 50 m
ENGINEERING BUSINESS 55 m
ENGINEERING MEDIA 50 m
BUSINESS MEDIA 45 m
DELHI HEAD CHENNAI 2175 km
OFFICE CAMPUS

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


ADMIN 110
ENGINEERING 75
BUSINESS 40
MEDIA 12
DELHI HEAD 20

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.

(ii) Sartaj has created a 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

[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

Computer Science (083)

Marking Scheme

Time Allowed: 3 hours MM: 70

Ques Question and Answers Distribution Total


No of Marks Marks

SECTION A
1 False 1 mark for 1
correct
answer

2 Option b 1 mark for 1


correct
6,20
answer

3 Option c 1 mark for 1


correct
-244.0 answer

4 PYTHON-is-Fun 1 mark for 1


correct
answer

5 Option b 1 mark for 1


correct
8,15
answer

6 Option a 1 mark for 1


correct
PAN answer

7 Option b 1 mark for 1


correct
del D1["Red"] answer

8 Option b 1 mark for 1


correct
answer

[1]
ceieP0

9 Option d 1 mark for 1


correct
Statement 4 answer

10 Option b 1 mark for 1


correct
WHITE* answer

BLACK*

11 Option b 1 mark for 1


correct
Modulator answer

12 Option c 1 mark for 1


correct
global b answer

13 True 1 mark for 1


correct
answer

14 Option c 1 mark for 1


correct
A candidate key that is not a primary key is a foreign key. answer

15 Circuit 1 mark for 1


correct
answer

16 Option c 1 mark for 1


correct
seek() answer

17 Option d 1 mark for 1


A is false but R is True correct
answer

[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

URL – Uniform Resource Locator

(ii)

HTML( Hyper text mark Up language)

 We use pre-defined tags


 Static web development language – only focuses on how
data looks
 It use for only displaying data, cannot transport data
 Not case sensistive

XML (Extensible Markup Language) 1 mark for


any one
 we can define our own tags and use them correct
difference
 Dynamic web development language – as it is used for
transporting and storing data No mark to
be awarded if
 Case sensitive only full form
OR is given

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

20 def revNumber(num): ½ mark for 2


rev = 0 each
rem = 0 correction
while num > 0: made
rem =num %10
rev = rev*10 + rem
num = num//10
return rev
print(revNumber(1234))

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

Note: Any other correct logic may be marked

22 4*L ½ mark for 2


each correct
33*4
line of output
21*S
10*6
23 (i) L1.insert(2,200) 1 mark for 1+1=2
each correct
(ii) message.endswith('.') statement

OR
import statistics
1 mark for
print( statistics.mode(studentAge) )
correct
import
statement

1 mark for
correct
command
with mode()
and print()

24 SQL Command to add primary key: 1 mark for 2


correct
ALTER TABLE Employee ADD EmpId INTEGER ALTER TABLE
command
PRIMARY KEY;

[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

1 mark for 1*3=3


each correct
(i)
output
COUNT(DISTINCT SPORTS)

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

Note: Any other correct logic may be marked


29 (i) 1 mark for 1*3=3
each correct
UPDATE Personal
query
SET Salary=Salary + Salary*0.5
WHERE Allowance IS NOT NULL;

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

34 (i) 1 mark for 2+3=5


each correct
r+ mode:
difference
 Primary function is reading
( minimum
 File pointer is at beginning of file two
 if the file does not exist, it results in an differences
should be
error w+ mode: given)
 primary function is writing
 if the file does not exist, it creates a new file.
 If the file exists, previous data is overwritten
 File pointer is at the beginning of file
(ii)
½ mark for
correctly
opening and
closing files

½ 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

 Extension is .txt 1 mark for


 Data is stored in ASCII format that is human readable correctly
displaying
 Has EOL character that terminates each line of data data
stored in the text files

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()

(i) All keys that have the properties to become a primary


key are candidate keys. The candidate keys that do not
become primary keys are alternate keys. 1 mark for
(ii) correct
difference

½ 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

COMPUTER SCIENCE (083)


PRACTICE SET
Time allowed: 3 Hours Maximum Marks: 70

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.

QUES QUESTION MARKS


NO.
SECTION A

1 State True or False: 1


In MySQL, the GROUP BY clause is used to combine all such records of a table which
have identical values in specified field(s).
2. Which of the following statements is not valid for CSV files? 1
a. CSV files are the text files.
b. The newline argument suppresses blank rows in the file.
c. By default, EOL takes place while writing data into the file.
d. None of the above.

3. What will be the value of p when p=int(17/2+11.5)? 1


20 b. 20.0 c. 28 d. 28.0

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

5. To work with MySQL, you need to enter a password, known as 1


a. Root password
b. System Password
c. MySQL Password
d. Data Language Password
6. Physical or logical arrangement of network refers to as: 1
a. Routing
b. Looping
c. Topology
d. Networking

7. Write the output of the code given below: 1


T= (12,72,34,76,21,89,4,83,11,2)
RESULT = list(T [-4:])
print(RESULT)
a. [4, 83, 11, 2]
b. (89,4, 83, 11)
c. (4,83,11,2)
d. [89,4,83,11]

8. Find the output of the following 1


code: String = “Python
Programming” String.isalnum()
(a) True
(b) False
(c) TypeError
(d) None of these
9. What is output of following code 1

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.
d.) To generate truly random numbers for secure applications.

11. The internet facility that facilitates remote login is: 1


a. 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. Stack is a linear data structure which implements? 1
a. Last in First out
b. Last in Last out
c. First in First out
d. None of the above
14. Which of the following TCP/IP protocols is used for transferring files from one computer 1
to another?
a. FTP b. PPP c. SMTP d. HTTP

15. Which of the following statement is correct for ‘wb+’ mode? 1


a. It enables writing and reading operations.
b. It disables writing but enables reading operations.
c. It enables reading followed by writing operations.
d. None of the above

16. Which of the following function is used with the csv modules in Python to read the content of a 1
csv file into an object?
a. readrow() b. readrows() c. reader() d. load()
Q17 and 18 are ASSERTION (A) and REASONING (R) based questions. Mark the
correct choice as
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False.
(d) A is false but R is True
17. Assertion (A): The key concept of data structure is to manage the storage of data in the memory 1
efficiently.
Reason (R): The data structure is a way to create a logical structure in the memory so that the
storage of numerous data values could be managed using minimum space. It helps in a fast
accessing of data during execution of a program.
18. Assertion(A): Every open file maintains a file-pointer and keeps track of its position after every 1
operation.
Reason (R): Every read and write operation takes place at the current position of the file pointer.
SECTION B

19. Give two advantages and two disadvantages of star topology 2

OR

Define the following terms:


www, web hosting
20. What will be the flow of execution of the following code? 2
1 #function definition
2 def Increment(X):
3 X += 1
4 X=3
5 print(X)
6 Increment(X)
7 print(X)
21. Explain the Scope of a variable in Python with example. 2
OR
Differentiate between actual parameter(s) and formal parameter(s) with a suitable example for
each
22. Write a function Name(N) in Python, that accepts a list, N, of names and display the names 2
starting with letter ‘A’. For example, if the list is
N = ['Ashima', 'Neha', 'Rahul', 'Ishaan', 'Ashu', 'Kirti']
Then the output should be:
Ashima
Ashu
OR
Write definition of a method SumEvenOdd(K) to display the sum of Odd and Even values
separately from the list K. For example, if list K is defined as:
K = [14,25,16,23,12,9,7,23]
Then the output should be:
Sum of Even numbers:42
Sum of Odd numbers:87

23. Categorize following commands into DDL and DML commands? 2

INSERT INTO, DROP TABLE, ALTER TABLE,UPDATE...SET


24. Differentiate between char(n) and varchar(n) data types with respect of databases. 2

25. Predict the Output for the following code: 2


x = [1,2,3,4,5,6,7,8,9]
a=[]
n=len(x)
for i in range(n):
if x[i]%2 == 0:
a.append(x[i]/2)
else:
a.append(x[i]*2)
print("New List is: ",a)

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

26. Charu has to create a database named MYEARTH in MYSQL. 3


She now needs to create a table named CITY in the database to storethe records of
various cities across the globe. The table CITY has the following structure:

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?

Infrared, coaxial cable, optical fibre,microwave, Ethernet cable

3. How is packet switching different from circuit switching?

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.

Happy Faces Corporation

Block B
Block A

Block D
Block C

Distance between the various blocks is as follows:A to B 40 m


B to C 120m
C to D 100m
A to D 170m
B to D 150m
A to C 70m

Numbers of computers in each


block Block A -25
Block B - 50
Block C - 125
Block D - 10

a. Suggest and draw the cable layout to efficiently connectvarious blocks of


buildings within the Noida centre for connecting the digital devices.
b. Which block will be best suitable to place the server and why?
c. Suggest the placement of the following device withjustification
a. Repeater b. Hub/Switch
d. Which kind of network (PAN/LAN/WAN) will be formed if theNoida office
is connected to its head office in Mumbai?
e. Which fast and very effective wireless transmission mediumshould preferably
be used to connect the head office at Mumbai with the centre at Noida?
34. Read the following passage and answer the questions that follow: 5
Lists are the container which store the heterogeneous elements of any type as integer,
character, floating that store in square brackets [].
Consider the following list:
T = [4,7,[2,5.7,9.6], ‘Delhi’, ‘Mumbai’, ‘Kolkata’]
1. To print Value 9.6, the correct python statement will be:
a. L [2][2] b. L [2][-1] c. L [-4][-1] d. All of the above
2. The length of L is:
a. 6 b. 8 c. 18 d. None of these
3. The output for statement len(L[1]) will be:
a. 1 b. 3 c. Exception d. Syntax Error
4. print(L[:2] will generate value:
a. [4] b. [4,7] c. [4,7,[2,5.7,9.6]] d. Error
5. L.append[4,5,6] will generate output:
a. Error
b. Append a sublist [4,5,6] into L
c. Append three elements in list 4, 5 and 6
d. None of these

OR
Read the following passage and answer the questions that follows:
Lists are the container which store the heterogeneous elements of any type like integer,
character or floating point that store in square brackets[].
Consider the following list for Python:
D = [“Raja”, 4.87, ‘Delhi’, ‘Kerala’, [23, 7.56, ‘Neha’], 98]
What will the following statements do as per above definition of D:
1. D [4][-3]
2. len( D[3])
3. d [2] = 54
4. print (D[0] + D[1])
5. print (D[1:5:3]

35. Ami has joined as teaching assistant. She is working with data files using Python. She is 5
currently working on the following incomplete code:
Color= [‘Red’, ‘Orange’, ‘Crimson’, ‘Magenta’, ‘Fuschia’, ‘Blue’,
‘Black’] def LenColors( , ): #Statement 1
with : #Statement 2
for c in Color:
: #Statement 3
#Statement 4
Fname =’Colors.txt’
N = int(input(“Enter a number (between 3 to 7): “))
#Statement 5
FILE = open(Fname)
print(File.read())

Help her complete the code as per instruction given below:


a. Complete Statement 1 and Statement 5 so that Statement 5 invokes the
function LenColors() by passing arguments—the filename and the integer value
n.
b. Statement 2: Open the file for writing using a with statement in the file object
namely F.
c. Inside the loop, write code so that only those colors from the color list get
written in separate lines on the file that have word length more than n(the
second parameter received) (Statement 3 and Statement 4)
d. What will be the output produced, if the value of n is entered as 6?
OR
Atif won a junior programming contest and as a prize, he is attending a Python
workshop. In one of his assignments, he has been given a text file namely Demo.txt as
shown below:
The total turnover of the bamboo sector in the state has increased from the base
levels of Rs 27.90 crores in 2006-07.
The turnover was 83.7 crore during the FY 2015-16 which has increased to over Rs. 93.53
cr during 2016-17.
#tripura #bamboo #mission
tripura@government.gov
Atif has been asked to complete the following code as per the instructions below:
F= #Statement 1
Ch = “ ” #initially stored a space
Dcount = 0
Ccount = 0
While Ch:
#Statement 2
If : #Statement 3
#Statement 4
: #Statement 5
#Stataement 6
print(“Count 1: “,Dcount)
print(“Count 2: “,Ccount)
F.close()
Help him complete the code as per instruction given below:
a. Complete Statement 1 so that the given file is opened for reading.
b. Complete Statement 2 so that one character is read from the open file into
the variable Ch.
c. Complete code for Statement 3 and Statement 4 so that it counts number
of digits in the file, and stores the count in the variable Dcount.
d. Complete code for Statement 5 and Statement 6 so that it counts number
of these special characters ‘@’,’#’ and ‘-‘, in the variable Ccount.
After completing code, what will be the output of produced by the code
CLASS: XII SESSION: 2023-24

COMPUTER SCIENCE (083)


PRACTICE SET
Time allowed: 3 Hours Maximum Marks: 70

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

P_ID Name Desig Salary Allowance


P01 Rohit Manager 89000 4800
P02 Kashish Clerk NULL NULL
P03 Mahesh Supervisor 48000 NULL
P04 Salil Clerk 31000 1900
P05 Ravina Supervisor NULl 2100
Based on the given table, write SQL queries for the following:
a. Increase the salary by 10% of persons whose allowance is given.
b. Display Name and Total salary (sun of salary and allowance) of
all persons. The column heading ‘TOTAL SALARY’ should also
be displayed.
c. Delete the record of Supervisors who have salary greater than
25000.
30 A list, NList, contains following record as list 3

elements: [City, Country, distance from Delhi]

Each of these records are nested together to form a nested list. Write
the following user defined functions in Python to perform the specified
operations on the stack named travel.
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

DELHI HEAD OFFICE

Human Resources

Academics Administration

Shortest distances between various Blocks :


Human Resources to Administration 200 m

Human Resources to Academics 60 m

Academics to Administration 150 m

Delhi Head Office to Bangaluru office Setup 2000 km

The Number of Computers installed at various blocks are as


follows: BLOCK No. of Computers

Human Resources 55

Administration 60

Academics 200

Delhi Head Office 30

(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

D001 INFRASTRUCTURE DELHI

D002 MARKETING DELHI

D003 MEDIA MUMBAI

D005 FINANCE KOLKATA

D004 HUMAN RESOURCE MUMBAI


Table: EMPLOYEE
E_NO NAME DOJ DOB GENDER D_CODE AGE

1001 Vinay 2013-09-02 1991-09-01 MALE D001 25

1002 Ruby 2012-12-11 1990-12-15 FEMALE D003 27

1003 Anuj 2013-02-03 1987-09-04 MALE D005 24

1007 Sunny 2014-01-17 1988-10-19 MALE D004 25

1004 Rohit 2012-12-09 1986-11-14 MALE D001 27

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.
Write SQL queries for the following:
To display D_NAME and CITY from table DEPT where D_NAME ends with letter ‘G’ and CITY is ‘DELHI’.
To delete data of all those employees whose age is less than 25.
To update AGE to 23 of those employee whose E_NO is 1004.
To change the sequence of DOB column in employee table and move it before DOJ
column.
To add a new column MOBILE int(20) before column AGE in employee table.

You might also like