Notes
Notes
com/
CLASS-XII
SUBJECT: COMPUTER SCIENCE (083) – PYTHON
INDEX
CHAPTER PAGE
CHAPTER NAME
NO. NO.
1 FUNCTIONS IN PYTHON 2
2 RECURSION 10
3 FILE HANDLING 13
5 PROGRAM EFFICIENCY 28
https://pythonschoolkvs.wordpress.com/ Page 1
CHAPTER-1
FUNCTIONS IN PYTHON
1.1 Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
https://pythonschoolkvs.wordpress.com/ Page 2
2. Functions defined in modules:
a. Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3)
20.085536923187668
Example:
import random
n=random.randint(3,7)
https://pythonschoolkvs.wordpress.com/ Page 3
Where:
Example:
def display(name):
https://pythonschoolkvs.wordpress.com/ Page 4
1.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
(7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
https://pythonschoolkvs.wordpress.com/ Page 6
OUTPUT:
Hello
None
Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 7
Here, we can see that the value of x is 20 initially. Even though the function my_func()changed
the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the
one outside. Although they have same names, they are two different variables with different
scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
https://pythonschoolkvs.wordpress.com/ Page 9
CHAPTER-2
RECURSION
2.1 Definition: A function calls itself, is called recursion.
2.2 Python program to find the factorial of a number using recursion:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
https://pythonschoolkvs.wordpress.com/ Page 10
return(fibonacci(n-1)+fibonacci(n-2))
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
https://pythonschoolkvs.wordpress.com/ Page 11
Program:
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)
https://pythonschoolkvs.wordpress.com/ Page 12
CHAPTER-3
FILE HANDLING
3.1 INTRODUCTION:
File:- A file is a collection of related data stored in a particular area on the disk.
Stream: - It refers to a sequence of bytes.
File handling is an important part of any web application.
S.
Text Files Binary Files
No.
Example:
To open a file for reading it is enough to specify the name of the file:
f = open("book.txt")
The code above is the same as:
f = open("book.txt", "rt")
Where "r" for read mode, and "t" for text are the default values, you do not need to specify
them.
Text Binary
file File Description
mode Mode
‘r’ ‘rb’ Read - Default value. Opens a file for reading, error if the file does not
exist.
‘w’ ‘wb’ Write - Opens a file for writing, creates the file if it does not exist
‘a’ ‘ab’ Append - Opens a file for appending, creates the file if it does not exist
‘r+’ ‘rb+’ Read and Write-File must exist, otherwise error is raised.
‘x’ ‘xb’ Create - Creates the specified file, returns an error if the file exists
https://pythonschoolkvs.wordpress.com/ Page 14
In addition you can specify if the file should be handled as binary or text mode
“t” – Text-Default value. Text mode
“b” – Binary- Binary Mode (e.g. images)
Print/Access data
https://pythonschoolkvs.wordpress.com/ Page 15
Let a text file “Book.txt” has the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is official language of google.”
OUTPUT: OUTPUT:
Python is interactive language. It is case sensitive Python is
language.
It makes the difference between uppercase and
lowercase letters.
It is official language of google.
https://pythonschoolkvs.wordpress.com/ Page 16
Some important programs related to read data from text files:
Program-a: Count the number of characters from a file. (Don’t count white spaces)
fin=open("Book.txt",'r')
str=fin.read( )
L=str.split( )
count_char=0
for i in L:
count_char=count_char+len(i)
print(count_char)
fin.close( )
fin=open("D:\\python programs\\Book.txt",'r')
str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
To write the data to an existing file, you have to use the following mode:
https://pythonschoolkvs.wordpress.com/ Page 18
Example: Open the file "Book.txt" and append content to the file:
fout= open("Book.txt", "a")
fout.write("Welcome to the world of programmers")
Example: Open the file "Book.txt" and overwrite the content:
fout = open("Book.txt", "w")
fout.write("It is creative and innovative")
Program: Write a program to take the details of book from the user and write the record
in text file.
fout=open("D:\\python programs\\Book.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :3
Enter details of record : 1
Enter the title of book : java
Enter price of the book: 250
Enter details of record : 2
Enter the title of book : c++
Enter price of the book: 300
Enter details of record : 3
Enter the title of book : python
Enter price of the book: 450
https://pythonschoolkvs.wordpress.com/ Page 19
"a" - Append - will append to the end of the file.
Program: Write a program to take the details of book from the user and write the record
in the end of the text file.
fout=open("D:\\python programs\\Book.txt",'a')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record :", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )
OUTPUT:
How many records you want to write in a file ? :2
Enter details of record : 1
Enter the title of book : DBMS
Enter price of the book: 350
Enter details of record : 2
Enter the title of book : Computer
Networking
Enter price of the book: 360
d. Delete a file: To delete a file, you have to import the os module, and use remove( )
function.
import os
os.remove("Book.txt")
https://pythonschoolkvs.wordpress.com/ Page 20
import os
if os.path.exists("Book.txt"):
os.remove("Book.txt")
else:
print("The file does not exist")
Output:
https://pythonschoolkvs.wordpress.com/ Page 21
Output:
Once upon a time
Output:
14
Example:
fout=open("story.txt","w")
fout.write("Welcome Python")
fout.seek(5)
print(fout.tell( ))
fout.close( )
Output:
5
3.8 File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
encoding Returns the encoding format of the file
closed Returns True if the file closed else returns False
https://pythonschoolkvs.wordpress.com/ Page 22
Example:
f = open("D:\\story.txt", "r")
print("Name of the File: ", f.name)
print("File-Mode : ", f.mode)
print("File encoding format : ", f.encoding)
print("Is File closed? ", f.closed)
f.close()
print("Is File closed? ", f.closed)
OUTPUT:
Name of the File: D:\story.txt
File-Mode : r
File encoding format : cp1252
Is File closed? False
Is File closed? True
https://pythonschoolkvs.wordpress.com/ Page 23
CHAPTER-4
CREATE & IMPORT PYTHON LIBRARIES
4.1 INTRODUCTION:
Python has its in-built libraries and packages. A user can directly import the libraries and its
modules using import keyword. If a user wants to create libraries in python, he/she can create
and import libraries in python.
Example:
Let’s create a package named Shape and build three modules in it namely Rect, Sq and Tri to
calculate the area for the shapes rectangle, square and triangle.
Step-1 First create a directory and name it Shape. (In this case it is created under
C:\Users\ViNi\AppData\Local\Programs\Python\Python37-32\ directory path.)
Step-2 Create the modules in Shape directory.
To create Module-1(Rect.py), a file with the name Rect.py and write the code in it.
class Rectangle:
def __init__(self):
print("Rectangle")
https://pythonschoolkvs.wordpress.com/ Page 24
To create Module-2(Sq.py), a file with the name Sq.py and write the code in it.
class Square:
def __init__(self):
print("Square")
def Area(self, side):
self.a=side
print("Area of square is : ", self.a*self.a)
To create Module-3 (Tri.py), a file with the name Tri.py and write the code in it.
class Triangle:
def __init__(self):
print("Trinagle")
Step-3 Create the __init__.py file. This file will be placed inside Shape directory and can be
left blank or we can put this initialisation code into it.
from Shape import Rect
from Shape import Sq
from Shape import Tri
That’s all. Package created. Name of the package is Shape and it has three modules namely
Rect, Sq and Tri.
https://pythonschoolkvs.wordpress.com/ Page 25
from Shape import Rect
from Shape import Sq
from Shape import Tri
OUTPUT:
Rectangle
Area of Rectangle is : 200
Square
Area of square is : 100
Trinagle
Area of Triangle is : 24.0
https://pythonschoolkvs.wordpress.com/ Page 26
r=Shape.Rect.Rectangle( )
s=Shape.Sq.Square( )
t=Shape.Tri.Triangle( )
Method-2:
If we want to access a specific module of a package then we can use from and import
keywords.
Syntax:
from package-name import module-name
Example:
from Shape import Rect
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
Method-3:
If a user wants to import all the modules of Shape package then he/she can use * (asterisk).
Example:
from Shape import *
r=Rect.Rectangle( )
s=Sq.Square( )
t=Tri.Triangle( )
https://pythonschoolkvs.wordpress.com/ Page 27
CHAPTER-5
PROGRAM EFFICIENCY
5.1 INTRODUCTION:
Program efficiency is a property of a program related to time taken by a program for execution
and space used by the program. It is also related to number of inputs taken by a program.
Complexity: To measure the efficiency of an algorithm or program in terms of space and time.
The program which uses minimum number of resources, less space and minimum time, is
known as good program.
Complexity
Time and space complexity depends on lots of things like hardware, operating system,
processors, size of inputs etc.
Best case: The minimum number of steps that an algorithm can take for any input data
values.
Average case: The efficiency averaged on all possible inputs. We normally assume the
uniform distribution.
Worst case: The maximum number of steps that an algorithm can take for any input
data values.
https://pythonschoolkvs.wordpress.com/ Page 28
5.2 Estimation the complexity of a program:
Suppose you are given a list L and a value x and you have to find if x exists in List L.
Simple solution to this problem is traverse the whole List L and check if the any element is
equal to x.
Each of the operation in computer take approximately constant time. Let each operation
takes t time. The number of lines of code executed is actually depends on the value of x.
During analysis of algorithm, mostly we will consider worst case scenario, i.e., when x is not
present in the list L. In the worst case, the if condition will run n times where n is the length of
the list L. So in the worst case, total execution time will be (n∗t+t). n∗t for the if condition
and t for the return statement.
As we can see that the total time depends on the length of the list L. If the length of the list will
increase the time of execution will also increase.
Order of growth is how the time of execution depends on the length of the input.
In the above example, we can clearly see that the time of execution is linearly depends on the
length of the list.
Order of growth in algorithm means how the time for computation increases when you increase
the input size. It really matters when your input size is very large.
For example, a process requiring n2 steps and another process requiring 1000n2 steps and
another process requiring 3n2+10n+17 steps. All have O(n2) order of growth. Order of growth
provides a useful indication of how we may expect the behavior of the process to change as we
change the size of the problem. Depending on the algorithm, the behaviour changes. So, this is
one of the most important things that we have to care when we design an algorithm for some
given problem.
https://pythonschoolkvs.wordpress.com/ Page 29
There are different notations to measure it and the most important one is Big O notation which
gives you the worst case time complexity.
for i in range(1, num + 1): print("factorial does not exist for negative numbers")
factorial = factorial*i elif num==0:
https://pythonschoolkvs.wordpress.com/ Page 30
else:
end=time.time() print("The factorial of ",num," is ", factorial(num))
t=end-start end=time.time( )
OUTPUT: OUTPUT:
Enter a number: 5 enter the number: 5
Recursive program is taking less time than without recursion program. So, Program with
recursion is efficient. Therefore, we can conclude that Performance of algorithm is inversely
proportional to the wall clock time.
https://pythonschoolkvs.wordpress.com/ Page 31
CHAPTER-6
DATA VISUALIZATION USING PYPLOT
6.1 NTRODUCTION:
Data visualization basically refers to the graphical or visual representation of information and
data using charts, graphs, maps etc.
pyplot is an interface, which exists in matplotlib library.
To draw the lines, charts etc. first of all we have to install matplotlib library in our
computer and import it in the python program.
matplotlib is a package which is used to draw 2-D graphics.
Program:
import matplotlib.pyplot as pl #pl is alias for matplot.pyplot
x=[2, 8] # values of x1 and x2
y=[5, 10] #values of y1 and y2
pl.plot(x,y) # to create a line
https://pythonschoolkvs.wordpress.com/ Page 32
pl.xlabel("Time") #label name for x-axis
pl.ylabel("Distance") #label name for y-axis
pl.show() #to show the line
Output:
color code
Red ‘r’
Green ‘g’
https://pythonschoolkvs.wordpress.com/ Page 33
Blue ‘b’
Yellow ‘y’
Magenta ‘m’
Black ‘k’
Cyan ‘c’
White ‘w’
Line width:
Syntax:
matplotlib.pyplot.plot(data1, data2, linewidth=value)
Example:
matplotlib.pyplot.plot(x, y, ‘c’, linewidth=6)
Line style:
Syntax:
matplotlib.pyplot.plot(data1, data2, linestyle = value)
Example:
matplotlib.pyplot.plot(x, y, ‘:’)
https://pythonschoolkvs.wordpress.com/ Page 34
Different types of line styles:
-. Dash-dot line
https://pythonschoolkvs.wordpress.com/ Page 35
Some marker types for plotting:
Note: color of the line and marker type can be written combined e.g. ‘ro’ means red color of
the line with circle marker. If you don’t specify the linestyle separately along with linecolor
and marker type combination. Example:
with combination of line color and marker type with combination of line color, marker type along
with linestyle
https://pythonschoolkvs.wordpress.com/ Page 36
6.2.2 Bar Chart:
A bar chart is a graphical display of data using bars of different heights.
import the matplotlib library and pyplot interface.
pyplot interface has bar( ) function to create a bar chart.
To set the lables for x-axis and y-axis, xlabel( ) and ylabel( ) functions are used.
Use show( ) function to display the bar chart.
There are two types of bar charts:
1. Single bar chart
2. Multiple bar chart
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 37
The bar( ) function has width argument to set the width of all bars. It has color argument also,
to change the color of bars.
https://pythonschoolkvs.wordpress.com/ Page 38
2. Multiple Bar Charts:
Program:
import matplotlib.pyplot as pl
import numpy as np # importing numeric python for arange( )
boy=[28,45,10,30]
girl=[14,20,36,50]
X=np.arange(4) # creates a list of 4 values [0,1,2,3]
pl.bar(X, boy, width=0.2, color='r', label="boys")
pl.bar(X+0.2, girl, width=0.2,color='b',label="girls")
pl.legend(loc="upper left") # color or mark linked to specific data range plotted at location
pl.title("Admissions per week") # title of the chart
pl.xlabel("week")
pl.ylabel("admissions")
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 39
Syntax for legend( ):
matplotlib.pyplot.legend(loc= ‘postion-number or string’)
Example:
matplotlib.pyplot.legend(loc= ‘upper left’)
OR
matplotlib.pyplot.legend(loc= 2)
upper right 1
upper left 2
lower left 3
lower right 4
center 10
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
pl.pie(part)
pl.show( )
https://pythonschoolkvs.wordpress.com/ Page 40
Add Labels to slices of pie chart:
To display labels of pie chart, pie( ) function has labels argument.
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
pl.pie(part, labels=['abc','pqr','xyz','def'])
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 41
autopct argument calculates automatic percentage for each share.
autopct argument has a formatted string as a value. Example : %1.1f%%
Syntax for formatted string is:
%<flag><width> . <precision><type>% %
o % symbol: In the starting and ending, the % symbol specifies that it is a special
formatted string. One more % after the type is to print a percentage sign after
value.
o flag: if digits of value are less than width, then flag is preceded to value.
o width: Total number of digits to be displayed (including the digits after decimal
point). If the value has more digits than the width specifies, then the full value is
displayed.
o precision: Number of digits to be displayed after decimal point.
o type: Specifies the type of value. f or F means float type value, d or i means
integer type value.
Example:
%07.2f%%
Where
% = starting and ending % specifies that it is a special formatted string
0= flag
7=width
2= digits after decimal point
f=float type
%= percentage sign to be displayed after value
https://pythonschoolkvs.wordpress.com/ Page 42
then percentage of first share:
= (12*100)/(12+25+10+32)
= 1200/79
=15.19
OUTPUT:
Exploding a slice:
Add explode argument to pie( ) function.
Example:
import matplotlib.pyplot as pl
part=[12,9,69,10]
clr=['g','m','y','c']
ex=[0, 0.2, 0, 0] # exploding 2nd slice with the distance 0.2 units
https://pythonschoolkvs.wordpress.com/ Page 43
pl.pie(part, colors=clr, labels=['abc','pqr','xyz','def'], autopct='%1.1f%%', explode=ex)
pl.show( )
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 44
CHAPTER-7
DATA STRUCTURE-I (LINEAR LIST)
7.1 INTRODUCTION:
Definition: The logical or mathematical model of a particular organization of data is called
data structure. It is a way of storing, accessing, manipulating data.
DATA STRUCTURE
LINKED
ARRAY STACK QUEUE TREE GRAPH
LIST
1. Linear data structure: It is simple data structure. The elements in this data structure creates
a sequence. Example: Array, linked list, stack, queue.
2. Non-Linear data structure: The data is not in sequential form. These are multilevel data
structures. Example: Tree, graph.
https://pythonschoolkvs.wordpress.com/ Page 45
7.3 OPERATION ON DATA STRUCTURE:
There are various types of operations can be performed with data structure:
1. Traversing: Accessing each record exactly once.
2. Insertion: Adding a new element to the structure.
3. Deletion: Removing element from the structure.
4. Searching: Search the element in a structure.
5. Sorting: Arrange the elements in ascending and descending order.
6. Merging: Joining two data structures of same type. (not covered in syllabus)
Output:
10
20
30
40
50
b. Inserting Element in a list: There are two ways to insert an element in a list:
(i) If the array is not sorted
(ii) If the array is sorted
https://pythonschoolkvs.wordpress.com/ Page 46
(i) If the array is not sorted: In this case, enter the element at any position using insert( )
function or add the element in the last of the array using append( ) function.
Example:
L=[15,8,25,45,13,19]
L.insert(3, 88) # insert element at the index 3
print(L)
Output:
[15, 8, 25, 88, 45, 13, 19]
(ii) If the array is sorted: In this case, import bisect module and use the functions bisect( ) and
insort( ).
bisect( ) : identifies the correct index for the element and returns the index.
insort( ): Inserts the element in the list in its correct order.
Example:
import bisect
L=[10,20,30,40,50]
print("Array before insertion the element:", L)
item=int(input("Enter the element to insert in array: "))
pos=bisect.bisect(L,item) #will return the correct index for item
bisect.insort(L,item) #will insert the element
print("Element inserted at index: ", pos)
print("Array after insertion the element : ", L)
OUTPUT:
Array before insertion the value: [10, 20, 30, 40, 50]
Enter the element to insert in array: 35
Element inserted at index : 3
Array after insertion the element : [10, 20, 30, 35, 40, 50]
Note: bisect( ) works only with that lists which are arranged in ascending order.
https://pythonschoolkvs.wordpress.com/ Page 47
c. Deletion of an element from a List: To delete an element from a list we can use remove( )
or pop( ) method.
Example:
L=[10,15,35,12,38,74,12]
print("List Before deletion of element: ", L)
val=int(input("Enter the element that you want to delete: "))
L.remove(val)
print("After deletion the element", val,"the list is: ", L)
OUTPUT:
List Before deletion of element: [10, 15, 35, 12, 38, 74, 12]
Enter the element that you want to delete: 12
After deletion the element 12 the list is: [10, 15, 35, 38, 74, 12]
d. Searching in a List:
There are two types of searching techniques we can use to search an element in a list. These
are:
(i) Linear Search
(ii) Binary Search
https://pythonschoolkvs.wordpress.com/ Page 48
break
else:
print("Element not Found")
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
https://pythonschoolkvs.wordpress.com/ Page 49
if found>=0:
print(element, "Found at the position : ",found+1)
else:
print("Element not present in the list")
OUTPUT:
Enter the elements in sorted order: [12,23,31,48,51,61,74,85]
Enter the element that you want to search : 61
61 Found at the position : 6
e. Sorting: To arrange the elements in ascending or descending order. There are many sorting
techniques. Here we shall discuss two sorting techniques:
(i) Bubble sort
(ii) Insertion sort
(i) BUBBLE SORT: Bubble sort is a simple sorting algorithm. It is based on comparisons, in
which each element is compared to its adjacent element and the elements are swapped if they
are not in proper order.
https://pythonschoolkvs.wordpress.com/ Page 50
PROGRAM:
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
if L[i]>L[i+1]:
OUTPUT:
The sorted list is : [8, 12, 24, 45, 60, 77, 87, 90]
https://pythonschoolkvs.wordpress.com/ Page 51
(ii) INSERTION SORT: Sorts the elements by shifting them one by one and inserting the
element at right position.
PROGRAM:
n=len(L)
for j in range(1,n):
temp=L[j]
prev=j-1
prev=prev-1
Enter the elements: [45, 11, 78, 2, 56, 34, 90, 19]
The sorted list is : [2, 11, 19, 34, 45, 56, 78, 90]
7.4.2. Multi-Dimensional array (Nested Lists): A list can also hold another list as its element.
It is known as multi-dimensional or nested list.
A list in another list considered as an element.
Example:
>>>NL=[10, 20, [30,40], [50,60,70], 80]
>>> len(NL)
5
>>>secondlist=[1,2,3,[4,5,[6,7,8],9],10,11]
>>> len(secondlist)
6
Example-2:
>>> L=["Python", "is", "a", ["modern", "programming"], "language", "that", "we", "use"]
>>> L[0][0]
'P'
>>> L[3][0][2]
'd'
>>> L[3:4][0]
['modern', 'programming']
>>> L[3:4][0][1]
'programming'
>>> L[3:4][0][1][3]
'g'
>>> L[0:9][0]
'Python'
>>> L[0:9][0][3]
'h'
>>> L[3:4][1]
IndexError: list index out of range
https://pythonschoolkvs.wordpress.com/ Page 54
CHAPTER-8
DATA STRUCTURE-II (STACK AND QUEUE)
8.1 STACK IN PYTHON:
8.1.1 INTRODUCTION:
Stack is a linear data structure.
Stack is a list of elements in which an element may be inserted or deleted only at one
end, called the TOP of the stack.
It follows the principle Last In First Out (LIFO).
There are two basic operations associated with stack:
o Push : Insert the element in stack
o Pop : Delete the element from stack
def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)
s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You entered wrong choice ")
https://pythonschoolkvs.wordpress.com/ Page 56
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
cd=True
else:
cd=False
Exponentiation ↑ 1
https://pythonschoolkvs.wordpress.com/ Page 57
Element Operation Stack Result
5 Push 5
6 Push 5, 6
2 Push 5, 6, 2
+ Pop 5, 8 6+2=8
* Pop 40 5*8=40
12 Push 40, 12
4 Push 40, 12, 4
/ Pop 40, 3 12/4=3
- Pop 37 40-3=37
https://pythonschoolkvs.wordpress.com/ Page 58
8.1.5 Infix to Postfix Conversion:
Example-1 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A + B * ( C-D ) / E )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element in expression
+ (+ A Operator, so push into stack
B (+ AB Move the element in expression
* (+* AB Operator, push into stack, * has higher precedence than
+, so can come after +
( (+*( AB Push the open parentheses symbol into stack
C (+*( ABC Move the element in expression
- (+*(- ABC Operator, push into stack
D (+*(- ABCD Move the element in expression
) (+* ABCD - Closing parentheses, so pop the elements of the stack up
to opening parentheses
/ (+/ ABCD - * Operator, / and * operators have the same precedence,
so associativity from left to write will take place and *
will pop from stack and / will push into stack
E (+/ ABCD - *E Move the element in expression
) ABCD - * E / + Closing parentheses, so pop the elements of the stack up
to opening parentheses
Example-2 : Convert the following infix expression into its equivalent postfix expression.
Y= ( A / B - ( C*D ↑ E ) + F )
Symbol Stack Expression Description
( ( Push the symbol in stack
A ( A Move the element into expression
/ (/ A Operator, so push into stack
B (/ AB Move the element into expression
- (- AB/ Operator, - has lower precedence than /. so, / will pop
from stack and – will push into stack.
( (-( AB/ Push the symbol into stack
C (-( AB/C Move the element into expression
* (-(* AB/C Operator, push into stack
D (-(* AB/CD Move the element into expression
↑ ( - ( *↑ AB/CD Operator, ↑ has higher precedence than *, so can come
after *.
E ( - ( *↑ AB/CDE Move the element into expression
https://pythonschoolkvs.wordpress.com/ Page 59
) (- AB/CDE↑ * Closing parentheses, so pop the elements of the stack up
to opening parentheses
+ (+ AB/CDE↑ * - Operator, - and + both have same precedence, to
associativity from left to right take place. – will pop
from stack then + will push into stack.
F (+ AB/CDE↑ * - F Move the element into expression
Remove Insert
10 20 30 40 50 60
front rear
8.2.2 MENU BASED PROGRAMME FOR QUEUE:
class Queue:
def __init__(Q):
Q.items = [ ]
https://pythonschoolkvs.wordpress.com/ Page 60
Q.rear=Q.items[len(Q.items)-1]
print("Now Front is: ", Q.front)
print("Now Rear is: ", Q.rear)
def size(Q): # Size of the queue i.e. total no. of elements in queue
return len(Q.items)
#main method
q = Queue( )
print("MENU BASED QUEUE")
cd=True
while cd:
print(" 1. ENQUEUE ")
print(" 2. DEQUEUE ")
print(" 3. Display ")
print(" 4. Size of Queue ")
https://pythonschoolkvs.wordpress.com/ Page 61
q.Enqueue(val)
elif choice==2:
if q.items==[ ]:
print("Queue is empty")
else:
print("Deleted element is :", q.Dequeue( ))
elif choice==3:
print(q.items)
elif choice==4:
print("Size of the queue is :", q.size( ))
else:
print("You entered wrong choice ")
https://pythonschoolkvs.wordpress.com/ Page 62
A Circular Queue can be seen as an improvement over the Linear Queue because:
1. There is no need to reset front and rear, since they reset themselves. This means that
once the front or rear reaches the end of the Queue, it resets itself to 0.
2. The rear and front can point to the same location - this means the Queue is empty.
Job Scheduling
Traffic Signals
https://pythonschoolkvs.wordpress.com/ Page 63
def C_enqueue(CQ,data): #Adding elements to the queue
if (CQ.rear+1) % CQ.maxSize==CQ.front:
CQ.rear = -1
CQ.rear = (CQ.rear + 1) % CQ.maxSize
CQ.queue[CQ.rear]=data
if CQ.front = = -1:
print("Queue is empty")
elif CQ.front = = CQ.rear:
CQ.queue.pop(CQ.front)
CQ.front=CQ.front+1
else:
CQ.queue.pop(CQ.front)
CQ.front = (CQ.front + 1) % CQ.maxSize
https://pythonschoolkvs.wordpress.com/ Page 64
#main
q = CircularQueue()
print("MENU BASED CIRCULAR QUEUE")
cd=True
while cd:
print("1. ENQUEUE")
print("2. DEQUEUE")
print("3. DISPLAY ")
print("4. Front Position ")
print("5. Rear Position ")
if choice==1:
val=input("Enter the element: ")
q.C_enqueue(val)
elif choice==2:
q.C_dequeue()
elif choice==3:
print(q.queue)
elif choice==4:
print("Front element position :", q.front)
elif choice==5:
print("Rear element position : ", q.rear)
https://pythonschoolkvs.wordpress.com/ Page 65
else:
print("You entered invalid choice: ")
https://pythonschoolkvs.wordpress.com/ Page 66
https://pythonschoolkvs.wordpress.com/
CLASS-XII
COMPUTER SCIENCE-PYTHON (083)
UNIT-II COMPUTER NETWORKS
By: Vikash Kumar Yadav
PGT-Computer Science
K.V. No.-IV ONGC Vadodara
2.1 INTRODUCTION:
Network: - To connect more than one devices via a medium, is called network.
1. LAN:
*Use in small local area, like in an institute or an organization.
https://pythonschoolkvs.wordpress.com/ Page 1
* Devices are connected via physical medium.
* Limited distance, up to 150 Meter.
* Example - Intranet
2. MAN:
* Larger than LAN.
* Used in Metropolitan cities.
*Range up to 50 KM.
3. WAN:
* Large network
* Public
* Example – Internet
4. PAN:
* For very small distance
* Private Communication
* Example: Bluetooth
WEB:
World Wide Web started in 1989, launched by ‘ Tim Berners Lee’ .
The web is a service that run on the internet.
It is collection of web pages.
INTERNET:
It is a network of networks.
Web is a part of internet and runs on internet.
It is a public network.
2.4 CLOUD COMPUTING:
A kind of internet based computing where resources, storage, data and information
computing services are provided on-demand.
One can use remote servers using cloud computing instead of configure or install its
personal server.
It is a way to deploy and manage the services over internet.
Example:
Storage and Backup: Google Drive, Dropbox, Onedrive
https://pythonschoolkvs.wordpress.com/ Page 2
Chatbots: Google assistant, Siri, Alexa
Scalable uses (Subscription models): Netflix
Communication : Skype, WhatsApp
Productivity: Microsoft Office 365, Google docs
Business: Marketo, Salesforce
Social Networking: Facebook, Twitter, Myspace
https://pythonschoolkvs.wordpress.com/ Page 3
2.4.2 Advantages and disadvantages of cloud computing:
Advantages:
Cost reduction : Companies can save money by using shared resources.
Increased storage : Instead of purchasing large amount of storage, companies can
increase the storage as per requirement on nominal charges.
Highly Automated : As per software and hardware requirement, service providers
keeps the things up to date and available.
Greater mobility : Once the information is stored in the cloud, one can access the
information anywhere, anytime.
Keeps things updated
Disadvantages:
Security
Data privacy
Where the data stored.
Always need of internet to access data
Service unavailability
Connect the physical objects through internet for communication and sense interaction.
Example:
o Smart Home: To control the home remotely, like start the A.C., lock or unlock
the door, etc.
o Wearables: They collect the data and information about the user and processed
it for the user. Fitness and health devices, smart watches etc.
o Cars: To control the car or other vehicles.
o Smart Cities: Smart surveillance, automated transportation, smarter energy
management systems, water distribution, urban security and environmental
monitoring all are examples of internet of things applications for smart cities.
o Agriculture: Sensing for soil moisture and nutrients, controlling water usage for
plant growth and determining custom fertilizer are some simple uses of IoT.
o Smartphone detection.
https://pythonschoolkvs.wordpress.com/ Page 4
2.5.1 COMPONENTS OF IoT:
a. Low power embedded system
b. Cloud Computing
c. Availability of big data
d. Network connection
2. Tracking: The computers keep a track both on the quality and the viability of things at
home. Knowing the expiration date of products before one consumes them improves safety
and quality of life. Also, you will never run out of anything when you need it at the last
moment.
3. Time: The amount of time saved in monitoring and the number of trips done otherwise
would be tremendous.
4. Money: The financial aspect is the best advantage. This technology could replace humans
who are in charge of monitoring and maintaining supplies.
2. Complexity: There are several opportunities for failure with complex systems. For
example, both you and your spouse may receive messages that the milk is over and both of
https://pythonschoolkvs.wordpress.com/ Page 5
you may end up buying the same. That leaves you with double the quantity required. Or there
is a software bug causing the printer to order ink multiple times when it requires a single
cartridge.
3. Privacy/Security: Privacy is a big issue with IoT. All the data must be encrypted so that
data about your financial status or how much milk you consume isn’t common knowledge at
the work place or with your friends.
4. Safety: There is a chance that the software can be hacked and your personal information
misused. The possibilities are endless. Your prescription being changed or your account
details being hacked could put you at risk. Hence, all the safety risks become the consumer’s
responsibility.
Medium
Wired Wireless
(Guided) (Unguided)
https://pythonschoolkvs.wordpress.com/ Page 6
fig: Optical Fiber Cable (Principle: Total Internal Reflection)
Types of server:
1. Dedicated Sever
2. Non-Dedicated Server
Dedicated Server: A dedicated server is a server whose only job is to help workstations
access data, software and hardware. It does not double up as a workstation.
https://pythonschoolkvs.wordpress.com/ Page 7
2.8 NETWORK DEVICES:
1. Modem
2. Hub
3. Switch
4. Gateway
5. Bridge
6. Router
7. Repeater
8. NIC (Network Interface Card)
1. Modem:
The full form of modem is Modulator and demodulator.
A modem is a device or program that enables a computer to transmit data over
telephone or cable lines.
A modem converts analog signal to digital signal and vice- versa.
Modem connects computer to internet.
There are two types of modem:
a. Internal Modem
b. External Modem
Telephone pole
Modem
2. Hub:
A network device that contains multiple ports.
Provides multiple connections.
When a packet arrives at one port, it is copied to the other ports so that all
segments of the LAN can see all packets.
Two types of hub :
a. Active Hub
b. Passive Hub
https://pythonschoolkvs.wordpress.com/ Page 8
Fig: Hub Fig. : Active and Passive Hub
3. Switch:
A switch is called smart hub.
Provides multiple connections
A device that filters and forwards packets between LAN segments.
HUB SWITCH
4. Gateway:
A gateway is a network point that acts as an entrance to another network.
Used to connect two dissimilar networks.
https://pythonschoolkvs.wordpress.com/ Page 9
WAN LAN
5. Bridge:
A device that connects two local-area networks (LANs), or two segments of the same
LAN that use the same protocol, such as Ethernet.
LAN-1
LAN-2
6. Router:
A router is a device that forwards data packets along networks. A router is connected
to at least two networks, commonly two LANs or WANs. Routers are located
at gateways, the places where two or more networks connect.
A router acts as a dispatcher, choosing the best path for information to travel so it's
received quickly.
https://pythonschoolkvs.wordpress.com/ Page 10
7. Repeater:
Network repeaters regenerate and amplify the weak signals to transmit the information
for long distance.
8. NIC (Network Interface Card): NIC card has a physical address of a system; this physical
address known as MAC address.
A MAC address is a 6- byte address with each byte separated by a colon. First 3-bytes have
Manufacturer id and last 3-bytes represent Card id.
10:BE:05:56:3F:CB
Manufacturer id Card id
https://pythonschoolkvs.wordpress.com/ Page 11
Information signal is known as baseband signal or modulating signal.
(Ai Amplitude of information signal)
Common form of carrier wave is sinusoidal. (Ac Amplitude of carrier wave)
Modulated wave Am = Ac + Ai
Broadcast Transmission: widely used for broadcasting on the long, medium and short
wave bands.
Air band Radio: It is used for ground to air radio communications as well as two way
radio links for ground staff as well.
Short range wireless links
https://pythonschoolkvs.wordpress.com/ Page 12
Advantages and Disadvantages of Amplitude Modulation (AM):
Advantages Disadvantages
It can be demodulated using a circuit which It is not efficient in terms of its use of
has a few components. bandwidth.
https://pythonschoolkvs.wordpress.com/ Page 13
Applications of Frequency Modulation (FM) :
Radar
Seismic prospecting
EEG ( ElectroEncephaloGraphy ) monitoring of new-born’s etc.
Broadcasting of FM radio.
It is also used in music synthesis, some systems that use video-transmission and also
for magnetic tape-recording systems.
Collision: Collision, in computer networking, is a condition that occurs when two or more
computers on a network try to transmit packets at the same time. The network detects the
collision of the two transmitted packets and discards them both.
https://pythonschoolkvs.wordpress.com/ Page 14
START
Assemble a frame
YES
Transmit RTS
NO
CTS
received?
YES
END
https://pythonschoolkvs.wordpress.com/ Page 15
Error Detecting Codes (Implemented either at Data link layer or Transport Layer of OSI
Model). Whenever a message is transmitted, it may get scrambled by noise or data may get
corrupted. To avoid this, we use error-detecting codes which are additional data added to a
given digital message to help us detect if any error has occurred during transmission of the
message.
Basic approach used for error detection is the use of redundancy bits, where additional bits
are added to facilitate detection of errors.
Some popular techniques for error detection are:
1. Simple Parity check
2. Two-dimensional Parity check
3. Checksum
4. Cyclic redundancy check
https://pythonschoolkvs.wordpress.com/ Page 17
4. Cyclic redundancy check (CRC)
Unlike checksum scheme, which is based on addition, CRC is based on binary
division.
In CRC, a sequence of redundant bits, called cyclic redundancy check bits, are
appended to the end of data unit so that the resulting data unit becomes exactly
divisible by a second, predetermined binary number.
At the destination, the incoming data unit is divided by the same number. If at this step
there is no remainder, the data unit is assumed to be correct and is therefore accepted.
A remainder indicates that the data unit has been damaged in transit and therefore must
be rejected.
Example :
https://pythonschoolkvs.wordpress.com/ Page 18
2.13 MAC Address : MAC stands for Media Access Control. It is a physical address of a
device. A MAC address is a 6- byte address with each byte separated by a colon. First 3-
bytes have Manufacturer id and last 3-bytes represent Card id.
10:BE:05:56:3F:CB
Manufacturer id Card id
2.14 Routing: Routing is the process of moving packets across a network from a source to
destination.
Functions of routing:
(i) Determine optimal routing path
(ii) Transfer the packets on a network
Routing protocols use metrics to evaluate what path will be the best for a packet to travel.
2.15 IP address:
Each computer has unique address over internet, is called IP address. An IP address is an
identifier for a computer or device on a TCP/IP network.
Two types:
I. IPv4 (32-bits or 4-bytes) : IPv4 provides the host-to-host communication
between systems in the internet. IPv4 addresses are canonically represented
in dot-decimal notation, which consists of four decimal numbers, each ranging
from 0 to 255, separated by dots, e.g., 192.168.1.1.
II. IPv6 (128-bits or 16-bytes)
A routing table contains the information to forward a packet along the best path toward its
destination. A router uses the routing table.
The routing table contains a list of specific routing destinations, and when the router receives
a packet of data, it references the routing table to know where to send that data. The routing
table may also contain information on how far each destination is from the router. In essence,
a routing table is a map for the router.
https://pythonschoolkvs.wordpress.com/ Page 19
There are two types of routing tables:
(i) Static tables: These are for static network devices. Static tables do not change unless a
network administrator manually changes them.
(ii) Dynamic tables: Network devices build and maintain their routing tables automatically
by using routing protocols to exchange information about the surrounding network topology.
Write the following command on command prompt to see the routing table:
route print
https://pythonschoolkvs.wordpress.com/ Page 20
2.17.1 Types of DNS servers:
Three types:
i. Root Server
ii. Primary Server
iii. Secondary Server
Root Server
Primary Server
sk.edu Server bk.edu Server Secondary Server abc.org Server xyz.org Server
(i) Root server : A root server is a server whose zone consists of the whole tree. A root server
usually does not store any information about domains but delegates its authority to other
servers.
(ii) Primary Server : A primary server is a server that stores a file about the zone for which
it is an authority. It is responsible for creating, maintaining and updating the zone file. It stores
the zone file on local disk. These are also called Top-Level-Domain servers.
(iii) Secondary Server: A secondary server is a server that transfers the complete information
about a zone from another servers (primary and secondary) and stores the file on local disk.
The secondary server neither creates nor update the zone files.
https://pythonschoolkvs.wordpress.com/ Page 21
i. Some popular generic domains:
ii. Country Domain: The country domain section uses two-character country abbreviations.
Some of country domains are:
in (India), us (United States), fr (France), uk (United Kingdom)
iii. Inverse Domain: The inverse domain is used to map an address to a name.
2.18 URL (Uniform Resource Locator): The URL is a unique identifier of any resource or
web page on the internet.
URL has four things:
i. Protocol
ii. Host Computer
iii. Port
iv. Path
Syntax:
protocol: // host : port / path
Example:
http://www.cbse.nic.in/newsite/circulars.html
https://pythonschoolkvs.wordpress.com/ Page 22
2.19 TCP (Transmission Control Protocol):
TCP is a connection oriented, reliable data transfer protocol.
Connection oriented transmission requires three phases:
o Connection establishment
o Data transfer
o Connection termination
2.19.1 Connection Establishment: TCP transmits data in full duplex mode. TCP uses three
way handshaking between sender and receiver for connection establishment. Firstly, each
party must initialize communication and get approved from the other party, before any data
is transferred.
https://pythonschoolkvs.wordpress.com/ Page 23
2.20 Congestion Control in Network: In this, we try to avoid traffic congestion.
2.20.1 Congestion: It may occur, if the load on the network is more than the capacity of the
network. It occurs due to queues in the routers and switches.
Congestion load > capacity
Where:
Load means no. of packets sent to network.
Capacity means no. of packets a network can handle.
2.20.2 Traffic Descriptors:
Max. Burst size (Max. length of time the traffic is generated at peak rates)
Data Rate
1. Constant Bit Rate: Not change in data rate with respect to time.
Data Rate
https://pythonschoolkvs.wordpress.com/ Page 24
2. Variable Bit Rate (VBR) : Data flow changes with time.
Data Rate
3. Bursty data : Data rate changes suddenly.
Data Rate
https://pythonschoolkvs.wordpress.com/ Page 25
I) Open Loop Congestion Control: Policies are used to prevent the congestion before it
happens.
Retransmission Policy: The sender retransmits a packet, if it feels that the packet it
has sent is lost or corrupted.
Window Policy: Selective reject window method is used. This method sends only the
lost or damaged packets.
Acknowledgement Policy: By sending fewer acknowledgements we can reduce load
on the network. To implement it, several approaches can be used:
Discarding Policy: A router may discard less sensitive packets when congestion is
likely to happen.
Admission Policy: first check the resource requirement of a flow before admitting it
to the network.
II) Closed Loop Congestion Control: Try to remove the congestion after it happens.
Backpressure: In which a congested node stops receiving data from the immediate
upstream node or nodes.
Choke Point: Packet sent by a node to the source to inform it of congestion.
Implicit Signaling: The source guesses that there is a congestion somewhere in the
network from other symptoms.
Explicit Signaling: The node that experiences congestion can explicitly send a signal
to the source or destination, the signal is included in the packets that carry data.
2.21 Protocol:
Introduced in 1993.
Technology used: Digital cellular, GSM (Global System for Mobiles) and GPRS
(General Packet Radio Service)
Data rate capacity – 64 Kbps
Services: Calling, SMS, Web browsing, E-mail
https://pythonschoolkvs.wordpress.com/ Page 26
3G : 3rd Generation mobile network
Wi-Fi: Stands for Wireless Fidelity. It is a facility allowing computers, smartphones, or other
devices to connect to the Internet or communicate with one another wirelessly within a
particular area.
a. traceroute: A traceroute (tracert) is a command which traces the path from one network
to another.
Syntax:
tracert hostname
where hostname is the name of the server connection you are testing.
Example:
tracert kvongcbrd.com
https://pythonschoolkvs.wordpress.com/ Page 27
b. ping : ping command to test the availability of a networking device on a network.
If you receive a reply then the device is working OK , if you don’t then the device is faulty,
disconnected, switched off, incorrectly configured.
Syntax:
ping IP address
Example:
ping 192.168.0.1
c. ipconfig : Displays all current TCP/IP network configuration values and refresh Dynamic
Host Configuration Protocol and Domain Name System settings.
Syntax:
ipconfig
Example:
ipconfig
https://pythonschoolkvs.wordpress.com/ Page 28
d. nslookup : The nslookup (which stands for name server lookup) command is a network
utility program used to obtain information about internet servers. It finds name server
information for domains by querying the Domain Name System.
Syntax:
nslookup domainname
Example:
nslookup www.kvsangathan.nic.in
e. whois : whois is a simple command-line utility that allows you to easily get information
about a registered domain. It automatically connect to the right WHOIS server, according to
the top-level domain name, and retrieve the WHOIS record of the domain. It supports both
generic domains and country code domains.
Syntax:
https://pythonschoolkvs.wordpress.com/ Page 29
whois domainname
Example:
whois amazon.in
Note: Run this command after nslookup or along with nslookup command.
f. speed-test : To test the internet speed using command prompt, firstly you need to install
the following using pip command.
speedtest-cli
Example:
https://pythonschoolkvs.wordpress.com/ Page 30
2.23 Application Layer:
The application layer contains a variety of protocols that are commonly needed by users. It
provides a user interface that enables users to access the network and various services.
2.23.1 HTTP (HyperText Transfer Protocol): It is a protocol used to transfer the hypertext
pages over internet.
HTTP is implemented in two program: Client program and Server program. Both the
programs executing on different end system, communicate to each other by exchanging
HTTP messages.
E-Mail is a method to send the messages in digital form. E-mail is a message that may
contain text, files, images, or other attachments sent through a network to a specified
individual or group of individuals.
SMTP
POP3/IMAP
https://pythonschoolkvs.wordpress.com/ Page 31
SMTP (Simple Mail Transfer Protocol) is a protocol which is used to transfer the e-mail from
sender side. This protocol is known as push protocol.
POP3 (Post Office Protocol version 3): This protocol is used to access e-mail from the server
to receiver. This protocol is known as pull protocol.
IMAP (Internet Message Access Protocol): It is a standard email protocol that stores email
messages on a mail server, but allows the end user to view and manipulate the messages as
though they were stored locally on the end user's computing device.
It is a variant of HTTP that adds a layer of security on the data in transit through a secure
socket layer (SSL).
HTTPS enables encrypted communication and secure connection between a remote user and
the primary web server.
https://pythonschoolkvs.wordpress.com/ Page 32
HTTPS encrypts every data packet in transition using SSL encryption technique to avoid
intermediary hackers and attackers to extract the content of the data.
Example:
https://pythonschoolkvs.wordpress.com/
2.25.1 Remote Desktop: Remote desktop is a program that allows a user to connect to a
computer in another location, see that computer's desktop and interact with it as if it were
local. Example: Team Viewer, Any desk, Virtual Network Computing, GoToMyPC etc.
2.25.2 Remote login: A login that allows a user’s computer to connect to a host computer via
a network and to interact with that host.
2.25.3 FTP (File Transfer Protocol): It is used to transfer files from one computer to another
computer.
2.25.4 SCP (Session Control Protocol): It is a session layer protocol. It creates multiple light-
duty connections from a single TCP connection. It uses Secure Shell (SSH) for data transfer.
2.25.5 SSH (Secure Shell): Secure Shell (SSH) is a cryptographic network protocol for
operating network services securely over an unsecured network. Secure Shell provides strong
authentication and encrypted data communications between two computers connecting over
an open network such as the internet.
2.25.6 VoIP (Voice over Internet Protocol): It is the phone service over the Internet.
2.25.7 NFC (Near Field Communication): NFC is a short-range high frequency wireless
communication technology that enables the exchange of data between devices over about a
10 cm distance.
https://pythonschoolkvs.wordpress.com/ Page 33
https://pythonschoolkvs.wordpress.com/
CLASS-XII
COMPUTER SCIENCE-PYTHON (083)
UNIT-III DATA MANAGEMENT-2
By: Vikash Kumar Yadav
PGT-Computer Science
K.V. No.-IV ONGC Vadodara
3.1 Django Introduction:
Django is a free and open source web application framework written in Python.
It is based on Model-View-Template (MVT) framework. Here Model means tables,
View means logic and Template means HTML files to display the contents interactive.
It is used for developing the web application.
Django provides the concept of ‘reusability’.
https://pythonschoolkvs.wordpress.com/ Page 1
Here Vehicle is the name of Project. A folder with the name Vehicle will be created in
D:\ WebApplications directory.
Vehicle
Vehicle manage.py
https://pythonschoolkvs.wordpress.com/ Page 2
3.3.2 Run the Django Server:
Now to start the Django server, Type following command in command prompt:
D:\WebApplications\Vehicle>python manage.py runserver
https://pythonschoolkvs.wordpress.com/ Page 3
3.3.3 Create an Application:
Now, open the command prompt. Go to the directory D:\WebApplications\Vehicle and
create the application under Vehicle Project. Here the application name is Car. To
create this application, type the following command :
After this, a folder will be created under Vehicle folder (Outer folder) and the structure
of directory will look like this:
Vehicle
__init__.py migrations
__init__.py
settings.py
admin.py
urls.py
apps.py
wsgi.py
models.py
tests.py
views.py
https://pythonschoolkvs.wordpress.com/ Page 4
3.3.4 Register the Application in Project:
Now register the created application Car under the project Vehicle. For this, we have
to open settings.py file under Vehicle folder.
In this web application we will perform the CRUD (Create, Read, Update, Delete )
operations.
We shall store the data of different types of cars and perform the CRUD operations
with the data stored in database.
To Store the data, we will use sqlite3 database system which is in-built in Django. So
no need to install it separately.
Open the file models.py under Car web application to create a model and its fields.
Models are considered as tables in MVT framework. An application may have multiple
models. Write the following code in models.py:
https://pythonschoolkvs.wordpress.com/ Page 5
Here, Meta class is simply an inner class. In Django, the use of Meta class is simply to
provide metadata to the ModelForm class.
Django provides the facility of forms. It means we need not create any HTML form for
table fields. Django denotes the table fields as a form. Now, create a file forms.py
under Car folder.
Now migrate the models in database. For this, we have to run the following command
in command prompt:
D:\WebApplications\Vehicle>python manage.py makemigrations
This command will create the model and make the changes if any.
Now run another command to migrate the created model. In command prompt window,
write the following command:
D:\WebApplications\Vehicle>python manage.py migrate
https://pythonschoolkvs.wordpress.com/ Page 6
Now the created model is stored in the file 0001_initial.py under the folder migration in Car
application.
A table named as ctable has been created in database. It has following fields:
(id, cbrand, cdom, cprice). id field is automatically created in Django, which has its
own system generated values.
Make the entry of created folder in settings.py file. The meaning of this step that we
are informing the project that there is an application with the name Car, whose all
.html pages are inside templates folder.
In our application, we will have index.html, edit.html and show.html files under
templates folder.
https://pythonschoolkvs.wordpress.com/ Page 7
HTML coding for index.html:
In this file we’ll create an HTML form to take the values from user.
(CREATE operation)
<html>
<head><title>Index Page</title></head>
<body>
<center><strong>
<h1>CAR DATA</h1>
</strong></center>
<center>
In above code, csrf_token is inbuilt feature of django application. csrf stands for Cross Site
Request Forgery. It provides easy-to-use protection against Cross Site Request Forgeries.
<html>
<head>
<title>Show Car Details</title>
</head>
<body>
<center><strong><u><h1>CAR DETAILS</h1></u></strong></center>
<center>
<table width=60% border=6">
<tr>
<th>Car Brand</th>
<th>Date of Manufacturing</th>
<th> Price</th>
https://pythonschoolkvs.wordpress.com/ Page 8
<th colspan="2">Action</th>
</tr>
https://pythonschoolkvs.wordpress.com/ Page 9
3.3.8 Write the logic in views.py:
Now, open views.py under the application Car.
views.py file will work as a controller. In this file we would write the logics in the form
of functions and call the views according to their actions. So, it is an important file.
https://pythonschoolkvs.wordpress.com/ Page 10
3.3.9 Write the logic in views.py
Open urls.py under Vehicle subfolder and refer the views. Write the following code
in urls.py file.
After execution of above command, the following address will appear on command
prompt:
http://127.0.0.1:8000/
Copy it and paste it into web browser. Press Enter. It will display the name of all urls.
Now write the address of the show page. Means, write the address given below:
http://127.0.0.1:8000/show
https://pythonschoolkvs.wordpress.com/ Page 11
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 12
OUTPUT-3 Records in the table after addition
https://pythonschoolkvs.wordpress.com/ Page 13
3.4 CSV and Flat Files:
CSV (Comma Separated Values). 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.
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:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
['2', 'Sujata', 'Science', '412']
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'])
https://pythonschoolkvs.wordpress.com/ Page 14
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
https://pythonschoolkvs.wordpress.com/ Page 15
Open urls.py, and write following code:
After successful execution of above, write the given address in web browser.
http://127.0.0.1:8000/csv
If the command successfully runs (without any error), then the MySQL connector is
successfully installed.
Now, open MySQL and check the current user, by typing the following command in
MySQL:
SELECT current_user( );
https://pythonschoolkvs.wordpress.com/ Page 16
Connect MySQL database with python. For this, open Python IDLE and write the
following code in python file.
CODE:
import mysql.connector
demodb=mysql.connector.connect(host="localhost",user="root", passwd="computer")
print(demodb)
If you get the following output, then the connection made successfully.
OUTPUT:
After making successful connection between python and MySQL, now create a
database in MySQL through python. For that, write the following code in python:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="computer")
democursor=demodb.cursor( )
democursor.execute("CREATE DATABASE EDUCATION")
https://pythonschoolkvs.wordpress.com/ Page 17
If you want to check the created database through python, write the following python
code to show the present databases in MySQL.
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="computer")
democursor=demodb.cursor()
democursor.execute("SHOW DATABASES")
for i in democursor:
print(i)
OUTPUT:
To verify the table created or not, write the following code in python:
import mysql.connector
https://pythonschoolkvs.wordpress.com/ Page 18
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor = demodb.cursor( )
democursor.execute ("show tables")
for i in democursor:
print(i)
OUTPUT:
OUTPUT:
https://pythonschoolkvs.wordpress.com/ Page 19
3.10 Update the record:
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
(i) Data Definition Language (DDL): It consist the commands to create objects such as
tables, views, indexes etc. in the database.
https://pythonschoolkvs.wordpress.com/ Page 20
(ii) Data Manipulation Language (DML): It is used for queries. It allows you to perform
data manipulation e.g. retrieval, insertion, deletion, modification of data stored in
database.
(iii) Transaction Control Language (TCL): This language allows you to manage and
control the transaction.
(iv) Data Control Language (DCL): This language is used to control data and access
to the databases. It is used for protecting the data from unauthorized access.
https://pythonschoolkvs.wordpress.com/ Page 21
Example: USE Bank;
DROPPING DATABASES: To remove the entire database we use the DROP DATABASE
statement.
Syntax: DROP DATABASE <database-name>;
Example: DROP DATABASE Bank;
Fig. : EMPLOYEE
The into clause specifies the target table and the value clause specifies the data to be
added to the new row of the table.
While inserting data into tables, following points should be taken care of:
Character data should be enclosed within single quotes.
NULL values are given as NULL, without any quotes.
If no data is available for all the columns then the column list must be included,
following the table name. Example: INSERT INTO EMPLOYEE(Ecode, Ename,
salary) VALUES(1001, ‘Amit’, 20000.00);
Table: EMPLOYEE
DROPPING A TABLE:
To remove the entire structure of the table completely, we use the DROP TABLE
command.
Syntax:
https://pythonschoolkvs.wordpress.com/ Page 23
DROP TABLE <table-name>;
Example:
DROP TABLE EMPLOYEE;
(i) SELECT Command:- A SELECT command retrieves information from the database.
(ii) INSERT Command:- This command is used to insert the data in table.
NOTE:- We have already discussed about this command.
(iii) DELETE Command:- It means delete the information from the table. This command is
used to remove the rows from the table.
Specific rows are deleted when you specify the WHERE clause.
All rows in the table are deleted if you omit the WHERE clause.
(i) SELECT:-
A SELECT command is used to retrieve information from a table.
If you want to select the all columns from a table, then we use the
asterisk(*) in SELECT clause.
Example: - SELECT * FROM EMPLOYEE;
To display specific columns of the table by specifying the column names,
separated by commas.
Example: - SELECT Ecode, Ename, salary
FROM EMPLOYEE;
(ii) FROM:-
A FROM clause, specifies the table name that contains the columns.
(iii) WHERE:-
A WHERE clause, specifies the condition.
https://pythonschoolkvs.wordpress.com/ Page 25
SOME IMPORTANAT POINTS:-
SQL statements are not case sensitive.
To end the SQL command, we write the semicolon(;) at the end of a line followed by
<ENTER>.
Selecting All Columns:- To select all the columns, we use asterisk (*) in SELECT
statement.
Example:- SELECT *
FROM EMPLOYEE;
Selecting Specific Columns:- To display the specific columns of the table, write
columns name, separated by commas.
Example:- SELECT Ecode, Ename, salary
FROM EMPLOYEE;
ALL keyword:-
SQL allows us to use the keyword ALL to specify explicitly that duplicates are not
removed.
Example: SELECT ALL Dept
FROM EMPLOYEE;
Arithmetic Operations:-
The SELECT clause may also contain arithmetic expressions involving the operators +, - ,
* and / operating on constants or attributes.
Example:- Find the new salary of every employee increased by 25%.
SELECT Ename,salary,salary*0.25
FROM EMPLOYEE;
COLUMN ALIAS:- You can change a column heading by using a column alias.
Example:- SELECT Ename as Name
https://pythonschoolkvs.wordpress.com/ Page 26
FROM EMPLOYEE;
Examples of Queries:-
1. List the name and department of those employees where department is production.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE Dept=’production’;
2. Find the name and salary of those employees whose salary is more than 20000.
Solution:- SELECT Ename, salary
FROM EMPLOYEE
WHERE salary > 20000;
5. Display the name and department of those employees who work in surat and salary is
greater than 25000.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE city=’surat’ and salary > 25000;
https://pythonschoolkvs.wordpress.com/ Page 27
8. List the name of employees who are not males.
Solution:- SELECT Ename, Sex
FROM EMPLOYEE
WHERE sex!=’M’;
(i) BETWEEN :-
Example:- Find the name and salary of those employees whose salary is between
35000 and 40000.
Solution:- SELECT Ename, salary
FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
Or we can write this query in another way:
SELECT Ename, salary
FROM EMPLOYEE
WHERE salary>35000 and salary<40000;
(ii) IN :-
Example:- Find the name of those employees who live in guwahati, surat or jaipur
city.
Solution:- SELECT Ename, city
FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
(iii) LIKE :-
% :- It represents any sequence of zero or more characters.
_ :- Represents any single character.
Example:- Display the name of those employees whose name starts with ‘M’.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;
Example:-Display the name of those employees whose department name ends with ‘a’.
https://pythonschoolkvs.wordpress.com/ Page 28
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Dept LIKE ‘%a’;
Example:- List the name of employees whose name having ‘e’ as the second character.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Ename LIKE ‘_e%’;
(iv) IS NULL :-
Aggregate functions are functions that take a collection of values as input and return a
single value. SQL offers five types of aggregate functions:-
https://pythonschoolkvs.wordpress.com/ Page 29
(i) Avg( ) :- To findout the average
(ii) Min( ) :- Minimum value
(iii) Max( ) :-Maximum value
(iv) Sum( ) :-To calculate the total
(v) Count( ) :- For counting
NOTE: - The input to sum ( ) and avg( ) must be a collection of numbers, but the other
functions can operate on non numeric data types e.g.string.
In some circumstance, we would like to apply the aggregate function not only to a single
set of tuples, but also to a group of sets of tuples. We specify this wish in SQL using the
group by clause.
The attributes given in the group by clause are used to form groups.
Dept Avg(salary)
Production 38000.00
Marketing 35410.00
RND 40016.66
Q.5 Find the total salary of those employees who work in Guwahati city.
Solution:- SELECT sum(salary)
https://pythonschoolkvs.wordpress.com/ Page 30
FROM EMPLOYEE
WHERE city=’Guwahati’;
Q.9 Show the name of each department and minimum salary where minimum salary
in the department is less than 8000.
Solution: SELECT Dept, min(salary)
FROM EMPLOYEE
group by Dept
HAVING min(salary) < 8000;
Note: HAVING clause is often used with GROUP BY clause to apply filter condition for a
group of rows.
Q.10 Find maximum salary of each department and display the name of that
department which has maximum salary more than 39000.
Solution: SELECT Dept, max(salary)
FROM EMPLOYEE
group by Dept
HAVING max(salary)>39000;
https://pythonschoolkvs.wordpress.com/ Page 31
https://pythonschoolkvs.wordpress.com/
CLASS-XII
COMPUTER SCIENCE-PYTHON (083)
UNIT-IV SOCIETY, LAWS AND ETHICS-2
By: Vikash Kumar Yadav
PGT-Computer Science
K.V. No.-IV ONGC Vadodara
4.1 Intellectual Property Rights: Intellectual property rights (IPR) is the term applied to the
legal protection afforded to innovative and creative materials. It allows owner of IPR to gain
from the use of the material and thereby to encourage innovation and creativity.
o Copyright law
o The law of confidence
o Patent law
o Design law
o Trademarks
o Copyright and computer programs
o Database copyright and the database right
o Criminal offences
4.2 Plagiarism: "The unauthorized use of someone’s ideas, thoughts, expressions and the
representation of them as one's own original work."
4.4 Digital License: A license is an agreement that allows someone to copy, use, or resell
the digital content. In digital rights management (DRM), acquiring a license to use protected
copyrighted electronic material is essential.
GPL : The GNU General Public License (GNU GPL or GPL) is a widely-used free
software license, which guarantees end users the freedom to run, study, share and
modify the software.
https://pythonschoolkvs.wordpress.com/ Page 1
Apache License: The Apache License is an open source softwarelicense released by
the Apache Software Foundation (ASF). ... The Apache License allows you to freely
use, modify, and distribute any Apache licensedproduct. However, while doing so,
you're required to follow the terms of the Apache License.
4.6 Open Data: Open data is data that anyone can access, use and share without any
copyright restrictions. Governments, businesses and individuals can use open data to bring
about social, economic and environmental benefits.
Open data must also be licensed to allow free usage and be available for commercial use. It
has the power to help improve services, grow economies and protect our planet.
Example:
• Government policies and implementation
• Money spent on government projects
• Surveys
https://pythonschoolkvs.wordpress.com/ Page 2
In India, there is a fundamental right to privacy under the Indian constitution, establishing
that “The right to privacy is protected as an intrinsic part of the right to life and personal
liberty”.
“Every individual in society irrespective of social class or economic status is entitled to the
intimacy and autonomy which privacy protects. The pursuit of happiness is founded upon
autonomy and dignity. Both are essential attributes of privacy which makes no distinction
between the birth marks of individuals.”
The Information Technology (Amendment) Act, 2008 made changes to the Information
Technology Act, 2000 and added the following two sections relating to Privacy:
4.8 Fraud:
• Fraud is intentional deception over internet to secure unfair or unlawful gain, or to
deprive a victim of a legal right.
• Fraud can violate civil law, a criminal law.
• It refers to dishonestly cheating someone.
4.9 Cyber Crime: Criminal activities carried out by means of computers or the Internet.
There are some examples of cybercrime:
(i) Phishing: Phishing is the fraudulent act of acquiring private and sensitive information
(username and password) of a person or company through e-mail, malicious links etc.
(ii) Illegal downloads: Illegal downloading is obtaining files that you do not have the right
to use from the Internet. Downloading of copyrighted files for which you do not have
permission or licensed, is called illegal downloads.
(iii) Child Pornography: Sexual exploitation of children (under the age of 18). Child
pornography is publishing and transmitting obscene material of children in electronic form.
Child pornography is most often made by taking pictures, audio and video recording.
Safeguards for children:
Never give address to people who you do not know.
Never publish your personal information publicly.
https://pythonschoolkvs.wordpress.com/ Page 3
Do not open suspicious emails.
Never visit porn, harmful websites.
Child pornography is a crime in India. Information Technology Act, 2000 & Indian Penal
Code, 1860 provides protection from child pornography. Child is the person who is below
the age of 18 years.
The newly passed Information Technology Bill is set to make it illegal to not only create and
transmit child pornography in any electronic form, but even to browse it.
The punishment for a first offence of publishing, creating, exchanging, downloading or
browsing any electronic depiction of children in “obscene or indecent or sexually explicit
manner” can attract five years in jail and a fine of Rs. 10 lakh.
(iv) Scams: A scam is a term used to describe any fraudulent business or scheme that takes
money or other goods from an unsuspecting person.
Types of scams:
• Phishing: fraudulent act of acquiring private and sensitive information
• Auction Fraud: someone may claim to be selling tickets for an upcoming concert that
really are not official tickets.
• Donation Scam: A person claiming they have or have a child or someone they know
with an illness and need financial assistance.
• Catfish: A person who creates a fake online profile with the intention of deceiving
someone.
• Cold call scam: Someone claiming to be from technical support from a computer
company, saying they have received information that your computer is infected with a
virus, or hacked. They offer to remotely connect to your computer and fix the problem.
• Chain main: Usually harmless, this scam is usually spread through e-mail and tells
people to forward the e-mail to all their friends to get money back from someone.
• Online survey scams: Online survey scams are survey sites that say they offer money or
gift vouchers to participants.
4.10 Cyber Forensics: Cyber forensics is a technique of digital forensic science for
investigation and analysis to collect evidence from a computer, mobile, internet or any
electronic device to present evidence in court of law, against any criminal activity.
https://pythonschoolkvs.wordpress.com/ Page 4
The Act provides legal framework for electronic governance by giving recognition
to electronic records and digital signatures.
Commission of cybercrime may be divided into three basic groups:
• Individual
• Organisation
• Society at Large
• Against Individual
o Harassment via Emails
o Cyber Stalking
o Dissemination of obscene material
o Defamation
o Hacking/Cracking Indecent Exposure
o Computer Vandalism
o Transmitting a Virus
o Network Trespassing
o Unauthorized Control over Computer System
o Hacking/Cracking
• Against Organisation
o Hacking & Cracking
o Possession of unauthorized Information
o Cyber- Terrorism against Government Organization
o Distribution of Pirated Software Etc
https://pythonschoolkvs.wordpress.com/ Page 6
(2) The subscriber or any person in charge of the computer resource shall, when called upon
by any agency which has been directed under sub-section (1), extend all facilities and
technical assistance to decrypt the information.
(3) The subscriber or any person who fails to assist the agency referred to in subsection shall
be punished with imprisonment for a term which may extend to seven years.
Punishment: Imprisonment for a term which may extend to seven years. The offense is
cognizable and non- bailable.
6. Protected System:
Section 70 of this Act provides that –
(1) The appropriate Government may, by notification in the Official Gazette, declare that any
computer, computer system or computer network to be a protected system.
(2) The appropriate Government may, by order in writing, authorize the persons who are
authorized to access protected systems notified under sub-section (1).
(3) Any person who secures access or attempts to secure access to a protected system in
contravention of the provision of this section shall be punished with imprisonment of either
description for a term which may extend to ten years and shall also be liable to fine.
Punishment: The imprisonment which may extend to ten years and fine.
7. Penalty for misrepresentation:
Section 71 provides that-
(1) Whoever makes any misrepresentation to, or suppresses any material fact from, the
Controller or the Certifying Authority for obtaining any license or Digital Signature
Certificate, as the case may be, shall be punished with imprisonment for a term which may
extend to two years, or which fine which may extend to one lakh rupees, or with both.
Punishment: Imprisonment which may extend to two years or fine may extend to one lakh
rupees or with both.
8. Penalty for breach of confidentiality and privacy:
Section 72 provides that- Save as otherwise provide in this Act or any other law for the time
being in force, any person who, in pursuance of any of the powers conferred under this Act,
rules or regulation made thereunder, has secured assess to any electronic record, book,
register, correspondence, information, document or other material without the consent of the
person concerned discloses such material to any other person shall be punished with
imprisonment for a term which may extend to two years, or with fine which may extend to
one lakh rupees, or with both.
Punishment: Term which may extend to two years or fine up to one lakh rupees or with both.
9. Penalty for publishing Digital Signature Certificate false in certain particulars:
Section 73 provides that –
(1) No person shall publish a Digital Signature Certificate or otherwise make it available to
any other person with the knowledge that-
https://pythonschoolkvs.wordpress.com/ Page 7
(a) The Certifying Authority listed in the certificate has not issued it; or
(b) The subscriber listed in the certificate has not accepted it; or
(c) The certificate has been revoked or suspended unless such publication is for the purpose
of verifying a digital signature created prior to such suspension or revocation.
(2) Any person who contravenes the provisions of sub-section (1) shall be punished with
imprisonment for a term which may extend to two years, or with fine which may extend to
one lakh rupees, or with both.
Punishment: Imprisonment of a term of which may extend to two Years or fine may extend
to 1 lakh rupees or with both.
10. Publication for fraudulent purpose:
Section 74 provides that- Whoever knowingly creates, publishes or otherwise makes
available a Digital Signature Certificate for any fraudulent or unlawful purpose.
Punishment: Imprisonment for a term up to two years or fine up to one lakh or both.
11. Act to apply for offense or contravention committed outside India:
Section 75 provides that-
(1) Subject to the provisions of sub-section (2), the provisions of this Act shall apply also to
any offense or contravention committed outside India by any person irrespective of his
nationality.
For the purposes of sub-section (1), this Act shall apply to an offense or
Contravention committed outside India by any person if the act or conduct constituting the
offense or contravention involves a computer, computer system or computer network located
in India.
12. Confiscation:
Section 76 provides that- Any computer, computer system, floppies, compact disks, tape
drives or any other accessories related thereto, in respect of which any provisions of this Act,
rules, orders or regulations made thereunder has been or is being contravened, shall be liable
to confiscation. :
Provided that where it is established to the satisfaction of the court adjudicating the
confiscation that the person in whose possession, power or control of any such computer,
computer system, floppies, compact disks, tape drives or any other accessories relating
thereto is found is not responsible for the contravention of the provisions of this Act, rules
orders or regulations made thereunder, the court may, instead of making an order for
confiscation of such computer, computer system, floppies, compact disks, tape drives or any
other accessories related thereto, make such other order authorized by this Act against the
person contravening of the provisions of this Act, rules, orders or regulations made thereunder
as it may think fit.
https://pythonschoolkvs.wordpress.com/ Page 8
13. Penalties or confiscation not to interfere with other punishments:
Section 77 provides that – No penalty imposed or confiscation made under this Act shall
prevent the imposition of any other punishment to which the person affected thereby is liable
under any other law for the time being in force.
Power to investigate offenses:
Section 78 provides that – Notwithstanding anything contained in the Code of Criminal
Procedure, 1973, a police officer not below the rank of Deputy Superintendent of Police shall
investigate any offense under this Act.
https://pythonschoolkvs.wordpress.com/ Page 10
Cartridges
Batteries
o Recycle:
Picking Shed : Sort the items manually. Remove batteries
Disassemble
First size reduction process
Second size reduction process
Over band magnet
Separation of metallic and non-metallic components
Water separation
4.14 Identity Theft: when someone uses your personal information to pretend to be you
without your knowledge and commit a crime or fraud.
How to prevent Identity Theft:
Never share your password or account number over email or message.
Do not follow links from e-mails when performing financial transaction.
Be aware of callers, pop-ups, websites or emails asking for personal information.
Use firewall and reliable anti-virus software.
Never share your personal information in public domain.
Regularly change the passwords of your account.
4.15 Unique Ids: Unique ids include fingerprints, hand geometry, earlobe geometry, retina
and iris patterns, voice waves, DNA, and signatures.
Iris Pattern: Iris recognition is an automated method of biometric identification that uses
mathematical pattern-recognition techniques on video images of one or both of the irises of
an individual's eyes, whose complex patterns are unique, stable, and can be seen from some
distance.
4.16 Biometrics: Electronic device which is used for authentication and identification of a
person using his/her biological and behavioural characteristics.
4.17 Gender and disability issues while teaching and using computers:
The low participation by women in computer science courses in secondary and sr. secondary
education is an important equity issue in science education. In addition to the increasingly
intense need for more highly skilled people in the IT sector, women are missing out on many
of today’s most attractive career opportunities. Equally importantly, the IT field is missing
out on the broader range of perspectives and talents that would result from significantly
increased participation by women.
To overcome this stereo type situation, the following points to be noted:
Transform pink software by creating gender neutral software that challenges and appeals to
a variety of students;
https://pythonschoolkvs.wordpress.com/ Page 11
Look to girls and women to fill the IT job shortage: encourage girls into computing by
using technology in a broad range of subjects to attract a more diverse group of
students.
Prepare tech-savvy teachers: empowered teachers will empower students.
Educate girls to be designers, not just users, ensuring they have opportunities to fully
explore the potential of technology.
Change the public face of computing so girls have a realistic image of computer
professionals, and understand the importance of communication and team work in this
field.
Create a family computer, placed where the entire family has access, and computer
activities are associated within a social context, and not equated to isolation.
Set a new standard for gender equity that seeks equal contributions to innovations in
technology and equal mastery of the analytical and computing skills required to make
these contributions.
https://pythonschoolkvs.wordpress.com/ Page 12