2nd PU Complete Python Notes
2nd PU Complete Python Notes
Introduction:
Sometimes while executing a Python program, the program does not execute at all or the program
executes but generates unexpected output or behaves abnormally. These occur when there are
syntax errors, runtime errors or logical errors in the code. In Python, exceptions are errors that get
triggered automatically. However, exceptions can be forcefully triggered and handled through
program code. In this chapter, we will learn about exception handling in Python programs.
Syntax Errors:
Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a program.
These errors are also known as parsing errors. On encountering a syntax error, the
interpreter does not execute the program unless we rectify the errors, save and rerun the
program.
When a syntax error is encountered while working in shell mode, Python displays the name
of the error and a small description about the error as shown in Figure
So, a syntax error is reported by the Python interpreter giving a brief explanation about the
error and a suggestion to rectify it.
Similarly, when a syntax error is encountered while running a program in script mode as
shown in Figure
Exceptions:
An exception is a Python object that represents an error. When an error occurs during the execution
of a program, an exception is said to have been raised.
Such an exception needs to be handled by the programmer so that the program does not terminate
abnormally.
Built-in Exceptions:
Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called
built-in exceptions.
Python’s standard library is an extensive collection of built-in exceptions that deals with the
commonly occurring errors (exceptions) by providing the standardized solutions for such errors.
A programmer can also create custom exceptions to suit one’s requirements. These are called
user-defined exceptions. We will learn how to handle exceptions in the next section.
Raising Exceptions:
Each time an error is detected in a program, the Python interpreter raises (throws) an
exception.
Exception Handling handlers are designed to execute when a specific exception is raised.
Programmers can also forcefully raise exceptions in a program using the raise and assert
statements.
Handling Exception:
Each and every exception has to be handled by the programmer to avoid the program from
crashing abruptly. This is done by writing additional code in a program to give proper messages
or instructions to the user on encountering an exception. This process is known as exception
handling.
Catching Exceptions:
An exception is said to be caught when a code that is designed to handle a particular exception is
executed. Exceptions, if any, are caught in the try block and handled in the except block.
While executing the program, if an exception is encountered, further execution of the code inside
the try block is stopped and the control is transferred to the except block. The syntax of try …
except clause is as follows:
try:
[ program statements where exceptions might occur]
except [exception-name]:
[ code for exception handling if the exception-name error is encountered]
try...except…else clause
We can put an optional else clause along with the try...except clause. An except block will be
executed only if some exception is raised in the try block. But if there is no error then none of the
except blocks will be executed. In this case, the statements inside the else clause will be executed.
Finally Clause
The try statement in Python can also have an optional finally clause.
The statements inside the finally block are always executed regardless of whether an
exception has occurred in the try block or not.
It is a common practice to use finally clause while working with files to ensure that the file
object is closed.
» Introduction to Files
» Types of Files
» Opening and Closing a Text File
» Writing to a Text File
» Reading from a Text File
» Setting Offsets in a File
» Creating and Traversing a Text File
» The Pickle Module
Introduction to Files:
We have so far created programs in Python that accept the input, manipulate it and display the
output. But that output is available only during execution of the program and input is to be entered
through the keyboard. This is because the variables used in a program have a lifetime that lasts till
the time the program is under execution.
Types of Files:
Computers store every file as a collection of 0s and 1s i.e., in binary form.
Therefore, every file is basically just a series of bytes stored one after the other. There are
mainly two types of data files — text file and binary file.
A text file consists of human readable characters, which can be opened by any text editor.
On the other hand, binary files are made up of non-human readable characters and symbols,
which require specific programs to access its contents.
Text file:
A text file can be understood as a sequence of characters consisting of alphabets, numbers
and other special symbols.
Files with extensions like .txt, .py, .csv, etc. are some examples of text files. When we open
a text file using a text editor (e.g., Notepad), we see several lines of text.
However, the file contents are not stored in such a way internally. Rather, they are stored
in sequence of bytes consisting of 0s and 1s.
In ASCII, UNICODE or any other encoding scheme, the value of each character of the text
file is stored as bytes.
Binary Files:
Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes
do not represent the ASCII values of characters.
Rather, they represent the actual content such as image, audio, video, compressed versions
of other files, executable files, etc.
These files are not human readable. Thus, trying to open a binary file using a text editor
will show some garbage values.
We need specific software to read or write the contents of a binary file.
Opening a file:
To open a file in Python, we use the open() function. The syntax of open() is as follows:
file_object= open(file_name, access_mode)
This function returns a file object called file handle which is stored in the variable file_object. We
can use this variable to transfer data to and from the file (read and write) by calling the functions
defined in the Python’s io module.
If the file does not exist, the above statement creates a new empty file and assigns it the name we
specify in the statement.
The file_object has certain attributes that tells us basic information about the file, such as:
<[Link]> returns true if the file is closed and false otherwise.
<[Link]> returns the access mode in which the file was opened.
<[Link]> returns the name of the file.
Closing a file:
Once we are done with the read/write operations on a file, it is a good practice to close the file.
Python provides a close() method to do so. While closing a file, the system frees the memory
allocated to it. The syntax of close() is:
file_object.close()
Here, file_object is the object that was returned while opening the file. Python makes sure that any
unwritten or unsaved data is flushed off (written) to the file before it is closed.
Hence, it is always advised to close the file once our work is done. Also, if the file object is re-
assigned to some other file, the previous file is automatically closed.
We can write a program to read the contents of a file. Before reading a file, we must make sure
that the file is opened in “r”, “r+”, “w+” or “a+” mode. There are three ways to read the contents
of a file:
The read() method This method is used to read a specified number of bytes of data from a data
file. The syntax of read() method is: file_object.read(n) Consider the following set of statements
to understand the usage of read() method:
>>>myobject=open("[Link]",'r')
>>> [Link](10) 'Hello ever'
>>> [Link]()
If no argument or a negative number is specified in read(), the entire file content is read. For
example,
>>> myobject=open("[Link]",'r')
>>> print([Link]())
Hello everyone
Writing multiline strings
This is the third line
>>> [Link]()
CHAPTER 03
STACK
A data structure defines a mechanism to store, organize and access data along with
operations (processing) that can be efficiently performed on the data. For example, string is a
data structure containing a sequence of elements where each element is a character. On the
other hand, list is a sequence data structure in which each element may be of different types.
We can apply different operations like reversal, slicing, counting of elements, etc. on list and
string. Hence, a data structure organizes multiple elements in a way so that certain operations
on each element as well as the collective data unit could be performed easily.
Stack and Queue are two other popular data structures used in programming. Although
not directly available in Python, it is important to learn these concepts as they are extensively
used in a number of programming languages. In this chapter, we will study about stack, its
implementation using Python as well as its applications.
STACK
We have seen piles of books in the library or stack
of plates at home. To put another book or another
plate in such a pile, we always place (add to the
pile) the object at the top only. Likewise, to remove
a book or a plate from such a pile, we always
remove (delete from the pile) the object from the
top only. This is because in a large pile, it is
inconvenient to add or remove an object from in
between or bottom. Such an arrangement of
elements in a linear order is called a stack. We
add new elements or remove existing elements
from the same end, commonly referred to as the top
of the stack. It thus follows the Last-In-First-out (LIFO) principle. That is, the element
which was inserted last (the most recent element) will be the first one to be taken out from
the stack.
APPLICATIONS OF STACK
Some of the applications of stack in real-life are:
• Pile of clothes in an almirah.
• Multiple chairs in a vertical pile.
• Bangles worn on wrist.
• Pile of boxes of eatables in pantry or on a kitchen shelf.
Some examples of application of stack in programming are as follows
When we need to reverse a string, the string is traversed from the last character till the
first character. i.e. characters are traversed in the reverse order of their appearance in
the string.
We use text/image editor for editing the text/image where we have options to
redo/undo the editing done. When we click on the redo /undo icon, the most recent
editing is redone/undone. In this scenario, the system uses a stack to keep track of
changes made.
While writing any arithmetic expression in a program, we may use parentheses to
order the evaluation of operators. While executing the program, the compiler checks
for matched parentheses i.e. each opening parenthesis should have a corresponding
closing parenthesis and the pairs of parentheses are properly nested. In case of
parentheses are mismatched, the compiler needs to throw an error. To handle matching
of parentheses, stack is used.
Operations on Stack
The end from which elements are added or deleted is called TOP of the stack.
Two fundamental operations performed on the stack are PUSH and POP.
PUSH and POP Operations
PUSH adds a new element at the TOP of the stack. We can add elements to a stack
until it is full.
A stack is full when no more elements can be added to it.
Trying to add an element to a full stack results in an exception called „overflow’.
POP operation is used to remove the top most element of the stack, that is, the
element at the TOP of the stack.
We can delete elements from a stack until it is empty. There is no element in stack.
Trying to delete an element from an empty stack results in an exception called
„underflow’.
A stack is used to insert and delete elements in LIFO order.
It is to be noted that we are using built-in methods append() and pop() of the list for
implementation of the stack.
Let us write a program to create a STACK (stack of glasses as given in Figure 3.2) in
which we will:
insert/delete elements (glasses)
Check if the STACK is empty (no glasses in the stack)
find the number of elements (glasses) in the STACK
read the value of the topmost element (number on the topmost glass) in the STACK
The program shall define the following functions to perform these operations:
• Let us create an empty stack named glassStack. We will do so by assigning an empty
list to the identifier named glassStack:
glassStack = list()
• A function named isEmpty to check whether the stack glassStack is empty or not.
Remember trying to remove an element from an empty stack would result in „underflow‟.
This function returns True if the stack is empty, else returns False
def isEmpty(glassStack):
if len(glassStack)==0:
return True
else:
return False
A function named opPush to insert (PUSH) a new element in stack. This function has two
parameters - the name of the stack in which the element is to be inserted (glassStack) and the
element that needs to be inserted.
We know that insertion of an element is always done at the TOP of the stack. Hence, we
shall use the built-in method append() of list to add an element to the stack that always adds
at the end of the list. As there is no limit on the size of list in Python, the implemented stack
will never be full unless there is no more space available in memory. Hence, we will never
face „overflow‟ (no space for new element) condition for stack.
def opPush(glassStack,element):
[Link](element)
• A function named size to read the number of elements in the glassStack. We will use the
len() function of list in Python to find the number of elements in the glassStack.
def size(glassStack):
return len(glassStack)
• A function named top to read the most recent element(TOP) in the glassStack.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x =len(glassStack)
element=glassStack[x-1]
return element
• A function named opPop to delete the topmost element from the stack. It takes one
parameter - the name of the stack (glassStack) from which element is to be deleted and
returns the value of the deleted element. The function first checks whether the stack is empty
or not. If it is not empty, it removes the topmost element from it. We shall use the builtin
method pop() of Python list that removes the element from the end of the list.
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return([Link]())
A function named display to show the contents of the stack.
def display(glassStack):
x=len(glassStack)
print("Current elements in the stack are: ")
for i in range(x-1,-1,-1):
print(glassStack[i])
Once we define the above functions we can use the following Python code to
implement a stack of glasses. glassStack=list()
# create empty stack
element='glass1' #add elements to stack
print("Pushing element ",element)
opPush(glassStack,element)
element='glass2'
print("Pushing element ",element)
opPush(glassStack,element)
appropriate action is taken as detailed in the algorithm. When each character in the
given infix expression has been processed, the string will contain the equivalent
postfix expression.
Example
The step-by-step process of evaluation of the postfix expression 7 8 2 * 4 / + using
Algorithm
Operations on Queue
1. ENQUEUE: is used to insert a new element to the queue at the rear end.
2. DEQUEUE: is used to remove one element at a time from the front of the queue.
3. IS EMPTY : used to check whether the queue has any element or not, so as to avoid
Underflow exception while performing dequeue operation.
4. PEEK : used to view elements at the front of the queue, without removing it from the queue
5. IS FULL : used to check whether any more elements can be added to the queue or not, to
avoid Overflow exceptions while performing enqueue operation.
Implementation of Queue using Python
For creating a queue structure in the program, following functions need to be defined:
• Let’s create a queue named myQueue. We can create it by assigning an empty list.
myQueue = list()
• A function (enqueue) to insert a new element at the end of queue. The function has two
parameters - name of the queue and element which is to be inserted in the queue.
def enqueue(myQueue, element):
[Link](element)
Note: append() function always adds an element at the end of the list, hence Rear of queue.
• We don’t need to implement Is Full, as Python being a dynamic language, does not ask for
the creation of list having fixed size. Hence, we will never encounter a situation when the queue is
full.
• A function (isEmpty) to check, if the queue has an element or not? This can be done by
checking the length of the queue. The function has a parameter -- name of the queue and returns True
if the queue is empty False otherwise.
def isEmpty(myQueue):
if len(myQueue)==0:
return True
else:
return False
• A function (dequeue) to delete an element from the front of the queue. It has one parameter - name
of the queue and returns the deleted element. The function first checks if the queue is empty or not,
for successful deletion.
def dequeue(myQueue):
if not (isEmpty(myQueue)):
return [Link](0)
else :
print(“Queue is empty”)
Note: The pop() function with index[0] will delete the element from the beginning of the list, hence
Front of queue.
• A function (size) to get the number of elements in the queue. We can use the len() function of
Python’s list to find the number of elements in the queue. The function has one parameter - name of
the queue and returns the number of elements in the queue.
def size(myQueue):
return len(myQueue)
• A function (peek) to simply read, but not to delete, the element at the front end of the queue. For
this, we can read the element at index[0] of the queue. The function has one parameter - name of the
queue and returns the value of element at Front if queue is not empty, None otherwise.
def peek(myQueue):
if isEmpty(myQueue):
print('Queue is empty')
return None
else:
return myQueue[0]
Let us consider the example of a queue that people form while waiting at a bank cash counter.
Usually, following are the events that occur in queue:
• Two friends come together and go to the cash counter, i.e. they form a queue - enqueue operation is
performed two times.
• As soon as the person at the front is serviced, he will be removed from the queue - thus dequeue
operation is performed. Cashier calls Next to serve the next person who is now at the front of the
queue.
• Cashier wants to know the length of the queue - size of the queue is checked.
• Meanwhile, a few more people walk in the bank, and three of them join the queue at the cash
counter, i.e. enqueue happens 3 times.
• Another person gets served and leaves the counter, i.e. dequeue is performed. Cashier calls Next to
serve another person.
• The Next three people get served one after another, i.e. dequeue is performed thrice.
• Cashier calls Next and realises that there are no more people to be served - underflow situation
happens.
Now, let us write the code for the above scenario of the bank.
Program
myQueue = list() # each person to be assigned a code as P1, P2, P3,...
element = input("enter person’s code to enter in queue :”)
enqueue(myQueue,element)
element = input("enter person’s code for insertion in queue :")
enqueue(myQueue,element)
print("person removed from queue is:", dequeue(myQueue))
print(“Number of people in the queue is :”,size(myQueue))
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
element = input("enter person’s code to enter in queue :")
enqueue(myQueue,element)
print("Now we are going to remove remaining people from the queue")
while not isEmpty(myQueue):
print("person removed from queue is ",
dequeue(myQueue))
Output
enter person’s code to enter in queue :P1
enter person’s code to enter in queue :P2
person removed from the queue is :p1
number of people in the queue is :1
enter person’s code to enter in queue :P3
enter person’s code to enter in queue :P4
enter person’s code to enter in queue :P5
Now we are going to remove remaining people from the queue
person removed from the queue is :p2
person removed from the queue is :p3
person removed from the queue is :p4
person removed from the queue is :p5
Queue is empty
Introduction to Deque
Deque (pronounced as “deck”) is an arrangement in which addition and removal of element(s) can
happen from any end, i.e. head/front or tail/rear.
This data structure does not apply any restriction on the side from which addition/removal of
elements should happen, so it can be used to implement stack or queue in the program.
It is also known as Double ended queue, because it permits insertion, deletion operations from any
end.
Basic deque structure displaying head and tail to implement stack or queue
Applications of Deque
At a train ticket purchasing counter, a normal queue of people is formed for purchasing a
ticket. A person at the front purchased the ticket and left the counter. After a while they return
back to the counter to ask something. As they have already purchased a ticket, they may have
the privilege to join the queue from the front.
• Vehicles in a highway toll tax booth are served following the principle of queue. There are
multiple queues if there are parallel booths at the toll gate. In case all vehicles of a booth are
served then vehicles from the other booth(s) are asked to form a queue in front of the vacant
booth. So, vehicles at the end of those queues will leave (removed from the end from where
queue was joined) current booth and join queue at the vacant booth.
Following are some examples where data structure deque maybe applied in computer science:
• To maintain browser history (URL), usually a stack is used, because once a tab is closed and if you
press ctrl+shift+T, the most recently closed URL is opened first. As the number of URLs which can
be stored in history is fixed, so when this list of URLs becomes large, URLs from the end of the list
(i.e. which were least visited) gets deleted.
• Same happens for providing the Do and Undo option in any text editor.
• To check whether a given string is palindrome or not? Process string left to right (character wise)
and insert it in deque from tail/rear like a normal queue. Once the entire string is processed (i.e.
inserted in deque) we will take out (delete) a character from both the ends and match them till there is
no character left or only one character left in deque. In either case, string is palindrome.
Operations on Deque
INSERTFRONT: This operation is used to insert a new element at the front of the deque.
INSERTREAR: This operation is the same as a normal queue, i.e. insert a new element at the
rear of the deque.
DELETIONFRONT: This operation is the same as normal queue, i.e. to remove an element
from the front of the deque.
DELETIONREAR: This operation is used to remove one element at a time from the rear of
the deque.
To perform above operations efficiently on a deque, we will need all supporting operations
used in normal queue viz Is Empty, Peek, Size.
Let’s understand how these operations work for checking whether a string is palindrome or
not, using a deque through the following algorithm.
ALGORITHM
• A function insertRear(), to insert an element at the rear of deque. It’s implementation will be
the same as enqueue() of normal queue requiring two parameters same as insertFront().
• A function isEmpty(), to check the presence of element(s) in deque will be the same as the
function, with the same name, defined for normal queue.
• A function deletionRear(), to delete an element from the rear of the deque. It only requires the
name of deque and returns the deleted element. We will use pop() without parameter(s) to
delete the last element of the deque.
def deletionRear(myDeque):
if not (isEmpty()):
return [Link]() # removing data from end of list
else :
print(“Deque empty”)
• A function deletionFront(), to delete an element from the front of deque. It’s implementation
will be the same as dequeue() of normal queue.
• A function getFront(), to read value from the front of deque, without removing it from the
queue when the queue is not empty. It accepts the name of deque as parameter and returns a
copy of value.
def getFront(mydeque):
if not (isEmpty()):
return mydeque[0]
else :
print(“ Queue empty”)
• A function getRear(), to read value from the rear of the deque, without removing it from the
deque. The function accepts deque as argument and returns a copy of value, when the queue is
not empty.
def getRear(mydeque):
if not (isempty()):
return mydeque[len(mydeque)-1]
else : print(“ Deque empty”)
Let us write a main(), function to invoke various Deque functions :
In this Chapter
» Introduction
» Bubble Sort
» Selection Sort
» Insertion Sort
» Time Complexity of Algorithms
In this chapter, we will learn about three sorting methods and implement
them using Python.
1)Bubble sort
2)Selection sort
3)Insertion sort
Algorithm
Shows the steps followed for the bubble sort that takes numList as a list of
n elements, and sorts the list in ascending order:
Algorithm Bubble Sort
BUBBLESORT( numList, n)
Step 1: SET i = 0
Step 2: WHILE i< n REPEAT STEPS 3 to 8
Step 3: SET j = 0
Step 4: WHILE j< n-i-1,REPEAT STEPS 5 to 7
Step 5: IF numList[j] > numList[j+1] THEN
Step 6: swap(numList[j],numList[j+1])
Step 7: SET j=j+1
Step 8: SET i=i+1
Program : Implementation of bubble sort using Python.
def bubble_Sort(list1):
n = len(list1)
for i in range(n): # Number of passes
for j in range(0, n-i-1):
# size -i-1 because last i elements are already sorted
#in previous passes
if list1[j] > list1[j+1] :
# Swap element at jth position with (j+1)th position
list1[j], list1[j+1] = list1[j+1], list1[j]
numList = [8, 7, 13, 1, -9, 4]
bubble_Sort(numList)
print (“The sorted list is :”)
for i in range(len(numList)):
print (numList[i], end=" ")
Output:
The sorted list is :
-9 1 4 7 8 13
Selection Sort: Selection sort is another sorting technique. To sort a list having n
elements, the selection sort makes (n-1) number of passes through the list.
The list is considered to be divided into two lists –
1. Left list (containing the sorted elements)
2. Right list( containing the unsorted elements)
Algorithm : Selection Sort
SELECTIONSORT( numList, n)
Step 1: SET i=0
Step 2: WHILE i< n REPEAT STEPS 3 to 11
Step 3: SET min = i, flag = 0
Step 4: SET j= i+1
Step 5: WHILE j< numList[min] THEN
Step 7: min = j
Step 8: flag = 1
Step 9: IF flag = 1 THEN
Step 10: swap(numList[i],numList[min])
Step 11: SET i=i+1
Insertion Sort:
Insertion sort is another sorting algorithm that can arrange elements of a given
list in ascending or descending order.
Algorithm :
Insertion Sort INSERTIONSORT( numList, n)
Step 1: SET i=1
Step 2: WHILE i< n REPEAT
STEPS 3 to 9 Step 3: temp = numList[i]
Step 4: SET j = i-1
Step 5: WHILE j> = 0 and numList[j]>temp,REPEAT STEPS 6 to 7
Step 6: numList[j+1] = numList[j] Step 7: SET j=j-1
Step 8: numList[j+1] = temp #insert temp at position j
Step 9: set i=i+1
Program
Implementation of insertion sort using Python.
def insertion_Sort(list3):
n= len(list3)
for i in range(n): # Traverse through all elements
temp = list3[i]
j = i-1
while j >=0 and temp< list3[j] :
list3[j+1] = list3[j]
j = j-1
list3[j+1] = temp
numList = [8, 7, 13, 1, -9, 4]
insertion_Sort(numList)
print (“The sorted list is :”)
for i in range(len(numList)):
print (numList[i], end=" ")
Output:
The sorted list is :
-9 1 4 7 8 13
****************************************************************
In this Chapter
» Introduction
» Linear Search
» Binary Search
» Search by Hashing
Linear Search
A linear search (often called a sequential search) is performed by inspecting each
item in a list one by one from one end to the other to find a match for what you
are searching for.
COLLISION
In this collision two or more elements cannot be in the same position in
the list. This situation is called collision in hashing
We must have a mechanism for placing the other items with the same
hash value in the hash table. This process is called collision resolution.
Chapter 7
In this chapter:
» Introduction to Data
» Data Collection
» Data Storage
» Data Processing
» Statistical Techniques for Data Processing
Introduction to Data:
Many a time, people take decisions based on certain data or information. For example, while
choosing a college for getting admission, one looks at placement data of previous years of that
college, educational qualification and experience of the faculty members, laboratory and hostel
facilities, fees, etc.
The following list contains some examples of data that we often come across.
• Name, age, gender, contact details, etc., of a person
• Transactions data generated through banking, ticketing, shopping, etc. whether
online or offline
• Images, graphics, animations, audio, video
• Documents and web pages
• Online posts, comments and messages
• Signals generated by sensors
• Satellite data including meteorological data, communication data, earth observation
data, etc.
Importance of Data:
Besides business, following are some other scenarios where data are also stored and analysed for
making decisions:
• The electronic voting machines are used for recording the votes cast. Subsequently, the voting
data from all the machines are accumulated to declare election results in a short time as compared
to manual counting of ballot papers.
• Scientists record data while doing experiments to calculate and compare results.
• Pharmaceutical companies record data while trying out a new medicine to see its effectiveness.
• Libraries maintain data about books in the library and the membership of the library.
• The search engines give us results after analysing large volume of data available on the websites
across World Wide Web (www).
• Weather alerts are generated by analysing data received from various satellites.
Types of Data:
As data come from different sources, they can be in different formats. For example, an image is a
collection of pixels; a video is made up of frames; a fee slip is made up of few numeric and non-
numeric entries; and messages/chats are made up of texts, icons (emoticons) and images/videos.
Two broad categories in which data can be classified on the basis of their format are:
Structured Data:
Data which is organised and can be recorded in a well defined format is called structured data.
Structured data is usually stored in computer in a tabular (in rows and columns) format where each
column represents different data for a particular parameter called attribute/ characteristic/variable
and each row represents data of an observation for different attributes.
Unstructured Data:
A newspaper contains various types of news items which are also called data. But there is no fixed
pattern that a newspaper follows in placing news articles. One day there might be three images of
different sizes on a page along with five news items and one or more advertisements.
Data Collection:
For processing data, we need to collect or gather data first. We can then store the data in a file or
database for later use. Data collection here means identifying already available data or collecting
from the appropriate sources. Suppose there are three different scenarios where sales data in a
grocery store are available:
Sales data are available with the shopkeeper in a diary or register. In this case we should
enter the data in a digital format for example, in a spreadsheet.
Data are already available in a digital format, say in a CSV (comma separated values) file.
The shopkeeper has so far not recorded any data in either form but wants to get a software
developed for maintaining sales data and accounts.
Data Storage:
Once we gather data and process them to get results, we may not then simply discard the
data. Rather, we would like to store them for future use as well.
Data storage is the process of storing data on storage devices so that data can be retrieved
later.
Now a days large volume of data are being generated at a very high rate. As a result, data
storage has become a challenging task.
However, the decrease in the cost of digital storage devices has helped in simplifying this
task.
There are numerous digital storage devices available in the market like, Hard Disk Drive
(HDD), Solid State Drive (SSD), CD/DVD, Tape Drive, Pen Drive, Memory Card, etc.
Data Processing:
We are interested in understanding data as they hold valuable facts and information that can
be useful in our decision making process. However, by looking at the vast or large amount of
data, one cannot arrive at a conclusion. Rather, data need to be processed to get results and
after analysing those results, we make conclusions or decisions.
Mean:
Mean is simply the average of numeric values of an attribute. Mean is also called average. Suppose
there are data on weight of 40 students in a class. Instead of looking at each of the data values, we
can calculate the average to get an idea about the average weight of students in that class.
Median:
Median is also computed for a single attribute/variable at a time. When all the values are sorted in
ascending or descending order, the middle value is called the Median. When there are odd number
of values, then median is the value at the middle position. If the list has even number of values,
then median is the average of the two middle values. Median represents the central value at which
the given data is equally divided into two parts.
Mode:
Value that appears most number of times in the given data of an attribute/variable is called Mode.
It is computed on the basis of frequency of occurrence of distinct values in the given data. A data
set has no mode if each value occurs only once. There may be multiple modes in the data if more
than one values have same highest frequency. Mode can be found for numeric as well as non-
numeric data.
Measures of Variability:
Range:
It is the difference between maximum and minimum values of the data (the largest value minus
the smallest value). Range can be calculated only for numerical data. It is a measure of dispersion
and tells about coverage/spread of data values.
Standard deviation:
Standard deviation refers to differences within the group or set of data of a variable. Like Range,
it also measures the spread of data.
However, unlike Range which only uses two extreme values in the data, calculation of standard
deviation considers all the given data. It is calculated as the positive square root of the average of
squared difference of each value from the mean value of data.
Given n values x1, x2, x3,...xn, and their mean x, the standard deviation, represented as σ (greek
letter sigma) is computed as
Chapter 8
In this chapter:
Introduction
File System
Database Management System
Rational Data Model
Keys in a Relational Database
Introduction:
Following are some of the limitations of manual record keeping in this example:
1) Entry of student details (Roll number and name) in the new attendance register when the
student is promoted to the next class.
2) Writing student details on each month’s attendance page where inconsistency may happen
due to incorrectly written names, skipped student records, etc.
3) Loss of data in case attendance register is lost or damaged.
4) Erroneous calculation while consolidating attendance record manually.
To overcome the hassles faced in manual record keeping, it is desirable to store attendance
record and student details on separate data files on a computerized system, so that office staff
and teachers can:
1) Simply copy the student details to the new attendance file from the old attendance file when
students are promoted to next class.
2) Find any data about student or guardian.
3) Add more details to existing data whenever a new student joins the school.
4) Modify stored data like details of student or guardian whenever required.
5) Remove/delete data whenever a student leaves the school.
File System:
A file can be understood as a container to store data in a computer. Files can be stored on the
storage device of a computer system. Contents of a file can be texts, computer program code,
comma separated values (CSV), etc. Likewise, pictures, audios/videos, web pages are also files.
Continuing the example of attendance at school, we need to store data about students and
attendance in two separate files. The below Table shows the contents of STUDENT file which
has six columns, as detailed below:
RollNumber – Roll number of the student
SName – Name of the student
SDateofBirth – Date of birth of the student
GName – Name of the guardian
GPhone – Phone number of the student guardian
GAddress – Address of the guardian of the student
Limitations of a File System:
(A) Difficulty in Access
Files themselves do not provide any mechanism to retrieve data. Data maintained in a
file system are accessed through application programs.
(B) Data Redundancy
Redundancy means same data are duplicated in different places (files). In our example,
student names are maintained in both the files.
(C) Data Inconsistency Data inconsistency occurs when same data maintained in different
places do not match. If a student wants to get changed the spelling of her name, it
needs to be changed in SName column in both the files.
(D) Data Isolation
This is because data mapping is not supported in file system. In a more complex system
where data files are generated by different person at different times, files being created
in isolation may be of different formats.
(E) Data Dependence Data are stored in a specific format or structure in a file. If the
structure or
format itself is changed, all the existing application programs accessing that file also
need to be changed. Otherwise, the programs may not work correctly. This is data
dependency.
(F) Controlled Data Sharing
There can be different category of users like teacher, office staff and parents. Ideally, not
every user should be able to access all the data.
Primary Key
Out of one or more candidate keys, the attribute chosen by the database
designer to uniquely identify the tuples in a relation is called the primary key of that relation.
The remaining attributes in the list of candidate keys are called the alternate keys.
Foreign Key
A foreign key is used to represent the relationship between two relations. A
foreign key is an attribute whose value is derived from the primary key of another relation. This
means that any attribute of a relation (referencing), which is used to refer contents from
another (referenced) relation, becomes foreign key if it refers to the primary key of referenced
relation.
UNIT III - SQL & MYSQL NOTES
MYSQL
It is freely available open source Relational Database Management System (RDBMS) that uses Structured Query
Language(SQL). In MySQL database , information is stored in Tables. A single MySQL database can contain many
tables at once and store thousands of individual records.
SQL (Structured Query Language)
SQL is a language that enables you to create and operate on relational databases, which are sets of related
information stored in tables.
A data model refers to a set of concepts to describe the structure of a database, and certain constraints (restrictions)
that the database should obey. The four data model that are used for database management are :
1. Relational data model : In this data model, the data is organized into tables (i.e. rows and columns). These
tables are called relations.
2. Hierarchical data model 3. Network data model 4. Object Oriented data model
7. Candidate Key : All attribute combinations inside a relation that can serve as primary key are candidate keys as
these are candidates for primary key position.
8. Alternate Key : A candidate key that is not primary key, is called an alternate key.
9. Foreign Key : A non-key attribute, whose values are derived from the primary key of some other table, is
known as foreign key in its current table.
REFERENTIAL INTEGRITY
- A referential integrity is a system of rules that a DBMS uses to ensure that relationships between records in
related tables are valid, and that users don’t accidentally delete or change related data. This integrity is
ensured by foreign key.
MySQL ELEMENTS
LITERALS
It refer to a fixed data value. This fixed data value may be of character type or numeric type. For example,
‘replay’ , ‘Raj’, ‘8’ , ‘306’ are all character literals.
Numbers not enclosed in quotation marks are numeric literals. E.g. 22 , 18 , 1997 are all numeric literals.
Numeric literals can either be integer literals i.e., without any decimal or be real literals i.e. with a decimal point
e.g. 17 is an integer literal but 17.0 and 17.5 are real literals.
DATA TYPES
Data types are means to identify the type of data and associated operations for handling it. MySQL data
types are divided into three categories:
Numeric
Date and time
String types
DATABASE COMMNADS
OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);
In order to insert another row in EMPLOYEE table , we write again INSERT command :
INSERT INTO employee
VALUES(1002 , ‘Akash’ , ‘M’ , ‘A1’ , 35000);
- To insert value NULL in a specific column, we can type NULL without quotes and NULL will be inserted in that
column. E.g. in order to insert NULL value in ENAME column of above table, we write INSERT command as :
e.g.
In order to retrieve everything from Employee table, we write SELECT command as :
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965
e.g. to display ECODE, ENAME and GRADE of those employees whose salary is between 40000 and 50000,
command is:
SELECT ECODE , ENAME ,GRADE
FROM EMPLOYEE
WHERE GROSS BETWEEN 40000 AND 50000 ;
Output will be :
- The NOT IN operator finds rows that do not match in the list. E.g.
SELECT * FROM EMPLOYEE
WHERE GRADE NOT IN (‘A1’ , ‘A2’);
Output will be :
e.g. to display names of employee whose name starts with R in EMPLOYEE table, the command is :
SELECT ENAME
FROM EMPLOYEE
WHERE ENAME LIKE ‘R%’ ;
Output will be :
ENAME
Ravi
Ruby
Output will be :
Output will be :
e.g. to display the details of employees in EMPLOYEE table in alphabetical order, we use command :
SELECT *
FROM EMPLOYEE
ORDER BY ENAME ;
Output will be :
ECODE ENAME GENDER GRADE GROSS
1002 Akash M A1 35000
1004 Neela F B2 38965
1009 Neema F A2 52000
1001 Ravi M E4 50000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
e.g. display list of employee in descending alphabetical order whose salary is greater than 40000.
SELECT ENAME
FROM EMPLOYEE
WHERE GROSS > 40000
ORDER BY ENAME desc ;
Output will be :
ENAME
Ravi
Ruby
Neema
e.g. to change the salary of employee of those in EMPLOYEE table having employee code 1009 to 55000.
UPDATE EMPLOYEE
SET GROSS = 55000
WHERE ECODE = 1009 ;
UPDATING MORE THAN ONE COLUMNS
e.g. to update the salary to 58000 and grade to B2 for those employee whose employee code is 1001.
UPDATE EMPLOYEE
SET GROSS = 58000, GRADE=’B2’
WHERE ECODE = 1009 ;
OTHER EXAMPLES
e.g.1. Increase the salary of each employee by 1000 in the EMPLOYEE table.
UPDATE EMPLOYEE
SET GROSS = GROSS +100 ;
e.g.2. Double the salary of employees having grade as ‘A1’ or ‘A2’ .
UPDATE EMPLOYEE
SET GROSS = GROSS * 2 ;
WHERE GRADE=’A1’ OR GRADE=’A2’ ;
e.g.3. Change the grade to ‘A2’ for those employees whose employee code is 1004 and name is Neela.
UPDATE EMPLOYEE
SET GRADE=’A2’
WHERE ECODE=1004 AND GRADE=’NEELA’ ;
So if we do not specify any condition with WHERE clause, then all the rows of the table will be deleted. Thus
above line will delete all rows from employee table.
DROPPING TABLES
The DROP TABLE command lets you drop a table from the database. The syntax of DROP TABLE command is :
DROP TABLE <tablename> ;
e.g. to drop a table employee, we need to write :
DROP TABLE employee ;
Once this command is given, the table name is no longer recognized and no more commands can be given on that table.
After this command is executed, all the data in the table along with table structure will be deleted.
To add a column to a table, ALTER TABLE command can be used as per following syntax:
However if you specify NOT NULL constraint while adding a new column, MySQL adds the new column with the
default value of that datatype e.g. for INT type it will add 0 , for CHAR types, it will add a space, and so on.
e.g. Given a table namely Testt with the following data in it.
Col1 Col2
1 A
2 G
Now following commands are given for the table. Predict the table contents after each of the following statements:
(i) ALTER TABLE testt ADD col3 INT ;
(ii) ALTER TABLE testt ADD col4 INT NOT NULL ;
(iii) ALTER TABLE testt ADD col5 CHAR(3) NOT NULL ;
(iv) ALTER TABLE testt ADD col6 VARCHAR(3);
MODIFYING COLUMNS
Column name and data type of column can be changed as per following syntax :
DELETING COLUMNS
To delete a column from a table, the ALTER TABLE command takes the following form :
TO ADD PRIMARY KEY CONSTRAINT
ALTER TABLE <table name>
ADD PRIMARY KEY (Column name);
e.g. to add PRIMARY KEY constraint on column ECODE of table EMPLOYEE , the command is :
ALTER TABLE EMPLOYEE
ADD PRIMARY KEY (ECODE) ;
TO ADD FOREIGN KEY CONSTRAINT
REMOVING CONSTRAINTS
- To remove primary key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP PRIMARY KEY ;
- To remove foreign key constraint from a table, we use ALTER TABLE command
as : ALTER TABLE <table name>
DROP FOREIGN KEY ;
ENABLING/DISABLING CONSTRAINTS
Only foreign key can be disabled/enabled in MySQL.
To disable foreign keys : SET FOREIGN_KEY_CHECKS = 0 ;
To enable foreign keys : SET FOREIGN_KEY_CHECKS = 1 ;
INTEGRITY CONSTRAINTS/CONSTRAINTS
- A constraint is a condition or check applicable on a field(column) or set of fields(columns).
- Common types of constraints include :
Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.
DEFAULT CONSTARINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement does not
provide a specific value. E.g.
UNIQUE CONSTRAINT
- The UNIQUE constraint ensures that all values in a column are distinct. In other words, no two rows can
hold the same value for a column with UNIQUE constraint.
e.g.
CREATE TABLE Customer
( SID integer Unique ,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
Column SID has a unique constraint, and hence cannot include duplicate values. So, if the table already
contains the following rows :
CHECK CONSTRAINT
- The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the table will
only insert a new row or update an existing row if the new value satisfies the CHECK constraint.
e.g.
CREATE TABLE Customer
( SID integer CHECK (SID > 0),
Last_Name varchar(30) ,
First_Name varchar(30) ) ;
will result in an error because the values for SID must be greater than 0.
- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.
Or
CREATE TABLE Customer
( SID integer,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (SID) ) ;
- The latter way is useful if you want to specify a composite primary key, e.g.
e.g.
Parent Table
TABLE: STUDENT
ROLL_NO NAME CLASS
1 ABC XI Primary key
2 DEF XII
3 XYZ XI Child Table
TABLE: SCORE
ROLL_NO MARKS
1 55
2 83
3 90
Here column Roll_No is a foreign key in table SCORE(Child Table) and it is drawing its values from
Primary key (ROLL_NO) of STUDENT table.(Parent Key).
REFERENCING ACTIONS
Referencing action with ON DELETE clause determines what to do in case of a DELETE occurs in the parent table.
Referencing action with ON UPDATE clause determines what to do in case of a UPDATE occurs in the parent table.
Actions:
1. CASCADE : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
automatically delete or update the matching rows in the child table i.e., cascade the action to child table.
2. SET NULL : This action states that if a DELETE or UPDATE operation affects a row from the parent table, then
set the foreign key column in the child table to NULL.
3. NO ACTION : Any attempt for DELETE or UPDATE in parent table is not allowed.
4. RESTRICT : This action rejects the DELETE or UPDATE operation for the parent table.
Table : EMPL
1. AVG( )
This function computes the average of given
data. e.g. SELECT AVG(SAL)
FROM EMPL ;
Output
AVG(SAL)
6051.6
2. COUNT( )
This function counts the number of rows in a given column.
If you specify the COLUMN name in parenthesis of function, then this function returns rows where COLUMN
is not null.
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.
3. MAX( )
This function returns the maximum value from a given column or expression.
5. SUM( )
This function returns the sum of values in given column or expression.
Output
SUM(SAL)
30258
** One thing that you should keep in mind is that while grouping , you should include only those values in the SELECT list
that either have the same value for a group or contain a group(aggregate) function. Like in e.g. 2 given above, DEPTNO
column has one(same) value for a group and the other expression SUM(SAL) contains a group function.
NESTED GROUP
- To create a group within a group i.e., nested group, you need to specify multiple fields in the GROUP BY
expression. e.g. To group records job wise within Deptno wise, you need to issue a query statement like :
DATABASE TRANSACTIONS
TRANSACTION
A Transaction is a logical unit of work that must succeed or fail in its entirety. This statement means that a
transaction may involve many sub steps, which should either all be carried out successfully or all be ignored if
some failure occurs. A Transaction is an atomic operation which may not be divided into smaller operations.
Example of a Transaction
Begin transaction
Get balance from account X
Calculate new balance as X – 1000
Store new balance into database file
Get balance from account Y
Calculate new balance as Y + 1000
Store new balance into database file
End transaction
TRANSACTION PROPERTIES (ACID PROPERTIES)
1. ATOMICITY(All or None Concept) – This property ensures that either all operations of the transaction are
carried out or none are.
2. CONSISTENCY – This property implies that if the database was in a consistent state before the start of
transaction execution, then upon termination of transaction, the database will also be in a consistent state.
3. ISOLATION – This property implies that each transaction is unaware of other transactions executing
concurrently in the system.
4. DURABILITY – This property of a transaction ensures that after the successful completion of a
transaction, the changes made by it to the database persist, even if there are system failures.
COMPUTER NETWORKS
CH-10 Networks
10.1 INTRODUCTION TO COMPUTER NETWORKS
The collection of interconnected computers is called a computer network(Figure 10.1).
Two computers are said to be interconnected if they are capable of sharing and exchanging
information.
Device
1
[Type here] [Type here] [Type here]
2
[Type here] [Type here] [Type here]
single room, a floor, laboratory, a school, college, or university
campus.
The connectivity is doneby means of wires, Ethernet cables,
fibre optics, or Wi-Fi.
3
[Type here] [Type here] [Type here]
10.4.1 Modem
Modem stands for ‘MOdulator DEModulator’.
The modem at the sender’s end acts as a modulator that converts the digital data
into analog signals.
The modem at the receiver’s end acts as a demodulator that converts the analog
signals into digital data for the destination node to understand.
Modulation Demodulation
Demodulation Modulation
4
[Type here] [Type here] [Type here]
10.4.4 Repeater
A repeater is an analog device that works with signals on the cables to which
it is connected. The weakened signal appearing on the cable is regenerated and put
back on the cable by a repeater.
10.4.5 Hub
An Ethernet hub is a network device used to connect different devices through
wires. Data arriving on any of the lines are sent out on all the others.
10.4.6 Switch
A switch is a networking device that plays a central role in a Local Area
Network (LAN).
When data arrives, the switch extracts the destination address from the data
packet and looks it up in a table to see where to send the packet.
Ethernet switches are common in homes/offices to connect multiple
devices thus creating LANs or to access the Internet.
10.4.6 Router
A router is a network device that can receive the data, analyse it and transmit
it to other networks.
A router connects a local area network to the internet.
A router can be wired or wireless. A wireless router can provide Wi-Fi
access to smartphones and other devices.
These days, home Wi-Fi routers perform the dual task of a router and a
modem/ switch.
10.4.7 Gateway
“Gateway” acts as a “gate” between an organisation's network and the
outside world of the Internet.
Gateway serves as the entry and exit point of a network, as all data coming in
or going out of a network must first pass through the gateway in order to use
routing paths.
5
[Type here] [Type here] [Type here]
10.5.2 Ring Topology
In ring topology, each node is connected to two other devices forming a ring.
The link in a ring topology is unidirectional. Thus, data can be transmitted in
one direction only (clockwise or counterclockwise)
6
[Type here] [Type here] [Type here]
10.5.5 Tree or Hybrid Topology
It is a hierarchical topology, in which there are multiple branches and each
branch can have one or more basic topologies like star, ring and bus.
In this type of network, data transmitted from source first reaches the
centralised device and from there the data passes through every branch
where each branch can have links for more nodes.
10.6.2 IP Address
Each computer on internet is identified by a unique number called as Internet
Protocol address
The initial IP Address called version 4 (IPV4 in short), is a 32 bit numeric
address, written as four numbers separated by periods, where each number is
7
[Type here] [Type here] [Type here]
the decimal (base-10) representation for an 8-bit binary (base-2) number and
each can take any value from 0 - 255. A sample IPV4 address looks
like:[Link]
A 128 bits IP address, called IP version 6 (IPV6 in short) is represented by
eight groups of hexadecimal (base-16) numbers separated by colons. A
sample IPV6 address looks like:
2001:CDBA:0000:0000:0000:0000:3257:9652
8
[Type here] [Type here] [Type here]
For example, IP addresses and domain names of some websites are as follows:
9
[Type here] [Type here] [Type here]
DATA COMMUNICATION
CH-11 Networks
11.1 Concept of Communication
data communication refers to the exchange of data between two or
more networked or connected devices.
Examples of such devices include personal computers, mobile phones,
laptops, etc. These devices are connected through a media to the network,
which carry information from one end to other end.
11.3.1 Bandwidth
Bandwidth of a channel is the range of frequencies available for transmission of
data through that channel.
Bandwidth is measured in Hertz (Hz).
1 KHz =1000 Hz
1 MHz =1000 KHz = 1000000 Hz
11.3.2 Data Transfer Rate
Data transfer rate is the number of bits transmitted between source and
destination in one second. It is also known as bit rate. It is measured in terms of
bits per second (bps). The higher units for data transfer rates are:
Kbps=210 bps=1024 bps
2
[Type here] [Type here] [Type here]
11.4.2 Half-duplex Communication
It is two way or bidirectional communication between two devices in which
both the devices can send and receive data or control signals in both
directions, but not at the same time.
EX: walkie-talkie.
3
[Type here] [Type here] [Type here]
4
[Type here] [Type here] [Type here]
It has a copper wire at the core of the cable which is surrounded with insulating
material.
It is better shielded and has more bandwidth than a twisted pair & transmits
data quickly, without interference of environmental factors.
These types of cables are used to carry signals of higher frequencies to a
longer distance.
C) Optical Fibre
Optical fiber cable carries data as light, which travels inside a thin fiber of
glass.
Optic fiber uses refraction to direct the light through the media.
These cables are of light weight and have higher bandwidth which means higher
data transfer rate.
Signals can travel longer distances and electromagnetic noise cannot affect the
cable.
Optic fibers are expensive and unidirectional.
Transmission
Waves Properties
Radio Waves 1. Waves of frequency range 3 KHz - 1 GHz
2. Omni-directional, these waves can move in all directions
3. Radio waves of frequency 300KHz-30MHz can travel long distance
4. Susceptible to interference & can penetrate walls
5. These waves are used in AM and FM radio, television, cordless phones.
A) Bluetooth
Bluetooth is a short-range wireless technology that can be used to connect
mobile-phones, mouse, headphones, keyboards, computers, etc. wirelessly
over a short distance.
In Bluetooth technology, the communicating devices within a range of 10
meters build a personal area network called piconet.
The devices in a piconet work in a master-slave configuration where a
master device can communicate with up to 7 active slave devices at the same
time.
Bluetooth technology allows up to 255 devices to build a network
B) Wireless LAN
Wireless LAN is a local area network (LAN), and it is a popular way to
connect to the Internet.
7
[Type here] [Type here] [Type here]
Wi-Fi gives users the flexibility to move around within the network area
while being connected to the network.
BENEFITS OF WLAN:
Wireless connections can be used to extend or replace an existing
wired infrastructure
Resulted in increased access for mobile devices
Provides easy access to the Internet in public places
8
[Type here] [Type here] [Type here]
10
Chapter 12
In this chapter:
Virus
The term computer virus was coined by Fred Cohen in 1985 and has been borrowed
from biological science with almost similar meaning and behavior, the only difference is
that the victim is a computer system and the virus is a malicious software.
A virus is a piece of software code created to perform malicious activities and hamper
resources of a computer system like CPU time, memory, personal files, or sensitive
information.
Worms
The Worm is also a malware that incurs unexpected or damaging behaviour on an
infected computer system.
The major difference between a worm and a virus is that unlike a virus, a worm does not
need a host program or software to insert its code into.
Worms are standalone programs that are capable of working on its own.
Ransomware
It is a type of malware that targets user data. It either blocks the user from accessing
their own data or threatens to publish the personal data online and demands ransom
payment against the same.
Some ransomware simply block the access to the data while others encrypt data making
it very difficult to access.
In May 2017, a ransomware WannaCry infected almost 200,000 computers across 150
countries.
Trojan
Since the ancient Greeks could not infiltrate the city of Troy using traditional warfare
methods, they gifted the king of Troy with a big wooden horse with hidden soldiers
inside and eventually defeated them.
Borrowing the concept, a Trojan is a malware, that looks like a legitimate software and
once it tricks a user into installing it, it acts pretty much like a virus or worm.
Spyware It is a type of malware that spies on a person or an organization by gathering
information about them, without the knowledge of the user.
It records and sends the collected information to an external entity without consent or
knowledge of the user.
Spyware usually tracks internet usage data and sells them to advertisers.
They can also be used to track and capture credit card or bank account information,
login and password information or user’s personal identity.
Adware
An Adware is a malware that is created to generate revenue for its developer.
An adware displays online advertisements using pop-ups, web pages, or installation
screens.
Once an adware has infected a substantial number of computer systems, it generates
revenue either by displaying advertisements or using “pay per click” mechanism to
charge its clients against the number of clicks on their displayed ads.
Keyloggers
A keylogger can either be malware or hardware. The main purpose of this malware is to
record the keys pressed by a user on the keyboard.
A keylogger makes logs of daily keyboard usage and may send it to an external entity as
well.
• Downloaded from the Internet: Most of the time, malware is unintentionally downloaded
into the hard drive of a computer by the user. Of course, the malware designers are smart
enough to disguise their malware, but we should be very careful while downloading files from
the Internet (especially those highlighted as free stuff).
• Spam Email: We often receive an unsolicited email with embedded hyperlinks or attachment
files. These links or attached files can be malware.
• Removable Storage Devices: Often, the replicating malware targets the removable storage
media like pen drives, SSD cards, music players, mobile phones, etc. and infect them with
malware that gets transferred to other systems that they are plugged into.
• Network Propagation: Some malware like Worms have the ability to propagate from one
computer to another through a network connection.
Combating Malware:
Common signs of some malware infection include the following:
• Frequent pop-up windows prompting you to visit some website and/or download some
software;
• Changes to the default homepage of your web browser;
• Mass emails being sent from your email account;
• Unusually slow computer with frequent crashes;
• Unknown programs startup as you turn on your computer;
• Programs opening and closing automatically;
• Sudden lack of storage space, random messages, sounds, or music start to appear;
• Programs or files appear or disappear without your knowledge.
Malware exists and continues to evolve, and so is the mechanism to combat them. As the saying
goes that prevention is better than cure, we list some preventive measures against the malware
discussed earlier.
Using antivirus, anti-malware, and other related software and updating them on a
regular basis.
Configure your browser security settings
Always check for a lock button in the address bar while making payments.
Never use pirated on unlicensed software. Instead go for Free and Open Source
Software (FOSS).
Applying software updates and patches released by its manufacturers.
Taking a regular backup of important data.
Enforcing firewall protection in the network.
Avoid entering sensitive (passwords, pins) or personal information on unknown or public
computers.
Avoid entering sensitive data on an unknown network (like Wi-Fi in a public place) using
your own computer also.
Avoid clicking on links or downloading attachments from unsolicited emails.
Scan any removable storage device with an antivirus software before transferring data to
and from it.
Never share your online account or banking password/pins with anyone.
Remove all the programs that you don’t recognize from your system.
Do not install an anti-spyware or antivirus program presented to you in a pop-up or ad.
Use the pop-up window’s ‘X’ icon located on the top-right of the popup to close the ad
instead of clicking on the ‘close’ button in the pop-up. If you notice an installation has
been started, cancel immediately to avoid further damage.
Antivirus
Antivirus is a software, also known as anti-malware. Initially, antivirus software was developed
to detect and remove viruses only and hence the name anti-virus.
Signature-based detection
In this method, an antivirus works with the help of a signature database known as “Virus
Definition File (VDF)”.
This file consists of virus signatures and is updated continuously on a real-time basis.
This makes the regular update of the antivirus software a must.
If there is an antivirus software with an outdated VDF, it is as good as having no antivirus
software installed, as the new malware will infect the system without getting detected.
Sandbox detection
In this method, a new application or file is executed in a virtual environment (sandbox)
and its behavioural fingerprint is observed for a possible malware.
Depending on its behaviour, the antivirus engine determines if it is a potential threat or
not and proceeds accordingly.
Heuristics
Often, a malware infection follows a certain pattern. Here, the source code of a
suspected program is compared to viruses that are already known and are in the
heuristic database.
If the majority of the source code matches with any code in the heuristic database, the
code is flagged as a possible threat.
Real-time protection
Some malware remains dormant or gets activated after some time.
Such malware needs to be checked on a real-time basis.
In this technique, the anti-malware software keeps running in the background and
observes the behavior of an application or file for any suspicious activity while it is being
executed i.e. when it resides in the active (main) memory of the computer system.
Spam
Spam is a broad term and applies to various digital platforms like messaging, forums, chatting,
emailing, advertisement, etc. However, the widely recognized form is email spam.
Depending on their requirements, organizations or individuals buy or create a mailing list (list of
email addresses) and repeatedly send advertisement links and invitation emails to a large
number of users.
HTTP vs HTTPS
Both the HTTP (Hyper Text Transfer Protocol) and its variant HTTPS (Hyper Text Transfer Protocol
Secure) are a set of rules (protocol) that govern how data can be transmitted over the WWW
(World Wide Web). In other words, they provide rules for the client web browser and servers to
communicate.
Firewall
Computer firewall is a network security system designed to protect a trusted private network
from unauthorised access or traffic originating from an untrusted outside network (e.g., the
Internet or different sections of the same network) to which it is connected
Types of Firewall
• Network Firewall: If the firewall is placed between two or more networks and monitors the
network traffic between different networks, it is termed as Network Firewall.
• Host-based Firewall: If the firewall is placed on a computer and monitors the network traffic
to and from that computer, it is called a host-based firewall.
Cookies
The term "cookie" was derived from the term "magic cookie" used by Unix programmers
to indicate a packet of data that a program receives and sends it back unchanged.
A computer cookie is a small file or data packet, which is stored by a website on the
client’s computer.
A cookie is edited only by the website that created it, the client’s computer acts as a host
to store the cookie.
Cookies are used by the websites to store browsing information of the user.
For example, while going through an e-commerce website, when a user adds items to
cart, the website usually uses cookies to record the items in the cart.
Denial of Service
Denial of Service (DoS) is a scenario, wherein an attacker (Hacker) limits or stops an
authorized user to access a service, device, or any such resource by overloading that
resource with illegitimate requests. The DoS attack floods the victim resource with
traffic, making the resource appear busy.
If attackers carry out a DoS attack on a website, they will flood it with a very large
number of network packets by using different IP addresses.
This way, the web server would be overloaded and will not be able to provide service to
a legitimate user.
The users will think that the website is not working, causing damage to the victim’s
organization.
Same way, DoS attacks can be done on resources like email servers, network storage,
disrupting connection between two machines or disrupting the state of information
(resetting of sessions).
Intrusion Problems
Network Intrusion refers to any unauthorized activity on a computer network.
These activities may involve unauthorized use of network resources (DoS) or threatening
the security of the network and the data.
Network intrusion is a very serious problem and the network administrator needs to
devise strategy and implement various security measures to protect the network.
Snooping
Snooping means secretly listening to a conversation. In the context of networking, it refers to
the process of secret capture and analysis of network traffic. It is a computer program or utility
that has a network traffic monitoring capability.
Eavesdropping
The term eavesdropping has been derived from the literal practice of secretly listening to the
conversations of people by standing under the eaves of a house. Unlike snooping, where the
network traffic can be stored for later analysis, eavesdropping is an unauthorized real-time
interception or monitoring of private communication between two entities over a network.
Project Based
13
InthisChapter Learning
Introduction
» Approaches for Solving Projects
» Teamwork
» Project Descriptions
INTRODUCTION
Project based learning gives a thorough practical exposure to students regarding a problem
upon which the project is based. Through project based learning, students learn to organize
their project and use their time effectively for successful completion of the project. Projects
are developed generally in groups where students can learn various skills such as working
together, problem solving, decision making, and investigating activities.
Outcome
of project
TEAM WORK
Many real-life tasks are very complex and require a lot of individuals to contribute in achieving them.
Efforts made by individuals collectively to accomplish a task is called teamwork.
Components of Teamwork
Apart from technical proficiency, a wide variety of other components make a successful teamwork. It
comprises skilled team members with specific roles to achieve the goal.
(F) Participate
All the team members must been courage by each other to participate in completing the project and also
in discussions in group meetings. Also, every member should take an active participations that they feel
their importance in the team.
Description:
A new restaurant “Stay Healthy” is coming up in your locality. The owner/management of the restaurant
wants to use a computer to generate bills and maintain other records of the restaurant. Your team is asked
to develop an application software to automate the order placing and associated processes.
Specifications:
Make a group of students to undertake a project on automating the order processing of the restaurant
‘Stay Healthy’. The owner of the restaurant wants the following specific functionalities to be made
available in the developed application:
•There should be two types of Login options — one for the manager of the joint and other for the
customer.
•Kiosk(s) running the software for customers will be placed at reception for placing the order. On the
opening screen, menu for placing orders will be displayed.
•To place orders, customers will enter Item Code(s) and quantity desired.
•After placing an order, a soft copy of the bill will be displayed on the kiosk, having an Order Number.
•Every bill will have a unique identification (such as combination of date, and order number of the day)
and should be saved in the data file/database.
•OrderNumberstartsfrom1everyday.
•For Manager login-provision for entry/change of Menu, deletion of Order (on demand) and generation of
following report is desired.
A Report giving Summary of the Sales made on a Day. Program should accept the date
for which the Summary is required.
•Add at least one more relevant report of your choice to the program.
Description:
Implement a puzzle solving game in Python. The game presents a grid board composed of cells to the
player, in which some cells have Bomb. Player is required to clear the board (of the bomb), without
detonating any one of them with the help of clue(s) provided on the board.
Specifications:
For clearing the board, the player will click a cell on the board, if the cell contains a bomb, the game
finishes. If the cell does not contain a bomb, then the cell reveals a number giving a clue about the
number of bombs hidden in adjacent cells.
Before you start coding the game, play any Mine sweeper game five times. This will help you in proper
understanding of your project. To reduce the complexity of the program you can fix the grid size to 6x6
and number of bombs to 6.
Note: Do ensure to handle various exception(s) which may occur while playing the game, in your code.
Project Title 3 : Development of an Educational Game
Description:
You are a member of the ICT club of your school. As a club member, you are given the responsibility of
identifying ways to improve mathematical skills of kids, in the age group of 5-7 years. One of the club
members suggested developing an Edutainment Game named “Match the Sum” for it. Match the Sum will
hone summing skills of student(s), by allowing them to form number 10 by adding 2/3 digits.
Specifications:
Following are the details of provisions required for program:
•Display a list of 15 cells on screen, where each cell can hold a digit (1 to 9)
•Randomly generate a digit at a time and place it in the list from the right end. Program will keep on
generating digits at equal intervals of time and place it in the rightmost cell. (Already existing digits, will
be shifted left, by one cell, with every new addition of digits’ in the list)
•For playing the game, students’ will be allowed to type 2/3 digits (one at a time) currently displayed in
the list of cells.
•If the sum of those digits is 10, then those digits should get removed from the list of cells.
•Game will continue till there is an empty cell to insert a digit in the list of cells.