12 CS
12 CS
12 CS
CLASS - XII
STUDENT SUPPORT MATERIAL
CBSE CURRICULUM
PATRON
OUR MOTIVATORS
CONTENTS PREPARED BY
3. Distribution of Marks:
Theory Practical
II Computer Networks 10 15 …
Total 70 110 70
1 Lab Test: 8
1. Python program (60% logic + 20%
documentation + 20% code quality)
2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using
one table / two tables.
● Minimum 4 programs based on Python -
SQL connectivity
4 Viva voce 3
1
Short questions Answers (03 Marks)
i. Write down the name of different types of Tokens.
Answers :-
i. Identifiers :- Roll_Number
ii. Keywords :- int, for, while
iii. Literals :- “Hello”, 123, -12.30
iv. Operators :- >, &, +,*
v. Delimiters :- , ( } [
2
MCQ (01 Marks)
i. Value of variable will be ………………………
ii. We can assign more than one value to variable . yes /not
iii. How many format to declaration of variable is ……………
iv. Data type is ……………… and ……………….
v. Choose correct name of variable
i. Name iii. _123a
ii. int iv. for
vi. Without variable we can write a program. Yes /not
vii. Choose correct statement
i. Name = “Purujee” iii. Str = \n
ii. int =100 iv. char = ‘Puruji’
viii. If z = 10 + 21i then real part = ……….
ix. Example of mapping data type is …………………
x. Boolean variable have ……………… values.
3
Short questions Answers (03 Marks)
i. How many method to initialize values of variables.
Answer:- Two method
1. Static Initialization
2. Dynamic Initialization
ii. What is the difference between static and dynamic initialization of variables?
Answer:-
Static Dynamic
Variable values are assigned at the Variable assigns through key board at
time of variable assign the time of program execution.
Examples if write name=”KV” Example : name=input(“Enter Name
Where Name is Static Variable of School”)
Where Name is Dynamic Variable
Its values will be fixed Its values will be changeable
4
ii. Without keyword , can we write a Python program ? Explain
Answers : No.
Introductions :- All those Data type those values will be change they are known as Mutable
and all those data type which value is not change they are known as immutable data type.
Examples :-
Mutable Data type : List and Dictionary
Immutable Data type : Tuple and String
5
Answer :-
Mutable Immutable
Values can be change Values cannot be change
It is data type It is also data type
Example: List, Dictionary etc. Examples : String, Tuple etc.
6
P =15 >>> p /= 2 then output will be 7. 5 >>> p //= 2 then output will be 7
7
Num = int(input(“Enter value of Num =”))
Name = input( “Enter Name :”)
For displaying data or outcome on screen we are using a function that function is “print( )
“ . It is also known as output function. Its format is given below :-
print(“ Write Statement ”)
print( name of variable )
Examples
print(“ My Name is Purujee”) than display on screen : My Name is Purujee
print(a) than if a =10 then display on screen : 10
Note : With print( ) function following symbol use , they have special meaning in print( )
function.
For new line : “\n”
For blank line : “\b”
For space : “\t”
MCQ (01 Marks)
i. Which function is use to enter data from keyboard …………………
ii. Which function is use to display data on screen …………………….
iii. Choose the correct statement
i. print “Puruji”
ii. print [“ Purujee”]
iii. print(“Purujee”)
iv. print< “Purujee”>
8
Example : Example :
num = int( input( “Enter value of num)) print(“ Enter value of num is :”, num)
9
Short questions Answers (03 Marks)
i. Write a program with comments.
Answer :
Num1 = int ( input (“Enter Value of Num1 =”)) # Enter integer value of Num1
Num2 = int ( input (“Enter Value of Num2 =”)) # Enter integer value of Num2
Sum = Num1 + Num2 # adding Num1 and Num2
print (“Sum of Numbers are = “ , Sum) # Displaying sum of two numbers.
Before developing a program we are using different types of tools and technique for
analysis and analyze the problem . Then after on the basis of use tool we try find out the
solution of problems.
1. Algorithm : An algorithm is a step by step procedure to solve a given problem . It is
also known as well defined structured.
10
2. Flow charts : A flow chart s a graphical representation of step by step an algorithm
to solve a given problem.
3. Pseudo code : it is an informal way of describing the steps of a program solution
without using any strict programming language syntax or underlying technology
consideration.
4. Decision tree : It is way of presenting rules in hierarchical and sequential structure
where based on the hierarchy of rules.
It is simplest form of “if” statement . When given condition is true then output will be
display or generated otherwise no output or display.
Format of “ if “ :-
if (conditions)
Statement ;
In this, when condition is true then output will generated and when condition is false then
output will also generated.
if (condition)
Statement 1;
else
Statement 2 ;
if condtion1
Statement 1 ;
elif condition 2
Statement 2 ;
elif condition 2
Statement 3 ;
--------------------------
--------------------------
else :
Statement 17
11
Range function :-
The range( ) function of Python generate a list. Which is special sequence type . A
sequence in Python is a succession of values bound together by a single name. Examples of
Python sequence types are : Lists, Tuple, String etc.
Format of range function is
range(<lower limit>, <upper limit> )
# both limit should be integers
If range(0,5) then produce [0,1,2,3,4]
If range (5,0) then no list produce
Format
Range(< lower limit>, <upper limit>,<step value>
# both limit and step value should be integers
If range(0,10,2) then (0,2,4,6,8)
If range(5,0,-1) then (5,4,3,2,1 )
Format
range(number)
# number should be interger
If range(5) then (0,1,2,3,4)
For Loop :-
The “for “ loop of Python is designed to process the items of any sequence .
Format for ‘for loop is given below
for <variable name> in [sequence] :
Statements
Where :
Variable Name : it is name of the variable
Sequence : it is use for how many time loop will be executed.
Examples
for a in [1,4,7] :
print (a)
print (a *a)
Output : 1 1 4 16 7 49
While loop :-
A While loop is a conditional loop that will repeat the instructions within itself as long as a
condition remain same.
Format I given below
While <logical expression> :
Loop body
12
Examples
a=5
While a > 0 :
Print (“Hello”, a)
A=a-3
Print(“Loop is over, dear”)
Output
Hello 5
Hello 2
Loop is over, dear
Break jump statement :-
The ‘Break’ statement enables a program o skip over a part of the code . A break
statement terminates the loop in lies within. Execution resumes at the statement
immediately.
Examples :
a=b=c=0
For in in range(1,21):
A = int(input(“Enter Number 1”))
B = int(input(“Enter Number 2”))
If b == 0 :
Print(“ Division by Zero Error ! Aborting )
break
else
C=a/b
Print (“Quotient = “,c)
Print (“Program is over”)
In the continue statement before the “continue “ keyword code will be repeating until given
condition will be satisfy but in continue statement force the next iteration of the loop to
take place.
Examples :
a=b=c=0
For in in range(1,21):
A = int(input(“Enter Number 1”))
B = int(input(“Enter Number 2”))
If b == 0 :
print(“ \n the denominator can not be zero, Enter again” )
continue
else
C=a/b
print (“Quotient = “,c)
13
MCQ (01 Marks)
i. How many type of flow of control ? Two
ii. How many types of statement ? Three
iii. Without range we can use “for” loop ? yes
iv. Is “if” use for looping ? No
v. How many part of range function ? three
vi. “ While” is similar to “for” ? yes
vii. “continue” and “break” are jump statement ? yes
viii. “exit( )” is keyword ? No.
14
Long Questions Answers (04 Marks )
i. Write a program to perform basic operation of calculator. (Write itself)
Note :
Some time we enclosed some things in single quotes they also known as String.
Examples : ‘ Hi Dear Students ‘ , ‘ Are to ready to read Pyhton’
When we enclosed any things in triple quotes that is known as doc string.
Examples : ‘ ‘ ‘ Hi Purujee ‘ ‘ ‘ , ‘ ‘ ‘ Are you from Where ‘ ‘ ‘
Traversal of String : All operation on string perform on the basis of Indexing. When we
travel all string character one by one that is known as traversal of string.
Example :-
0 1 2 3 4 5 6 Forward Indexing
P U R U J E E Name of String
-7 -6 -5 -4 -3 -2 -1 Backward Indexing
Note
Forward Indexing start from Zero (0) but backward indexing start from (-1)
Operation on string:
We can perform following operation on string :-
Suppose String name is : str =”Purujee” str1 = “ from Patna”
Name of operation Format Examples
Slicing Name of String[start : stop: step ] Str [ 0,5,2] then output : “Prj”
Concatenation Str3 = str1 + str2 Str + str 1 then output “
Purujeefrom Patna
Repletion Name of string * < + ve integer values> Str * 2 then output :
PurujeePurujee
Memberships <substring> in / not in <string> Pu in Purujee then Output : True
Reverse String [ :-1 ] Str[:-1] then output : eejuruP
We are using different type of function to perform the different type of operation on String.
Some important string functions are given below :-
15
Suppose String name is : str =”Purujee” str1 = “ Patna # Bihar ”
S.No Name of Function Operation Examples
1 len( ) Find length N = len(str) then N = 7
2 capitalize( ) Return upper str3 = str. capitalize( ) then PURUJEE
case
3 split ( ) Return str1.split( “#” ) then [“Patna” , “Bihar”]
substring
4 replace( ) Replace string str1.replace(“Patna”, “Patliputra”) then
“Patliputr # Bihar”
5 lower( ) Return Lower Str. Lower( ) then “purujee”
case
6 lstrip( ) Remove space Str1.lstrip( ) then “Patna # Bihar ”
from left side
7 rstrip( ) Remove space Str1.rstrip( ) then “ Patna # Bihar”
from right side
8 isspace( ) Return True if Str.isspace( ) then true
whitespace is
present
otherwise false
9 ord( ) Return ASCII ch = ‘b’ then ord(ch) output 98
code of
character
10 chr( ) Return ch = 98 then chr(ch) output b
character
values
11 isalpha( ) Return true if str.isalpha( ) then True
all characters
are alphabets
otherwise false
16
Very Short Questions Answers (02 Marks).
i. What do you mean by String ?
ii. What do you mean by Indexing of String ?
iii. What do you mean by Traversal of string ?
iv. Write about the split ( ) function of string .
v. String can be modify. Explain
vi. Write a program to enter a string and display on screen.
vii. Write a program to add two different string.
viii. Write a program to print index of entered string.
Answer :
a. str[1:3] then “ur”
b. str [ :3 ] then “Pur”
c. str[ 3: ] then “ujee”
d. str[ : ] then “Purujee”
e. str[ - 2: ] then “ee”
f. str[: - 2 ] then “Puruj”
g. str[ : : 2] then “Prje”
17
Name of Topic : List
Introductions :-
The lists are containers that are used to store a list of values of any type. Basically list is
mutable. We Known as which value will be change they are known as mutable in Python .
List is mutable but string and tuples are immutable.
When we enclosed any number, character, symbol in big square bracket. That type of
collection is known as list .We are using three types of list
1. The Empty list Example:: L = list ( )
2. Long List Example :: sqrs = [0,1,4,9,16,25,36,49,64,81,100]
3. Nested List Example :: L1 = [1,3, [4,5],7,8]
Creating list from existing Sequences .
Format :-
L = list ( <sequence>)
Where <sequence > can be any kind of sequence object including string, tuple ad list
>>> L1 = list(“hello”)
>>> L1
[‘h’, ’e’ ,’l’ ,’l’ ,’o’]
Accessing List :-
For Accessing of list we are using following methods
1. Length : use function len(L) for items count in list
2. Indexing and slicing
3. Membership function (in, not in)
4. Concatenation and replication operators
Accessing Individual elements of list
Example
>>> vowels = [‘a’, ’e’ ,’I’ ,’o’ ,’u’]
Then
>>> vowels[0] then ‘a’ wil display
>>> vowels [-1] then ‘u’ will be display
18
Example
>>> L1, L2 = [1,2,3] ,[1,2,3]
>>> L3 = [1, [2,3]]
Now
>>> L1= = L2
True
But When
>>> L1 = = L3
False
19
Working With List :-
Format
del <name of list> [<index>]
Or
del <name of list> [start : stop ]
Example
>>> L1 = [1,2,3,4,5,6,7,8,9,10]
>>> del L1= [5]
>>> L1
[1,2,3,4,5,7,8,9,10]
>>> del L1 =[3,7]
>>> L1
[1,2,3,9,10]
We are using different types of function and method for performing different types of
operation on list.
1. Index Method : list .index(<item>)
2. The append method : list.append(<item>)
3. The Extend method : list .extend(<item>)
20
4. The Insert Method : list. Insert (<pos>,<item>
5. The Pop method : list .pop(<index>)
6. The remove method : list .remove(<value>)
7. The Clear Method : list.clear( )
8. The count method : list. Count(<item>)
list1.extend(list2)
print(list1)
Output of above Program
[‘a’,’b’,’c’,1,2,3]
21
Some Useful program of List :-
L1 =[1,2,3,4,5,6,7,8,9,11,22,33,44,55,66]
L2=['a','b','c']
22
3. Suppose list1 is [2445,133,12454,123], what is max(list1)?
a) 2445
b) 133
c) 12454
d) 123 Answer : c
4. Suppose list1 is [1, 5, 9], what is sum(list1)?
a) 1
b) 9
c) 15
d) Error Answer : c
5. Suppose list1 is [2, 33, 222, 14, 25], What is list1[:-1]?
a) [2, 33, 222, 14]
b) Error
c) 25
d) [25, 14, 222, 33, 2] Answer : a
23
2. What is difference between string and list ?
Answer :
List String
It is mutable It is immutable
It is three type It has not type
Example : L1 = [1,2,3,4] Example: str =”Purujee”
Creation of tuple is similar to the list but at the place of big bracket we put the small
bracket ( )
Format
<name of tuple> (values of tuple) #separated by comma
Example
>>> TP=(1,2,3)
Types of Tuple
1. The Empty Tuple :: >>> TP =( )
2. Single Element Tuple :: >>> TP =(1)
3. Long Tuple :: >>> TP =(1,2,3,4,5,6,7,7,8,9,12)
4. Nested Tuple :: >>> TP = (1,2 ,(3,5))
24
Enter Tuples 1135
>>> T2 than
(‘1’, ’1’, ’3’, ’5’)
25
>>> del <name of tuple>
Or
>>> del <name of tuple> [subscript of tuple]
Examples
>>> T1 =(1,2,3)
>>> del T1 then >>> T1 no exist
>>> del T1 [0] then >>> T1 (2,3) will be display
We are using different types of method and function for performing different types of
operation on given tuples. Some important function /methods are given below :
1. The len( ) method : it is use for find out the length of tuples Example : >>> T1
=(1,2,3) than >>>len(T1) than result will be 3.
2. The max( ) method : it is use for find out the maximum values of the tuple Example
: >>> T1 =(1,2,3) than >>>max(T1) than result will be 3.
3. the min( ) method : it is use for find out the maximum values of the tuple Example :
>>> T1 =(1,2,3) than >>>min(T1) than result will be 2.
4. The index( ) method : it is use for fid out the index of tuple element in tuple Example
: >>> T1 =(1,2,3) than >>>index.T1(1) than result will be 0.
5. The count ( ) function : it is use for count the how many specific elements in tuple.
Example : >>> T1 =(2,1,2,3,2,3,2,4,2) than >>>T1.count(2) than result will be 5.
6. The tuple( ) method : It is use for create tuples from existing tuple.
Format tuple (<Sequence>)
Examples :-
26
# Creating a tuple from keys of dictionary
Example
>>> T1 = tuple({ 1 : “3”, 2: “4”})
>>> T1 then (3,4)
1. >>>t1 = (1, 2, 4, 3)
2. >>>t2 = (1, 2, 3, 4)
3. >>>t1 < t2
a) True
b) False
c) Error
d) None
27
Short questions Answers (03 Marks)
1. Write a program to traversal of given tuple ?
Answer
T1 = (“a”,”b”,”c”)
L = len(T1)
for i in range (0 , L , 1) :
print( “ Element of Tuple at index [“ , i , “] =” , T1[i] )
print( “\n”)
Dictionary is way which is use for organize the data in proper form. We can perform
different types of operation on dictionary with support of function and methods. It is
mutable unordered collection with elements in the form of a” key:value “ pair that
associate keys to values.
Creating a Dictionary :-
Format
<name of dictionary > = {<key : value> , <key : value > …………………………………..}
Example
School = { “teacher “: “Ram” , “salary “ : 10000 , “Hobbies” : “ Chess”}
Note : key of dictionary must be of immutable type.
Format
>>> <dictionary name> [<key>]
Examples
>>> School = { “teacher “: “Ram” , “salary “ : 10000 , “Hobbies” : “ Chess”}
>>> school [“Teacher”]
Then
Ram
>>> school [“salary”]
Then
10000
>>> print (school[“Teacher”])
Then
Ram
28
1. Unordered set
2. Not a sequence
3. Indexed by Key , no number
4. Keys must be unique
5. Mutable
6. Internally stored as mapping
Note : the key of dictionary must be of immutable types such as number or string. A tuple
can also be a key provided a contains immutable elements.
Different Functions :-
We Are using different types of function and method in dictionary for performing
different types of operations. Some are given below
1. The len( ) method : it is use for find out the length of dictionary.
Format >>> len(<name of dictionary>)
2. The clear( ) method : It is use for make dictionary empty
format : >>> <name of dictionary> . <clear>
3. The get( ) method : it is use for find out the similar things in given dictionary
format : <name of dictionary> .get (key. [default])
4. The items( ) method :it is use for return all the items of dictionary.
Format : >>> <name of dictionary> . Items( )
5. The keys( ) method : it is use for return the all keys of the dictionary.
Format : >>> <name of dictionary> . Keys ( )
6. The values( ) method : it is use for return the value of the dictionary
format : >>> <name of dictionary> . Values( )
7. The update ( ) method : It is use merger key :value pair from the new dictionary
into the original dictionary , adding or replacing as needed. Format : >>>
<dictionary> .update (other dictionary
29
MCQ (01 Marks)
1. Dictionary is ……………….
2. Keys and Values are associated ………….
3. Keys values can be change …………..
4. Values of dictionary can not change…………
5. Dictionary totally depend upon …………….
Bubble sorting :-
The basic idea of bubble sort is to compare two adjoining values and exchange them if they
are not proper order. Until all given elements are not come to the proper order.
Insertion Sorting :-
It is a sorting algorithm that builds a sorted list one element at a time from the unsorted
list by inserting the element at its correct position in sorted list
30
MCQ (01 Marks)
1. The process of placing or rearranging a collection of elements into a particular
order is known as
a. Searching
b. Sorting
c. Rearranging
d. Merging
2. Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements in case they are unordered in n-1 passes.
a. Bubble
b. Insertion
c. Complexity
d. Selection
Calling of function :
first way
def calcSomething ( x ):
r = 2 * x ** 2
return r
Second Way
x = int(input(“Enter a number”)
def calcSomething ( x ):
r = 2 * x ** 2
31
return r
print (calcSomething ( x ))
Types of function :-
1. Built in Function : It is pre define function
2. Function define in Module : these function are pre-define for particular module.
3. User define function : it is define by the user or programmer.
32
Scope Variables in Functions :-
1. def cube(x):
2. return x * x * x
3. x = cube(3)
4. print x
a) 9
b) 3
c) 27
d) 30
33
Very Short Questions Answers (02 Marks)
1. How many types of functions .
Answer : Basically function is two type
a. Pre define functions ; Its output is fixed.
b. User define function : Its output is not fixed. This function start from “ def ”
keyword.
2. What do you mean by default arguments ?
Answer : Default argument is parameter of parametrized function. When we do not
passing the parameters in this situation function accept define parameter values
itself that is known as default parameters.
1. Write program to calculate area of triangle, circle , square and rectangle using
function. (write itself)
34
MCQ (01 Marks)
1. How many except statements can a try-except block have?
a) zero
b) one
c) more than one
d) more than zero
2. Is the following Python code valid?
try:
# Do something
except:
# Do something
finally:
# Do something
a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes
35
Scoring tips for Students
Any others.
All contents are based on the CBSE examination pattern for the CBSE Board examination
2023-24.
36
Files – Text Files
A text file stores information in the form of a stream of ASCII or Unicode characters.In text files, each line of
text is terminated, (delimited) with a special character knownas EOL (End of Line) character. In Python, by
default, this EOL character is the newline character ('\n') or carriage-return, newline combination ('\r\n').
The text files can be of following types:
Regular Text files: These are the text files which store the text in the same form as typed. Here the newline
character ends a line and the text translationstake place. These files have a file extension as .txt.
Delimited Text files: In these text files, a specific character is stored to separate the values, i.e., after each
value, e.g., a tab or a comma after everyvalue.
a. When the comma is used to separate the values stored, these are calledCSV files (Comma Separated Values
files). These files take the extensionas .csv.
Files – Binary Files
A binary file stores the information in the form of a stream of bytes. A binary file contains information in the
same format in which the information is held in memory,i.e., the file content that is returned to you is raw (with
no translation or no specificencoding). As a result, binary files are faster and easier for a program to read and
write than are text files. As long as the file doesn't need to be read by people or needto be ported to a different
type of system, binary files are the best way to store program information.
File Object: A file object is a reference to a file on disk. It opens the file and makesit available for a number of
different tasks.
Absolute Vs Relative path:
An absolute path is defined as specifying the location of a file or directory from theroot directory. In other
words, we can say that an absolute path is a complete pathfrom start of actual file system from / directory.
Relative path is defined as the path related to the present working directly.
File Modes: A file mode govern the type of operations (read/write/append)possible in the opened file.
Sr.No. Modes & Description
r: Opens a file for reading only. The file pointer is placed at the beginningof the file. This is
1 the default mode.
r+: Opens a file for both reading and writing. The file pointer placed atthe beginning of
2 the file.
w: Opens a file for writing only. Overwrites the file if the file exists. If thefile does not exist,
3 creates a new file for writing.
w+: Opens a file for both writing and reading. Overwrites the existing fileif the file exists. If
4 the file does not exist, creates a new file for reading and writing.
a: Opens a file for appending. The file pointer is at the end of the file if the file exists. That
5 is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+: Opens a file for both appending and reading. The file pointer is at theend of the file if the
6 file exists. The file opens in the append mode. If thefile does not exist, it creates a new file
for reading and writing.
37
File Read Methods:
Sr.N
Methods & Description
o.
Filehandle.read([n]): reads and return n byres, if n is not specified itreads entire file.
1
Filehandle.readline([n]): reads a line of input. If n is specified reads atmost n bytes. Read
bytes in the form of string ending with end of line character of blank string if no more
2
bytes are left for reading.
Filehandle.readlines(): reads all the lines and return them in a list.
3
with statement: with statement will automatically close the file after the nested blockof code. It is guaranteed to
close the file no matter how the nested block exits. Evenif an exception occurs with statement will handle it and
close the file. It is used in thefollowing manner:
with open(<filename>,<filemode>) as <filehandle>:
<file manipulation statements>
Closing a text file: A close() function breaks the link of file-object and the file on the disk. No tasks cab be
performed after the file is closed.
It is used in the following way:
<file-handle>.close()
The tell() Function: The tell() function returns the current position of the file pointerin a file. It is used as per the
following syntax:
<file-object>.tell()
The seek() Function: the seek() function changes the position of the file pointer byplacing the file pointer at the
specified position in the opened file. It is used as per the following syntax:
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes.
mode: 0 – for beginning of the file – by default 0
1 – for current position of file pointer
2 – for end of the file
38
The seek() Function: the seek() function changes the position of the file pointer byplacing the file pointer at the
specified position in the opened file. Its is used as per the following syntax:
<file-object>.seek(offset[, mode])
offset: is a number specifying number of bytes.
mode: 0 – for beginning of the file – by default 0
1 – for current position of file pointer
2 – for end of the file
Questions – 1 Mark - MCQ
Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above
Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown
Q6. How to open a file such that close function is not needed to be called in orderto close the connection
between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
d. Using open with method
39
Q7. What is the full form of CSV?
a. Common segregated values
b. Comma separated values
c. Common separated values
d. None of the above
Q9. If the cursor in the file is at the end of the file, then what will the read()function return?
a. None
b. False
c. Exception
d. Empty string
Q10. Which is the value of mode parameter to set the offset of the cursor from theend of the file?
a. 0
b. 1
c. 2
d. None of the above
Answer Key
1.d 2.c 3.c 4.c 5.b 6.c 7.b 8.a 9.d 10.c
Questions – 2 Marks – Short Answer
Q1. What is the difference between opening mode ‘a’ and ‘w’?
Q2. What is the purpose of flush() in file handling operations?
Q3. What is the advantage of opening file using with keyword?
Q4. Given a file ‘data.txt’ write a function atoesidp() to display the file after replacing ‘a’ with ‘e’.
Q5. What is the advantage of saving a file in text form and binary form?
Q6. Write the output of the following program
f = open(‘data.txt’, ’w+’)
f.write(‘0123456789abcdef’)
f.write(‘xyz1234’)
f.seek(0)
print( f.read())
f.close()
Q7. If a file ‘f.txt’ contains data ‘Good’ and then what is the content of the file
f.txt then following program in run?
f = open(‘f.txt’, ‘w’)
f.write(‘Bye’)
f.close()
S. Answer Key
No
40
1 ‘w’ is used to write in file from the beginning. If file already exists then it
will overwrite the previous content.
‘a’ is also used to write in the file. If file already exists it will write after
the previous content.
2 The flush function forces the writing of data on disk still pending in output
buffer. Flush allows the user to send the content in file before closing thefile.
3 With keyword reduces the overheads involved in the closing of the file after file operation
or handling the file closing after exception have occurred. When file is opened using
‘with’ it will manage the closing of file
at the end of the operations or after an exception automatically.
4 def atoedisp():
f = open(‘data.txt’)
r = f.read()for ch in r:
if ch == ‘a’: print(‘e’, end = ‘’)
else:
print(ch, end = ‘’)
5 Text files are stored in the human readable format. These have someinternal conversions
like newlines etc.
Binary file store data in pure binary form and hence can be used on anymachine/hardware
with appropriate software.
6 0123456789abcdefxyz1234
7 Bye
Existing data will be overwritten.
Questions – 3 Marks – Long Answer
Q1. Write a program to read a text file and display the count of lowercase and uppercase letters in the file.
Q2. Write a method in python to read lines from a text file INDIA. TXT, to find and display the Occurrence of
the word "India".
Q3. Write a function count_line() in python that counts and display the lines starts with ‘P’ in the text file named
“data.txt”.
Q4. Write a program to read a text file line by line and display each word separated by a #.
Q5. Write a function vowelCount() in python that counts and display the numbers of vowels in the text file named
“Story.txt”.
S. Answer Key
No
1. myfile = open( "Answer.txt", "r")
ch = “ ” #initially stored a space ( a non-None value)
lcount = 0 #variable to store count of lowercase letters
ucount 0
while ch: #while ch stores a Non-None
valuech = myfile.read(1) #one character read from file
if ch.isupper() == True:
ucount ucount+1
else:
lcount = lcount + 1
print("Uppercase letters in the file: ", ucount)
41
print ("Lowercase letters in the file: ", lcount)
myfile.close()#close the file
2. def display1():
count = 0
file = open( 'INDIA. TXT ‘, 'r’)
LINE=file.read()
Words=LINE. split()
for W in Words:
if W= "India":
count count +1
print (count)
file.close()
3. def countline():
f=open(“data.txt”,’r’)
lines=f.readlines()
for i in lines:
if i[0]= = ‘P’:
print(i)
f.close()
4. myfile = open( "Answer.txt", "r")
line = " ”
while line:
line = myfile.readline() # one line read from file
# printing the line word by word using split()
for word in line.split():
print (word, end = '#’)
print()
#close the file
myfile.close()
5. def vowelCount():
f=open(‘Story.txt’,’r’):
s=f.read()
vow=[‘A’,’E’,’I’,’O’,’U’,’a’,’e’.’i’,’o’,’u’]
count=0
for x in s:
if x in vow:
count+=1
print(“No. of vowels in the given txt file is:”,count)
f.close()
Binary Files
Binary files store data in the binary format (0’s and 1’s) which is understandable bythe machine. So when we open
the binary file in our machine, it decodes the data and displays in a human-readable format.
Binary File Modes: File mode governs the type of operations read/write/appendpossible in the opened file. It
refers to how the file will be used once its opened.
File Description
Mode
42
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is
created. If file exists, it overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended
at the end.
rb+ Read and Write: File should exist, Both read and write operations can
be performed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is
truncated.
Pickle Module: Python Pickle is used to serialize and deserialize a python object structure. Any object on python
can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte stream.
Unpickling: A byte stream is converted into object hierarchy. To use the picking methods in a program, we have
to import pickle module using import keyword.
Example:
import pickle In this module, we shall discuss to functions of pickle module, which are:
i. dump( ) : To store/write the object data to the file.
ii. ii. load( ) : To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(List_name, file-object )
Read the object from a file:
pickle.load(file-object)
1 Mark Questions
1. The process of converting byte stream back to the original structure is known as
a. Pickling b. Unpickling c. Packing d. Zipping
5. Which of the following file mode opens a file for append or read a binary file and moves the files pointer at the
43
end of the file if the file already exist otherwise create a new file?
a. a
b. ab
c. ab+
d. a+
Answer Key
1. a 2. a 3. d 4. c 5. c
5 Mark Questions
2. Write a python program to create binary file dvd.dat and write 10 records init Dvd id,dvd name,qty,price
Display those dvd details whose dvd price more than 25.
ii.
def searchRollNo( r ):
f=open("student.dat","rb")
flag = False
while True:
try:
rec=pickle.load(f)
if rec[0] == r :
print(rec[‘Rollno’])
print(rec[‘Name’])
print(rec[‘Marks])
flag = True
except EOFError:
break
if flag == False:
print(“No record Found”)
f.close()
2. import pickle
f=open("pl.dat","ab")
ch="Y"
while ch=="Y":
44
L=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
L.extend([pi,pnm,sp,p])
pickle.dump(l,f)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.dat","rb+")
try:
while True:
L=pickle.load(f)
if L[3]>25:
print(l)
except EOFError:
pass
f.close()
A csv file is a type of plain text file that uses specific structuring to arrange tabular data. csv is a common format
for data interchange as it is compact, simple and general.
Each line of the file is one line of the table.
csv files have .csv as file extension.
As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.
Read a CSV file: To read data from a CSV file, we have to use reader( ) function. The reader function takes each
row of the file and make a list of all columns.
CODE:
import csv
with open('C:\\data.csv','rt') as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
print(row)
OUTPUT:
45
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
Write data to a CSV file: When we want to write data in a CSV file you have to use writer( ) function. To iterate
the data over the rows (lines), you have to use the writerow( ) function.
CODE:
import csv
with open('C:\\data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"' ) #write new record in file
writer.writerow(['3', 'Shivani', 'Commerce', '448'])
writer.writerow(['4', 'Devansh', 'Arts', '404'])
OUTPUT:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
When we shall open the file in notepad (Flat file) then the contents of the file will look like this:
Roll No.,Name of student,stream,Marks
1,Anil,Arts,426
2,Sujata,Science,412
3,Shivani,Commerce,448
4,Devansh,Arts,404
1 Mark Questions
1. What does the acronym CSV stand for in its full form?
a. Common Separated Value
b. Comma System Value
c. Comma Separated Value
d. Common System Vault
3. In regards to separated value files such as .csv and .tsv, what is the delimiter?
a. Any character such as the comma (,) or tab (\t) that is used to separate the row data
b. Anywhere the comma (,) character is used in the file
c. Delimiters are not used in separated value files
d. Any character such as the comma (,) or tab (\t) that is used to separate the column data.
4. In separated value files such as .csv and .tsv, what does the first row in the file typically contain?
46
a. The source of the data
b. The author of the table data
c. Notes about the table data
d. The column names of the data
5. Assume you have a file object my_data which has properly opened a separated value file that uses the tab
character (\t) as the delimiter.What is the proper way to open the file using the Python csv module and assign it to
the variable csv_reader?
Assume that csv has already been imported.
a. csv_reader = csv.tab_reader(my_data)
b. csv_reader = csv.reader(my_data)
c. csv_reader = csv.reader(my_data, tab_delimited=True)
d. csv_reader = csv.reader(my_data, delimiter='\t')
Answer Key
1. c 2. b 3. d 4. d 5. d
4 Mark Questions
1. Write a Program in Python that defines and calls the following user defined functions:
(i) ADDPROD( ) – To accept and add data of a product to a CSV file ‘product.csv’. Each record consists of a
list with field elements as prodid, name and price to store product id, employee name and product price
respectively.
(ii) COUNTPROD( ) – To count the number of records present in the CSV file named ‘product.csv’.
2. Write a Program in Python that defines and calls the following user defined functions:
(i) add() – To accept and add data of a to a CSV file ‘stud.csv’. Each record consists of a list with field
elements as admno, sname and per to store admission number, student name and percentage marks
respectively.
(ii) search()- To display the records of the students whose percentage is more than 75.
3. Manoj 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 ______________ #Line1
def addCsvFile(UserName, Password):
fh=open('user.csv','_____________') #Line2
Newfilewriter=csv.writer(fh)
Newfilewriter.writerow([UserName,Password])
fh.close( ) # csv file reading code
47
(a) What module should be imported in #Line1 for successful execution of the program?
(b) In which mode file should be opened to work with user.csv file in#Line2
(c) Fill in the blank in #Line3 to read data from csv file
(d) Fill in the blank in #Line4 to close the file
4. Radha Shah is a programmer, who has recently been given a task to write a python code to perform the
following CSV file operations with the help of two user defined functions/modules:
(a) . CSVOpen() : to create a CSV file called “ books.csv” in append mode containing information of books
– Title, Author and Price.
(b). CSVRead() : to display the records from the CSV file called “ books.csv” .where the field title starts
with 'R'. She has succeeded in writing partial code and has missed out certain statements, so she has left
certain queries in comment lines.
import csv
def CSVOpen( ):
with open('books.csv','______',newline='') as csvf: #Statement-1
cw= csv.writer(csvf)
______ #Statement-2
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead( ):
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-3
for r in cr:
if ______: #Statement-4
print(r)
except:
print('File Not Found')
CSVOpen( )
CSVRead( )
You as an expert of Python have to provide the missing statements and other related queries based on the
following code of Radha.
(a) Write the appropriate mode in which the file is to be opened in append mode (Statement 1)
(b) Write the correct option for Statement 2 to write the names of the column headings in the CSV file,
books.csv
(c) Write statement to be used to read a csv file in Statement 3.
(d) Fill in the appropriate statement to check the field Title starting with „R‟ for Statement 4 in the above
program.
2. import csv
def add():
fout=open("stud.csv","a",newline='\n')
wr=csv.writer(fout)
admno=int(input("Enter Admission No :: "))
sname=input("Enter Student name :: ")
per=int(input("Enter percentage :: "))
st=[fid,sname,per]
wr.writerow(st)
fout.close()
def search():
fin=open("stud.csv","r",newline='\n')
data=csv.reader(fin)
found=False
print("The Details are")
for i in data:
if int(i[2])>75:
found=True
print(i[0],i[1],i[2])
if found==False:
print("Record not found")
fin.close()
#main program
add()
print("Now displaying")
search()
3. a) csv
b) w
c) reader()
d) close()
4. (a) a
(b) cw.writerow(['Title','Author','Price'])
(c) csv.reader(csvf)
(d) r[0][0]=='R‟
49
Data Structure: Stack, operations on stack (push & pop), implementation of stack using list
Introduction :
Data structures: A data structure is a named group of data of different data types which is stored in a specific
way and can be processed as a single unit. It has well defined operations, behavior and properties.
Stack: It is a linear structure implemented in LIFO (Last In First Out) manner where insertions and deletions
are restricted to occur only at one end – stack’s top.
LIFO means element last inserted would be the first one to be deleted. For example, a pile of books, a stack
of coins, where you can remove only the top book or the coin placed at the top (Fig.1).
1. Creating a Stack
To create an empty Stack, use inbuilt function list() or [] as per the syntax given below:
Syntax :
Stack=list()
Stack=[]
In order to access the elements in a Stack, index values are used. Thus, the first element in the Stack will
be Stack[0], and so on.
ANSWER KEY
1.(d) 5 2 1* 2. (a) append() 3. (a) pop() 4. (a) overflow 5. Overflow 6.
Underflow 7. STACK 8. PUSH 9. POP 10. It is
a linear structure implemented in LIFO (Last In First Out) manner where insertions and deletions are
restricted to occur only at one end – stack’s top.
Long Answer Type Question – 3 Marks
2. Vedika has created a dictionary containing names and marks as key-value pairs of 5 students.
Write a program, with separate user-defined functions to perform the following operations:
51
(i) Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 70.
(ii) (ii) Pop and display the content of the stack.
def push(stk,item):
for i in item:
if item[i]>70:
stk.append(i)
def Pop(stk):
if stk= =[]:
return None
else:
return stk.pop()
52
Unit II: Computer Networks
Network: A computer network is a set of computers connected together for the purpose of sharing
resources. Each computer on the network is called a node.
Disadvantages of Networking
1. Threat to data: A computer network may be used by unauthorized users to steal or corrupt the data
and even to deploy computer virus or worms on the network.
2. Difficult to set up:
Evolution of Networking:
Internet:
➢ a global computer network providing a variety of information and communication facilities,
consisting of interconnected networks using standardized communication protocols
➢ Network of Networks
➢ Popularly known as “NET”
53
Intranet:
➢ Intranet is a local or restricted communications network, especially a private network created using
World Wide Web softwares.
➢ It is managed by any person/ organization
➢ Intranet user can avail services of Internet whereas Internet user cannot access intranet directly.
Interspace:
➢ Interspace is a client/server software program that allows multiple users to communicate online
with real time audio, video and text chat in dynamic 3D environment.
➢ Online video conferencing is an example of Interspace.
Switching techniques are used for transferring data across network. In large network, there might be
multiple path linking the sender and receiver. Information may be switched as it travels through various
communication channel.
Three types of Switching techniques
1. Circuit Switching
➢ First the complete physical connection between two computers is established and then the data are
transmitted from the source computer to the destination
➢ When a call is placed the switching equipment within the system seeks out a physical copper path
all the way from the sender to the receiver.
➢ It is must to setup an end-to-end connection between computers before any data can be sent.
➢ The circuit is terminated when the connection is closed.
➢ In circuit switching, resources remain allocated during the full length of a communication, after a
circuit is established and until the circuit is terminated and the allocated resources are freed
2. Packet Switching Packet switching introduces the idea of cutting data i.e. at the source entire message is
broken in smaller pieces called packets which are transmitted over a network without any resource being
allocated.
➢ Then each packet is transmitted and each packet may follow any rout available and at destination
packets may reach in random order.
➢ At the destination when all packets are received they are merged to form the original message.
➢ In packet switching all the packets of fixed size are stored in main memory.
3. Message Switching In message Switching, data is first stored by one node then forward to another node
to transfer the data to another system.
➢ In message Switching, data is first stored, then forwarded to the next node
➢ In Message Switching there is no upper bound on size of packet whereas in Packet Switching each
packet is of fixed size.
➢ In Packet Switching data packets are stored in main memory whereas in Message Switching
Message is stored in Hark disk which makes it reducing the access time
54
Communication terminologies:
Communication Channel (Transmission media): Is a medium through which a message is transmitted to
its intended destination. Communication channel can be wired (Guided) or Wireless (Unguided).
Bandwidth: Is a range of frequencies within a given band that is used for transmitting an analog signal.
Bandwidth is expressed in Hz, KHz, and MHz
Data transfer rate: DTR is the amount of data in digital form that is moved from one place to another in a
given time on a network. Data rates are often measured in megabits (million bits) or megabytes (million
bytes) per second.
Twisted pair cable It consists of two identical 1 mm thick copper wires insulated and twisted together. The
twisted pair cables are twisted in order to reduce crosstalk and electromagnet ic induction
Co-axial Cables It consists of a solid wire core surrounded by one or more foil or braided wire shields,
each separated from the other by some kind of plastic insulator. It is mostly used in the cable wires.
Optical fiber An optical fiber consists of thin glass fibers that can carry information in the form of visible
light.
Infrared Wave Transmission Short Range Communication: Infrared waves can travel from a few
centimetres to several meters.(Approx. 5m )
Radio Wave Transmission : Radio waves can cover distances ranging from a few
meters (in walkie-talkies) up to covering an entire city
Micro Wave Transmission: Microwave signals travel at a higher frequency than radio waves and are used
for transmitting data over several miles or kilometres.
55
Satellite Link
Satellite is a relay station in orbit above the earth that receive from one end of earth (uplink) regenerates,
and redirects signals to other end of earth (downlink).
Network devices:
Modem (MOdulator DEModulator) is an electronic device which converts digital
signals into analog signals for transmission over telephone lines (Modulation). At
the receiving end, a modem performs the reverse function and converts analog
signal into digital form (Demodulation) A modem can also amplify a signal so that
it can travel a long distance without attenuation.
RJ-45 (Registered Jack – 45) is an eight wired connector that is used to connect
computers on a local area network (LAN), especially Ethernet.
Ethernet card is a kind of network adapter and is also known as Network Interface
Card (NIC). These adapters support the Ethernet standard for high-speed network
connections via cables. An Ethernet Card contains connections for either coaxial
or twisted pair cables or fiber optic cable
Repeater When the data is transmitted over a network for long distances, the
data signal gets weak due to attenuation. A repeater regenerates the received
signal and re-transmits it to its destination.
Router is a network device used to establish connection between two similar networks. They can connect
networks with different architectures such as Token Ring and Ethernet. But, routers cannot transform
information from one data format to another such as TCP/IP to IPX/SPX.
Gateway is a device, which is used to connect dissimilar networks and perform the necessary translation
so that the connected networks can communicate properly. A gateway can translate information between
different network data formats and network architectures. It can translate TCP/IP to AppleTalk so
computers supporting TCP/IP can communicate with Apple brand computers.
56
Wi-Fi cards are small and portable cards that allow your computer to connect to the internet through a
wireless network.
Network Topologies It refers to the geometrical arrangement of nodes in a (LAN). The criteria for
choosing a topology: Installation cost, Reliability, Flexibility, Fault detection etc.
Bus Topology In bus topology all the nodes are connected to a main cable called backbone. If any node
has to send some information to any other node, it sends the signal to the backbone. The signal travels
through the entire length of the backbone and is received by the node for which it is intended.
Star Topology In star topology each node is directly connected to a hub/switch. If any node has to send
some information to any other node, it sends the signal to the hub/switch.
Tree topology is a combination of bus and star topologies. It is used to combine multiple star topology
networks. All the stars are connected together like a bus. This bus-star hybrid approach supports future
expandability of the network
57
Network Types:
PAN (Personal Area Network): Spread in the proximity of an individual
58
WAN (Wide Area Network): Spread across a city, country, or continent.
Network Protocol A protocol is the special set of rules that two or more machines on a network follow to
communicate with each other. Some of the important protocols used are as follows:
TCP/IP (Transmission Control Protocol / Internet Protocol): Communication between two computers
on internet is done using TCP/IP protocol. TCP/IP is a two-layer protocol.
➢ Using the TCP protocol a single large message is divided into a sequence of packets of size
limits from 128 to 4096 bytes.
➢ Each packet is independent and has the address of sender and destination.
➢ The IP (Internet protocol) does the routing for the packets. It keeps track of all the different routes
available to the destination. If one route is not available it finds the alternate route to the destination.
➢ At the destination, the TCP protocol re-assembles the packets into the complete message.
FTP (File Transfer Protocol) The File Transfer Protocol (FTP) is a standard network protocol used for the
transfer of computer files from a server to a client using the Client–server model on a computer
network.
PPP (Point to Point Protocol): In computer networking, Point-to-Point Protocol (PPP) is a data link
protocol used to establish a direct connection between two nodes. The Point-to-Point Protocol (PPP) is an
encapsulation protocol for transporting IP traffic across point-to-point links. PPP is used over many types
of physical networks including serial cable, phone line, trunk line, cellular telephone, radio links, and fibre
optic links etc.
Simple Mail Transfer protocol (SMTP): Simple Mail Transfer Protocol, a protocol for sending e-mail
messages between servers. Most e-mail systems that send mail over the Internet use SMTP to send
messages from one server to another; In addition, SMTP is generally used to send messages from a mail
client to a mail server. The messages can then be retrieved with an e-mail client using either POP or
IMAP. This is why you need to specify both the POP or IMAP server and the SMTP server when you
configure your e-mail application.
ESMTP (Extended Simple Mail Transfer Protocol) specifies extensions to the original SMTP protocol
for sending e-mail that supports graphics, audio and video files, and text in various national languages.
59
MIME (Multi-Purpose Internet Mail Extensions) is an extension of the original Internet e-mail protocol
that lets people use the protocol to exchange different kinds of data files on the Internet: audio, video,
images, application programs, and other kinds, as well as the ASCII text handled in the original protocol,
the Simple Mail Transport Protocol (SMTP).
Post Office Protocol Version 3 (POP3): POP3 is a client/server protocol used for opening the remote e-
mail boxes, the POP3 mail server receives e-mails, filters and holds them into the appropriate user
folders. When a user connects to the mail server to retrieve his mail, the messages are downloaded from
mail server to the user's hard disk.
Remote Access Protocol (Telnet) : This protocol helps a user (Telnet Client) to log in at a remote
computer (Telnet Server) and function as if he/she were connected directly to that computer. Telnet is the
main internet protocol for creating a connection with a remote machine. It allows you to connect to remote
computers (called remote hosts) over a TCP/IP network (such as the Internet).
60
Domain Names: Every computer on the network has a unique numeric address assigned to it which is a
combination of four numbers from 0-255 separated by a dot. For example, 59.177.134.72 since it is
practically impossible for a person to remember the IP addresses. A system has been developed which assigns
domain names to web servers and maintains a database of these names and corresponding IP addresses on
DNS (Domain Name Service) server.
URL (Uniform resource locator): A URL is a formatted text string used to identify a network resource
on the Internet. Network resources can be plain Web pages, text documents, graphics, downloadable files,
services or programs. Every network resource on the web has a unique URL in the following format:
Protocol: // domain name /path / file name The URL text string consists of three parts:
➢ Network Protocol: The network protocol identifies the protocol to be used to access the network
resource. These strings are short names followed by the three characters ': //’. Some examples of
protocols include http, gopher, ftp and mailto.
➢ Domain name: It identifies the host/server that holds the resource. For example: www. School.com
is a domain name.
➢ Resource Location: It consists of the path or directory and the file name of resource. For example
in the URL : http://www.school.com/syllabus/preprimary/nursery.htm the file nursery.htm is
stored in the sub directory preprimary, of the directory syllabus on the server www.school.com
Website: Related webpages from a single web domain is termed as a website. A website has multiple
webpages providing information about a particular entity.
Web browser: Web browser is software program to navigate the web pages on the internet. A bowser
interprets the coding language of the web page and displays it in graphic form. Internet works on client -
server model. A web browser is a client which requests the information from the web server. The web server
sends the information back to the client. Some of the web browsers are: Netscape Navigator, Internet
Explorer, Mozilla Firefox etc.
Web Server: A Web server is a computer or a group of computers that stores web pages on the internet. It
works on client/server model. It delivers the requested web page to web browser. Web servers use special
programs such as Apache or IIS to deliver web pages over the http protocol. Each server has a unique IP
address and domain name. In order to access a webpage, the user writes the URL of the site on the address
bar of the browser. The machine on which the browser is running sends a request to the IP address of the
machine running the web server for that page. Once the web server receives that request, it sends the page
content back to the IP address of the computer asking for it. The web browser then translates that content
into all of the text, pictures, links, videos, etc. A single web server may support multiple websites or a single
website may be hosted on several linked servers.
Web hosting: Web hosting is the process of uploading/saving the web content on a web server to make
it available on WWW. In case an individual or a company wants to make its website available on the
internet, it should be hosted on a web server.
Web page: Web page is an electronic document designed using HTML. It displays information in textual
or graphical form. It may also contain downloadable data files, audio files or video files. Traversal from one
webpage to another web page is possible through hyperlinks.
61
MCQs:
1. Combination of two or more networks are called
A. Internetwork B. WAN C. MAN D. LAN
3. National Internet Service Provider (ISP) networks are connected to one another by private switching
stations called
A. Network Access Points B. Peering Points C. National ISP D. Regional ISP
4. Multipoint topology is
A. Bus B. Star C. Mesh D. Ring
5. A communication path way that transfers data from one point to another is called
A. Link B. Node C. Medium D. Topology
8. Synonymous of rule is
A. Standard B. Protocol C. Forum D. Agency
62
A. Ring B. Hybrid C. Mesh D. Bus
19. Working document with no official status and a 6-month lifetime is called
A. Internet draft B. Internet standard C. Internet Protocol D. Regulatory Agencies
20. Organization that is developing cooperation in realms of scientific, technological and economic activity
is .
A. Institute of Electrical and Electronics Engineers B. International Organization for Standardization
C. American National Standards Institute D. Electronic Industries Association
Answer:
1A 2A 3B 4A 5A 6D 7A 8B 9B 10D 11A 12A 13D 14C
15C 16C 17C 18A 19A 20B 21D 22A 23B 24C 25C
2. What is Extranet?
Ans: External users are allowed or provided with access to use the network application of the organization.
3. How can you recover the data from a system which is infected with virus?
Ans: In another system (not infected with virus) install an OS and antivirus with the latest updates. Then
connect the HDD of the infected system as a secondary drive. Now scan the secondary HDD and clean it.
Then copy the data into the system.
4. What protocols can be applied when you want to transfer files between different platforms?
Ans: FTP
6. What happens when you use cables longer than the prescribed length?
Ans: Cables that are too long result in signal loss. This means that data transmission and reception would
be affected because the signal degrades over length.
8. You need to connect two computers for file sharing. Is it possible to do this without using a hub or
router?
Ans: Yes, you can connect two computers together using only one cable. A crossover type cable can be used
in this scenario. In this setup, the data transmit pin of one cable is connected to the data receive pin of the
other cable and vice-versa.
9. When you move the NIC cards from one PC to another PC, does the MAC address gets transferred as
well?
Ans: Yes, because MAC addresses are hard wired into the NIC circuitry, not the PC.
64
11. Why can’t wireless network detect collisions?
Ans: CSMA/CD can’t be used on a wireless. Using CSMA/CD, if a collision is detected on the medium,
end-devices would have to wait a random amount of time before they can start retransmission process.
15. Which protocol is used to send a destination network unknown message back to originating hosts?
Ans: ICMP
17. What protocol is used to find the hardware address of a local device?
Ans: ARP
18. What is hop count?
Ans: Hop count is the number of routers occurring in between the source and destination network. The path
with the lowest hop count is considered as the best route to reach a network and therefore placed in the
routing table.
19. How many maximum hop counts are allowed for RIP (Routing Information Protocol)?
Ans: 15.
Hop count of 16 is considered as network unreachable.
20. What is congestion?
Ans: It is a state occurring in network layer when the message traffic is so heavy that it slows down
network response time.
65
5) What do you mean by HTTP?
Answer: HTTP stands for Hyper Text Transfer Protocol and the port for this is 80. This protocol is
responsible for web content.
6) What do you mean by TCP and UDP?
Answer: TCP stands for Transfer control protocol and UDP stands for User Datagrams protocol and TCP is
a connection-oriented protocol and UDP is a Connectionless protocol.
7) What do you mean by a Firewall?
Answer: Firewall is a concept of a security system that will helps computers to protect it with unauthorized
access or any cyber-attack.
8) What do you mean by DNS?
Answer: DNS Stands for Domain Name System. It’s an internet address mapping process with the local
name. We can also call it as an internet phonebook.
9) What do you mean by Proxy server?
Answer: Proxy server prevents the external users which are unauthorized to access the network.
10) What do you mean by NIC?
Answer: NIC stands for Network interface card. It is an adapter that will be installed on the computer and
because of that NIC, only that computer will interact with the network.
11) What do you mean by ASCII?
Answer: ASCII is the American Standard Code for Information Interchange.
12) What are the types of mode available in Network?
Answer: Data transferring mode in a computer network will be of three types: Simplex, Half-Duplex and
Full Duplex.
13) What do you mean by SLIP protocol?
Answer: SLIP stands for Serial Line Interface Protocol. It is used for sending IP datagram over a network
in a single line.
14) What do you mean by Decoder?
Answer: A decoder is a program which converts the encrypted data into its actual format.
66
NETWORKING (4 Marks Questions)
1. Multipurpose Public School, Bengaluru is setting up the network between its different wings of
school campus. There are 4 wings named as:-
(i) Suggest the best wired medium and draw the cable layout to efficiently connect various wings of
Multipurpose Public School, Bengaluru.
(ii) Name the most suitable wing where the servers should be installed. Justify your answer.
(iii) Suggest a device/software and its placement that would provide data security for the entire
network of the school.
(iv) Suggest a device and a protocol that shall be needed to provide wireless internet access to all
smartphone/laptop users in the campus of Multipurpose Public School, Bengaluru.
67
Answers:
(i) Best wired medium: Optical fibre/CAT5/CAT6/CAT7/CAT8/Ethernet Cable.
Layout:
2. Intelligent Hub India is a knowledge community aimed to uplift the standard of skills and
knowledge in the society. It is planning to setup its training centres in multiple towns and villages
pan India with its head offices in the nearest cities. They have created a model of their network with
a city, a town and 3 villages as given.
As a network consultant, you have to suggest the best network related solution for their
issues/problems raised
in (i) to (iv) keeping in mind the distance between various locations and given parameters.
68
Note:
• In Villages, there are community centres, in which one room has been given as training center to this
organization to install computers.
• The organization has got financial support from the government and top IT companies.
1. Suggest the most appropriate location of the SERVER in the YHUB (out of the 4 locations), to get
the best and effective connectivity. Justify your answer.
2. Suggest the best wired medium and draw the cable layout (location to location) to efficiently
connect various locations within the YHUB.
3. Which hardware device will you suggest to connect all the computers within each location of
YHUB?
4. Which server/protocol will be most helpful to conduct live interaction of Experts from Head office
and people at YHUB locations?
Answers:
(i) YTOWN
Justification
Layout:
69
3. Indian School, in Mumbai is starting up the network between its different wings. There are four
Buildings named as SENIOR, JUNIOR, ADMIN and HOSTEL as shown below:
1.
70
2. Server can be placed in the ADMIN building as it has the maximum number of computers.
3. Repeater can be placed between ADMIN
and SENIOR building as the distance is more than 110 m.
4. Radiowaves can be used in hilly regions as they can travel through obstacles.
4) Vidya Senior Secondary Public School in Nainital is setting up the network between its different wings.
There are 4 wings named as SENIOR(S), JUNIOR(J), ADMIN(A) and HOSTEL(H).
Distance between various wings are given below:
1.
2. Server should be in Wing S as it has the maxi-mum number of computers. 1
3. All Wings need hub/switch as it has more than
one computer.
4. Fiber Optics.
71
5) Trine Tech Corporation (TTC) is a professional consultancy company. The company is planning to set
up their new offices in India with its hub at Hyderabad. As a network adviser, you have to understand
their requirement and suggest them the best available solutions. Their queries are mentioned as (i) to (iv)
below.
Physical Locations of the blocked of TTC
1. What will be the most appropriate block, where TTC should plan to install their server?
2. Draw a block to cable layout to connect all the buildings in the most appropriate manner for
efficient communication.
3. What will be the best possible connectivity out of the following, you will suggest to connect the
new setup of offices in Bangalore with its London based office:
o Satellite Link
o Infrared
o Ethernet Cable
4. Which of the following device will be suggested by you to connect each computer in each of the
buildings:
o Switch
o Modem
o Gateway
72
Answers:
1. Finance block because it has maximum
number of computers.
2.
3. Satellite link
4. Switch
6) G.R.K International Inc. is planning to connect its Bengaluru Office Setup with its Head Office in Delhi.
The Bengaluru Office G.R.K. international Inc. is spread across and area of approx. 1 square kilometer,
consisting of 3 blocks – Human Resources, Academics and Administration.
You as a network expert have to suggest answers to the four queries (i) to (iv) raised by them.
1. Suggest the most suitable block in the Bengaluru Office Setup, to host the server.
Give a suitable reason with your suggestion.
2. Suggest the cable layout among the various blocks within the Bengaluru Office Setup for
connecting the Blocks.
3. Suggest a suitable networking device to be installed in each of the blocks essentially required for
connecting computers inside the blocks with fast and efficient connectivity.
4. Suggest the most suitable media to provide secure, fast and reliable data connectivity between Delhi
Head Office and the Bengaluru Office Setup.
Answers:
1. Human Resources because it has maximum number of computers.
2.
3. Switch 1
4. Fiber Optics
73
(Abbreviations)
74
STUDY MATERIAL
CLASS - XII
Information – processed data are called information. It is related to some other entity.
E.g. 4 is a roll number of shyam, here 4 is information.
Database – it is a collection of interrelated data in organized manner. A table or group of tables is called
database.
Database Management System (DBMS) – It is a type of software that is responsible for storing,
manipulating, maintaining and utilizing database.
Relational Database Management System (RDBMS) – it is similar to DBMS with some advance feature
like joining of tables, Integrity constraint feature, group by with having etc.
Degree –Total number of attributes or columns of a table or relation is called degree in RDBMS
Cardinality –Total number of tuples or rows of a table or relation is called cardinality in RDBMS
Domain – It is a pool of values from which the actual values appearing in the given column are drawn.
75
Board type question
1. Define the term Domain with respect to RDBMS. Give one example to support your answer.
Ans. It is a pool of values from which the actual values appearing in the given column are drawn.
Ex - All the names of name columns of any given table.
2. Write the difference between degree and cardinality.
Ans. Total number of attributes or columns of a table or relation is called degree and total number of tuples
or rows of a table or relation is called cardinality
-----------------------------------------------------------------------------------------------------------------------
Structured Query Language (SQL) - Structured Query Language (SQL) is a standardized programming
language that is used to manage relational databases and perform various operations on the data in them.
MYSQL Elements:
1. Literals
2. Data types
3. Null
4. Comments
Literals
It means the fixed value or constant value. It may be of character, numeric or date time type.
Character and date/time literals are always in single quotation marks whereas numeric literals must be
without single quotation marks.
For example – ‘Virat’, 12, 12.56, ‘04-20-2018’.
date and time values are always in the format YYYY-MM-DD HH:MI:SS.
Special character like quotes are always written be preceding it back-slash(\). For example if we want to store
value as Tom’s Cat then it should be written as Tom\’s Cat
Data Type
Means the type of value and type of operation we can perform on data. For example, on numeric value we
can store numbers and perform all arithmetic operations and so on.
76
MySQL support three categories of data types:
➢ Numeric
➢ Date and time
➢ String types
➢ Numeric Data Types
FLOAT(M,D) Real numbers i.e. number with decimal. M specify length of numeric value
including decimal place D and decimal symbol. For example if it is given as
FLOAT(8,2) then 5 integer value 1 decimal symbol and 2 digit after decimal
TOTAL – 8. it can work on 24 digits after decimal.
DECIMAL It is used to store exact numeric value that preserves exact precision for e.g.
money data in accounting system.
DECIMAL(P,D) means P no. of significant digits (1-65), D represent no. of
digit after decimal(0-30), for e.g. DECIMAL(6,2) means 4 digit before
decimal and 2 digit after decimal. Max will be 9999.99
Char varchar
Fixed length string Variable length string
Fast, no memory allocation every time Slow, as it take size according to data so
77
every
time memory allocation is done
It takes more memory It takes less space
MySQL - MySQL is freely available open source RDBMS software that uses Structured Query Language
(SQL) to create and manage databases.
DATA DEFINITION LANGUAGE COMMANDS (DDL) –These commands are used to create or modify
the tables in SQL.
1. CREATE TABLE
1. CREATE DATABASE
2. USE
4. DESC
78
DATA DEFINITION LANGUAGE COMMANDS (DDL):
ALTER TABLE- it is used to change the data type and size of columns. It is also used to add new column or
delete column.
EXAMPLE –
EX – USE TEST;
79
EX – CREATE DATABASE NITYA;
EX – DESC STUDENT;
1. INSERT
2. DELETE
3. UPDATE
4. SELECT
EXAMPLE –
EX – UPDATE STUDENT
80
SET MARKS=500
WHERE NAME=‘NITYA’;
NOTE – THIS COMMAND IS ALSO USED TO FILL THE DATA IN PLACE OF NULL VALUE
SELECT COMMAND - This command is used to display the records of the table.
7. Sorting of Data
Ascending order
1. Select * from stu
Order by name;
Or
Select * from stu
Order by name asc;
Descending order
82
2. Select * from stu
Order by name desc;
Ans.
83
c.
Roll City Fee
2 Patna 300
-----------------------------------------------------------------------------------------------------------------------------------
Functions in SQL:
Function is used to perform some particular task and it returns zero or more values as a result.
Categories of functions in SQL
1. Single row functions -
Single row functions are applied on a single value and return a single value.
There are three categories of Single row function — Numeric (Math), String, Date and Time.
a. Numeric functions
87
COUNT(column) Returns the number of mysql> SELECT * from
values in the specified MANAGER;
column ignoring the NULL
values. +------ +---------+
Note: | MNO | MEMNAME |
In this example, let us +------ +---------+
consider a MANAGER
| 1 | AMIT |
table having two attributes
and four records. | 2 | KAVREET |
| 3 | KAVITA |
| 4 | NULL |
+------+----------+
4 rows in set (0.00 sec)
mysql> SELECT
COUNT(MEMNAME)
FROM MANAGER;
+----------------+
| COUNT(MEMNAME) |
+----------------+
|3|
+----------------+
1 row in set (0.01 sec)
-----------------------------------------------------------------------------------------------------------------------------------
Group By clause - It is used to combining those records that have identical values. It is used with aggregate
functions.
88
Group By with having -
Having clause is used to place condition on aggregate function in conjunction with group by clause.
89
Board type question
Relation: PRODUCT
AVG(Price) PNAME
2100 TV
38500 PC
90
18000 HANDYCAM
91
Board type question
Table : Brand
BID BName
M03 Medimix
92
M04 Pepsodent
M05 Dove
93
Candidate keys : all the columns of a table which consists of unique values and can be used to uniquely
identification of records are called candidate keys. Among all candidate keys one attribute is selected as
primary key.
Primary key – it is a column of a table consisting unique values and used to uniquely identification of
records.
Ex- adm_no
Alternate key – all the candidate keys which are not selected as primary key, called Alternate keys
Ex – roll_no, Contact_no
Foreign key – A primary key of one table is called foreign key of other table if a relationship is created
between them.
3. Ms. Shalini has just created a table named “Employee” containing 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
Constraints -
94
Constraints are the certain types of restrictions on the data values that an attribute can have.
Types of constraint
EXAMPLE –
1. Amit is working in a database named XIIC, in which he has created a table named “Student”
containing columns Roll, Name, marks, and address.
After creating the table, he realized that the attribute, city of data type string has to be added. This attribute
city cannot be left blank. Help Amit to write the commands to complete the task.
Ans.
------------------------------------------------------------------------------------------------------------------
95
DATABASE CONNECTIVITY
In order to connect to a database from within Python, you need a library that provides connectivity
functionality. There are many different libraries available for Python to accomplish this. We shall work with
‘mysql connector library’ for same.
Example---
cursor= mycon.cursor()
data= cursor.fetchmany(3)
print(row)
mycon.close()
96
EXTRACT DATA FROM RESULTSET
Once the result of query is available in the form of a resultset stored in a cursor object, we can extract
data from the resultset using any of the following fetch() functions.
(i) <data>= fetchall(): It will return all the records retrieved as per query in a tuple form (i.e. now <data>
will be tuple)
(ii) <data>= fetchone(): It will return one record from the resultset as a tuple or a list. First time it will return
the first record, next time it will fetch the next record and so on.
(iii) <data>= fetchmany(<n>): This method accepts number of records to fetch and returns a tuple.
(iv) <variable>= rowcount: It returns the n number of rows retrieved from the cursor so far.
1. Arnav wants to write a program in Python to insert the following record in the table named Studentin
MYSQL database, SCHOOL:
• Username - root
• Password - kvs
• Host – localhost
• Database – XII
The values of fields rno, name, doband feehas to be accepted from the user. Help Arnavr to write the
program in Python.
Ans.
cursor= mycon.cursor()
97
rno=int(input(“enter roll=”))
name=input(“enter name=”))
dob=input(“enter dob=”)
cursor.execute(query1)
mycon.commit()
mycon.close()
Nitya, now wants to display the records of students whose fee is more than 5000. Help Nitya to write the
program in Python.
Ans.
cursor= mycon.cursor()
cursor.execute(query1)
98
data= cursor.fetchall()
print(row)
mycon.close()
99