0% found this document useful (0 votes)
3 views108 pages

2nd PU Complete Python Notes

This document covers exception handling in Python, including syntax errors, built-in exceptions, and the process of raising and handling exceptions. It explains how to catch exceptions using try-except blocks and the use of finally clauses. Additionally, it introduces file handling concepts, types of files, and methods for reading and writing to text files, as well as the Pickle module for object serialization.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views108 pages

2nd PU Complete Python Notes

This document covers exception handling in Python, including syntax errors, built-in exceptions, and the process of raising and handling exceptions. It explains how to catch exceptions using try-except blocks and the use of finally clauses. Additionally, it introduces file handling concepts, types of files, and methods for reading and writing to text files, as well as the Pickle module for object serialization.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1

In this Chapter » Introduction


» Syntax Errors
» Exceptions
» Built-in Exceptions
» Raising Exceptions
» Handling Exceptions
» Finally Clause

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.

The raise Statement:


The raise statement can be used to throw an exception. The syntax of raise statement is:
raise exception-name[(optional argument)]
The argument is generally a string that is displayed when the exception is raised.

The assert Statement:


An assert statement in Python is used to test an expression in the program code. If the result after
testing comes false, then the exception is raised. This statement is generally used in the beginning
of the function or after a function call to check for valid input.
The syntax for assert statement is:
assert Expression[,arguments]

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.

Need for Exception Handling:


 Python categories exceptions into distinct types so that specific exception handlers
(code to handle that particular exception) can be created for each type.
 Exception handlers separate the main logic of the program from the error detection
and correction code. The segment of code where there is any possibility of error or
exception, is placed inside one block. The code to be executed in case the exception
has occurred, is placed inside another block. These statements for detection and
reporting the exception do not affect the main logic of the program.
 The compiler or interpreter keeps track of the exact position where the error has
occurred.
 Exception handling can be done for both user-defined and built-in exceptions

Process of Handling Exception:


 When an error occurs, Python interpreter creates an object called the exception object.
 This object contains information about the error like its type, file name and position in the
program where the error has occurred.
 The object is handed over to the runtime system so that it can find an appropriate code to
handle this particular exception.
 This process of creating an exception object and handing it over to the runtime system is
called throwing an exception.
 It is important to note that when an exception occurs while executing a particular program
statement, the control jumps to an exception handler, abandoning execution of the
remaining program statements.

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.

Recovering and continuing with finally clause:


 If an error has been detected in the try block and the exception has been thrown, the
appropriate except block will be executed to handle the error.
 But if the exception is not handled by any of the except clauses, then it is re-raised after
the execution of the finally block.
Chapter 2
In this chapter:

» 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 and Closing a Text file:


In real world applications, computer programs deal with data coming from different sources like
databases, CSV files, HTML, XML, JSON, etc. We broadly access files either to write or read data
from it.

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.

Opening a file using with clause:


In Python, we can also open a file using with clause. The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
The advantage of using with clause is that any file that is opened using this clause is closed
automatically, once the control comes outside the with clause. In case the user forgets to close the
file explicitly or if an exception occurs, the file is closed automatically. Also, it provides a simpler
syntax.
with open(“[Link]”,”r+”) as myObject: content = [Link]()

Writing to a Text File:


For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will be positioned at the
beginning of the file.
The write() method write() method takes a string as an argument and writes it to the text file. It
returns the number of characters being written on single execution of the write() method. Also, we
need to add a newline character (\n) at the end of every sentence to mark the end of line. Consider
the following piece of code:
>>> myobject=open("[Link]",'w')
>>> [Link]("Hey I have started #using files in Python\n")
41
>>> [Link]()

The writelines() method:


This method is used to write multiple strings to a file. We need to pass an iterable object like lists,
tuple, etc. containing strings to the writelines() method. Unlike write(), the writelines() method
does not return the number of characters written in the file. The following code explains the use of
writelines().
>>> myobject=open("[Link]",'w')
>>> lines = ["Hello everyone\n", "Writing #multiline strings\n", "This is the #third line"]
>>> [Link](lines)
>>>[Link]()

Reading from a Text file:

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

The readline([n]) method:


This method reads one complete line from a file where each line terminates with a newline (\n)
character. It can also be used to read a specified number (n) of bytes of data from a file but
maximum up to the newline character (\n). In the following example, the second statement reads
the first ten characters of the first line of the text file and displays them on the screen.
>>> myobject=open("[Link]",'r')
>>> [Link](10)
'Hello ever'
>>> [Link]()

The readlines() method:


The method reads all the lines and returns the lines along with newline as a list of strings. The
following example uses readlines() to read data from the text file [Link].
>>> myobject=open("[Link]", 'r')
>>> print([Link]())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third line']
>>> [Link]( )
Setting Offsets in a file:
The functions that we have learnt till now are used to access the data sequentially from a file. But
if we want to access data in a random fashion, then Python gives us seek() and tell() functions to
do so.

The tell() method:


This function returns an integer that specifies the current position of the file object in the file. The
position so specified is the byte position from the beginning of the file till the current position of
the file object. The syntax of using tell() is:
file_object.tell().

The seek() method:


This method is used to position the file object at a particular position in a file. The syntax of seek()
is:
file_object.seek(offset [, reference_point])

Creating a file and writing data:


To create a text file, we use the open() method and provide the filename and the mode. If the file
already exists with the same name, the open() function will behave differently depending on the
mode (write or append) used.
To create a text file and write data in it
# program to create a text file and add data
fileobject=open("[Link]","w+")
while True:
data= input("Enter data to save in the text file: ")
[Link](data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n':
break
[Link]()

Traversing a file and displaying data:


To read and display data that is stored in a text file, we will refer to the previous example where
we have created the file [Link]. The file will be opened in read mode and reading will begin
from the beginning of the file.
Program to create a text file and write data in it # program to create a text file and add data
fileobject=open("[Link]","w+")
while True:
data= input("Enter data to save in the text file: ")
[Link](data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n': break
[Link]()

The Pickle Module:


 To save any object structure along with data, Python provides a module called Pickle.
 The module Pickle is used for serializing and de-serializing any Python object structure.
 Pickling is a method of preserving food items by placing them in some solution, which
increases the shelf life.
 In other words, it is a method to store food items for later consumption.

Serialization is the process of transforming data or an object in memory (RAM) to a stream of


bytes called byte streams. These byte streams in a binary file can then be stored in a disk or in a
database or sent through a network. Serialization process is also called pickling.

De-serialization or unpickling is the inverse of pickling process where a byte stream is


converted back to Python object

The dump() method:


This method is used to convert (pickling) Python objects for writing data in a binary file. The file
in which data are to be dumped, needs to be opened in binary write mode (wb). Syntax of dump()
is as follows:
dump(data_object, file_object)

The load() method:


This method is used to load (unpickling) data from a binary file. The file to be loaded is opened
in binary read (rb) mode. Syntax of load() is as follows:
Store_object = load(file_object)

File handling using pickle module:


As we read and write data in a text file, similarly we will be adding and displaying data for a
binary file. Thereafter, the records are read from the binary file and displayed on the screen using
the same object. The user may enter as many records as they wish to. The program also displays
the size of binary files before starting with the reading process.
II PU Computer science-Chapter-03 2025

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.

Chapter-03 STACK Page 1


II PU Computer science-Chapter-03 2025

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

 Let us create a stack of glasses assuming that each glass is numbered.


Visual representations of PUSH and POP operations on a stack of glasses.
Implementation of Stack in Python
 A stack is a linear and ordered collection of elements.
 The simple way to implement a stack in Python is using the data type list. We can fix
either of the sides of the list as TOP to insert/remove elements.

Chapter-03 STACK Page 2


II PU Computer science-Chapter-03 2025

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

Chapter-03 STACK Page 3


II PU Computer science-Chapter-03 2025

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)

#display number of elements in stack


print("Current number of elements in stack is",size(glassStack))

#delete an element from the stack


element=opPop(glassStack)
print("Popped element is",element)

#add new element to stack


element='glass3'
print("Pushing element ",element)
opPush(glassStack,element)

#display the last element added to the #stack


print("top element is",top(glassStack))
Chapter-03 STACK Page 4
II PU Computer science-Chapter-03 2025

#display all elements in the stack


display(glassStack)

#delete all elements from stack


while True:
item=opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is",item)

The output of the above program will be as follows:


Pushing element glass1
Pushing element glass2
Current number of elements in stack is 2
Popped element is glass2
Pushing element glass3
top element is glass3
Current elements in the stack are:
glass3
glass1
Popped element is glass3
Popped element is glass1
Underflow
Stack is empty now
Notations for Arithmetic Expressions
 We write arithmetic expressions using operators in between operands, like x + y, 2 - 3
* y, etc.
 The expressions follow infix representation and are evaluated using BODMAS rule.
 Polish mathematician Jan Lukasiewicz in the 1920's introduced a different way of
representing arithmetic expression, called polish notation.
 For example, we can write x+y in polish notation as +xy. This is also called prefix
notation as we prefix the operator before operands.
 By reversing this logic, we can write an expression by putting operators after their
operands. For example, x+y can be written as xy+. This is called reverse polish
notation or postfix notation.
Type of
Description Example
Expression
Infix Operators are placed in x*y + z
between the operands 3 *(4 + 5)
(x + y)/(z * 5)

Chapter-03 STACK Page 5


II PU Computer science-Chapter-03 2025

Prefix Operators are placed before +z*xy


 (Polish) the corresponding operands *3+45
/+xy*z5
Postfix Operators are placed after xy*z+
(Reverse Polish) the corresponding operands 345+*
xy+z5*/

Infix, prefix and postfix notations


Conversion from Infix to Postfix Notation
 Consider an infix expression x + y / z. While going from left to right we first
encounter + operator, but we do not add x + y and rather evaluate y/z, followed by
addition operation. This is because we know the order of precedence of operators that
follows BODMAS rule.
 A stack is used to keep track of the operators encountered in the infix expression. A
variable of string type is used to store the equivalent postfix expression.

Algorithm 3.1: Conversion of expression from infix to postfix notation


Step 1: Create an empty string named postExp to store the converted postfix
expression.
Step 2: INPUT infix expression in a variable, say inExp
Step 3: For each character in inExp, REPEAT Step 4
Step 4: IF character is a left parenthesis THEN PUSH on the Stack
ELSE IF character is a right parenthesis
THEN POP the elements from the Stack and append to string
postExp until the corresponding left parenthesis is popped
while discarding both left and right parentheses
ELSE IF character is an operator
THEN IF its precedence is lower than that of operator at the top of Stack
THEN POP elements from the Stack till an
operator with precedence less than the current
operator is encountered and append to string
postExp before pushing this operator on the
postStack
ELSE PUSH operator on the Stack
ELSE Append the character to postExp
Step 5: Pop elements from the Stack and append to postExp until Stack is empty
Step 6: OUTPUT postExp
Example 3.1 Let us now use this algorithm to convert a given infix expression (x +
y)/(z*8) into equivalent postfix expression using a stack. Figure 3.3 shows the steps to
be followed on encountering an operator or an operand in the given infix expression.
Note here that stack is used to track the operators and parentheses, and a string
variable contains the equivalent postfix expression. Initially both are empty. Each
character in the given infix expression is processed from left to right and the
Chapter-03 STACK Page 6
II PU Computer science-Chapter-03 2025

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.

Conversion of infix expression (x + y)/(z*8) to postfix notation

Evaluation Of postfix Expression

Stacks can be used to evaluate an expression in postfix notation. For


simplification, we are assuming that operators used in expressions are binary
operators.
Algorithm 3.2: Evaluation of postfix expression
Step 1: INPUT postfix expression in a variable, say postExp
Step 2: For each character in postExp, REPEAT Step 3
Step 3: IF character is an operand
Chapter-03 STACK Page 7
II PU Computer science-Chapter-03 2025

THEN PUSH character on the Stack


ELSE POP two elements from the Stack, apply the operator on the popped elements and
PUSH the computed value onto the Stack
Step 4: IF Stack has a single element
THEN POP the element and OUTPUT as the net result
ELSE OUTPUT “Invaild Postfix expression”

Example
The step-by-step process of evaluation of the postfix expression 7 8 2 * 4 / + using
Algorithm

Evaluation of postfix expression 7 8 2 * 4 /+

Chapter-03 STACK Page 8


QUEUE
 Queue is an ordered linear list of elements, having different ends for adding and removing
elements in it.
 Queue works on First-In-First-Out (FIFO) principle.
 Example : 1. Queue of people at a bank
2. Queue of cars in a petrol pump
First In First Out (FIFO)
 Queue follows the principle of First In First Out (FIFO), since the element entering first in
the queue will be the first one to come out of it.
 Thus, the element that has been longest in the queue will be removed first. It is also known as a
First Come First Served (FCFS) approach.
 Queue is an arrangement in which new objects/items always get added at one end, usually
called the REAR, and objects/items always get removed from the other end, usually called the
FRONT of the queue.
 REAR is also known as TAIL and FRONT as HEAD of a queue.
Applications of Queue
(A) The concept of queue has many applications in real-life:
• If a train ticket is in the waiting list (such as W/L1), it means the ticket is in a queue of tickets
waiting to get confirmed, as per the increasing order of waiting numbers. If a confirmed ticket is
cancelled, the W/ L1 numbered ticket is removed from the FRONT of the waiting queue and
confirmed.
• Sometimes on calling a customer service centre, the Interactive Voice Response System (IVRS)
tells us to wait till a support person is available. Here the call is put into a queue of customers
waiting to be serviced.
• Imagine there is a single-lane one-way road, then the vehicle that entered first will exit first,
following the concept of queue. Likewise, vehicles in a highway toll tax booth are served
following the principle of FIFO.
(B) Following are some examples of application of queue in computer science:
• Suppose there is a web-server hosting a web-site to declare result(s). This server can handle a
maximum of 50 concurrent requests to view result(s). So, to serve thousands of user requests, a
Queue would be the most appropriate data structure to use.
• Some Operating Systems (OS) are required to handle multiple tasks called - jobs, seeking to use
the processor. But we know that a processor can handle only one task at a time. Therefore, in a
multitasking operating system, jobs are lined up (queued) and then given access to the processor
according to some order. The simplest way is to give access to the processor on a FIFO basis, that
is according to the order in which the jobs arrive with a request for the processor.
• When we send print commands from multiple files from the same computer or from different
computers using a shared printer. The OS puts these print requests in a queue and sends them to
the printer one by one on a FIFO basis.

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

Implementation of Deque Using Python


Like queue, deque is also an ordered linear list, hence we use list data type to create deque in
our program. The program should have the following functions/ statement(s) defined in it:
• A statement to create deque, with name myDeque.
myDeque = list()
• A function insertFront(), to insert an element at the front of deque having two parameters -
name of deque and element to be inserted. As the element is to be inserted in the beginning, we
will use insert() with index 0 for it.
def insertFront(myDeque, element):
[Link](0,element)

• 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

Sorting :Sorting is the process of ordering or arranging a given


collection of elements in some particular order like , numbers in ascending
(increasing) or descending (decreasing) order. If the collection is of strings, we
can sort it in an alphabetical order (a-z or z-a) or according to the length of the
string is called Sorting.
Ex:
 Words in a dictionary are sorted in alphabetical order.
 Seats in an examination hall are ordered according to
candidates’ roll number.

In this chapter, we will learn about three sorting methods and implement
them using Python.
1)Bubble sort
2)Selection sort
3)Insertion sort

1)Bubble Sort: The sorting algorithm repeatedly compares adjacent elements


in a list and swaps them if they are out of order, continuing this process until
the entire list is sorted. Swapping two elements means changing their
positions with each other
Note: In algorithm, every iteration through each element of a list is called
Example:

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

Program Implementation of selection sort using Python.


def selection_Sort(list2):
flag = 0 #to decide when to swap
n=len(list2)
for i in range(n): # Traverse through all list elements
min = i
for j in range(i + 1, len(list2)): #the left elements are already sorted in previous
passes
if list2[j] < list2[min]: # element at j is smaller than the current min element
min = j
flag = 1
if flag == 1 : # next smallest element is found list2[min]
list2[i] = list2[i], list2[min]
numList = [8, 7, 13, 1, -9, 4]
selection_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

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

Time Complexity of Algorithms


The amount of time an algorithm takes to process a given data can be called its
time complexity.

****************************************************************
In this Chapter
» Introduction
» Linear Search
» Binary Search
» Search by Hashing

Searching : Searching means locating a particular element in a collection of


elements. . Search result determines whether that particular element is
present in the collection or not.

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.

Algorithm : Linear Search


LinearSearch(numList, key, n)
Step 1: SET index = 0
Step 2: WHILE index < n, REPEAT Step 3
Step 3: IF numlist[index]= key THEN PRINT “Element found at position”, index+1
STOP ELSE index = index+1
Step 4: PRINT “Search unsuccessful
Example Program Linear Search
def linearSearch(list, key): #function to perform the search
for index in range(0,len(list)):
if list[index] == key: #key is present
return index+1 #position of key in list
return None #key is not in list
#end of function
list1 = [] #Create an empty list
maximum = int(input("How many elements in your list? "))
print("Enter each element and press enter: ")
for i in range(0,maximum):
n = int(input())
[Link](n) #append elements to the list
print("The List contents are:", list1)
key = int(input("Enter the number to be searched:"))
position = linearSearch(list1, key)
if position is None:
print("Number",key,"is not present in the list")
else:
print("Number",key,"is present at position",position)
Output
How many elements in your list? 4
Enter each element and press enter:
12
23
3
-45
The List contents are: [12, 23, 3, -45]
Enter the number to be searched:23
Number 23 is present at position 2
Binary Search
 The binary search is a search technique that makes use of the ordering of
elements in the list to quickly search a key.
 In binary search, the key to be searched is compared with the element in
the middle of a sorted list.
This could result in either of the three possibilities:
i) the element at the middle position itself matches the key or
ii) the element at the middle position is greater than the key or
iii) the element at the middle position is smaller than the key
Algorithm:
Binary Search
BinarySearch(numList, key)
Step 1: SET first = 0, last = n-1
Step 2: Calculate mid = (first+last)//2
Step 3: WHILE first <= last REPEAT Step 4
Step 4: IF numList[mid] = key
PRINT “Element found at position”,
" mid+1
STOP
ELSE
IF numList[mid] > key, THEN last = mid-1
ELSE
first = mid + 1
Step 5: PRINT “Search unsuccessful”
Applications of Binary Search
• Binary search has numerous applications including – searching a dictionary or
a telephone directory, finding the element with minimum value or maximum
value in a sorted list, etc.
• Modified binary search techniques have far reaching applications such as
indexing in databases, implementing routing tables in routers, data compression
code, etc.
Search by Hashing
 Hashing is a technique which can be used to know the presence of a key
in a list in just one step.
 Hashing makes searching operations very efficient.
 A formula called hash function is used to calculate the value at an index in
the list
Program
Use of hashing to find a key in the given list L
#Function to check if a key is present or not
def hashFind(key,hashTable):
if (hashTable[key % 10] == key): #key is present
return ((key % 10)+1) #return the position
else:
return None #key is not present
#end of function
#create hashTable with 10 empty positions
hashTable=[None, None, None, None, None, None, None, None, None,
None]
print("We have created a hashTable of 10 positions:")
print(hashTable)
L = [34, 16, 2, 93, 80, 77, 51]
print("The given list is", L[::] )
# Apply hash function
for i in range(0,len(L)):
hashTable[L[i]%10] = L[i]
print("The hash table contents are: " )
for i in range(0,len(hashTable)):
print("hashindex=", i," , value =", hashTable[i])
key = int(input("Enter the number to be searched:"))
position = hashFind(key,hashTable)
if position is None:
print("Number",key,"is not present in the hash table")
else:
print("Number ",key," present at ",position, " position")
Output:
We have created a hashTable of 10 positions:
[None, None, None, None, None, None, None, None, None, None]
The given list is [34, 16, 2, 93, 80, 77, 51]
The hash table contents are:
hashindex= 0 , value = 80
hashindex= 1 , value = 51
hashindex= 2 , value = 2
hashindex= 3 , value = 93
hashindex= 4 , value = 34
hashindex= 5 , value = None
hashindex= 6 , value = 16
hashindex= 7 , value = 77
hashindex= 8 , value = None
hashindex= 9 , value = None
Enter the number to be searched:16
Number 16 present at 7 position

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.

Statistical Techniques for Data Processing:


Given a set of data values, we need to process them to get information. There are various
techniques which help us to have preliminary understanding about the data.
Measures of Central Tendency
A measure of central tendency is a single value that gives us some idea about the data. Three most
common measures of central tendency are the mean, median, and mode.

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.

Database Management System:


A database management system (DBMS) or database system in short, is a software that can be
used to create and manage databases. DBMS lets users to create a database, store, manage,
update/modify and retrieve data from that database by users or application programs. Some
examples of open source and commercial DBMS include MySQL, Oracle, PostgreSQL, SQL Server,
Microsoft Access, MongoDB.
File System to DBMS:
In order to convert these two files into a database, we need to incorporate the following
changes:
a) SName need not be maintained in ATTENDANCE file as it is already there in STUDENT.
Details for a student can be retrieved through the common field RollNumber in both the
files.
b) If two siblings are in the same class, then same guardian details (GName, GPhone and
GAddress) are maintained for both the siblings. We know this is a redundancy and by
using a database we can avoid this. So let us split the STUDENT file into two file
(STUDENT file and GUARDIAN) file so that each guardian data are maintained only once.
c) One and more guardians can have the same name. So it will not be possible to identify
which guardian is related to which student. In such case, we need to create an additional
column, say GUID (Guardian ID) that will take unique value for each record in the
GUARDIAN file. The column GUID will also be kept with STUDENT file for relating these
two files.
Key Concepts in DBMS:
In order to efficiently manage data using a DBMS, let us understand certain key terms:
A) Database Schema
Database Schema is the design of a database. It is the skeleton of the database that
represents the structure (table names and their fields/columns), the type of data each
column can hold, constraints on the data to be stored (if any), and the relationships
among the tables.
B) Data Constraint
Sometimes we put certain restrictions or limitations on the type of data that can be
inserted in one or more columns of a table. This is done by specifying one or more
constraints on that column(s) while creating the tables. For example, one can define the
constraint that the column mobile number can only have non-negative integer values of
exactly 10 digits.
C) Meta-data or Data Dictionary
The database schema along with various constraints on the data is
stored by DBMS in a database catalog or dictionary, called meta-data. A meta-data is
data about the data.
D) Database Instance
When we define database structure or schema, state of database is empty i.e. no data
entry is there. After loading data, the state or snapshot of the database at any given time
is the database instance.
E) Query A query is a request to a database for obtaining information in a desired way.
Query can be made to get data from one table or from a combination of tables. For
example, “find names of all those students present on Attendance Date 2000-01-02” is a
query to the database
F) Data Manipulation Modification of database consists of three operations viz. Insertion,
Deletion or Update. Suppose, Rivaan joins as a new student in the class then the student
details need to be added in STUDENT as well as in GUARDIAN files of the Student
Attendance database.
G) Database Engine Database engine is the underlying component or set of programs used
by a DBMS to create database and handle various queries for data retrieval and
manipulation.

Relational Data Model:


 Different types of DBMS are available and their classification is done based on the
underlying data model.
 A data model describes the structure of the database, including how data are defined
and represented, relationships among data, and the constraints.
 The most commonly used data model is Relational Data Model.
 Other types of data models include object-oriented data model, entity-relationship data
model, document model and hierarchical data model.
 This book discusses the DBMS based on relational data model.
i) ATTRIBUTE: Characteristic or parameters for which data are to be stored in a relation.
Simply stated, the columns of a relation are the attributes which are also referred as
fields. For example, GUID, GName, GPhone and GAddress are attributes of relation
GUARDIAN.
ii) TUPLE: Each row of data in a relation (table) is called a tuple. In a table with n
columns, a tuple is a relationship between the n related values.
iii) DOMAIN: It is a set of values from which an attribute can take a value in each row.
Usually, a data type is used to specify domain for an attribute. For example, in
STUDENT relation, the attribute RollNumber takes integer values and hence its
domain is a set of integer values. Similarly, the set of character strings constitutes the
domain of the attribute SName.
iv) DEGREE: The number of attributes in a relation is called the Degree of the relation.
For example, relation GUARDIAN with four attributes is a relation of degree 4.
v) CARDINALITY: The number of tuples in a relation is called the Cardinality of the
relation. For example, the cardinality of relation GUARDIAN is 5 as there are 5 tuples
in the table
Three Important Properties of a Relation:
Property 1: imposes following rules on an attribute of the relation.
• Each attribute in a relation has a unique name.
• Sequence of attributes in a relation is immaterial.

Property 2: governs following rules on a tuple of a relation.


• Each tuple in a relation is distinct. For example, data values in no two tuples of relation
ATTENDANCE can be identical for all the attributes. Thus, each tuple of a relation must be
uniquely identified by its contents.
• Sequence of tuples in a relation is immaterial. The tuples are not considered to be ordered,
even though they appear to be in tabular form.

Property 3: imposes following rules on the state of a relation.


• All data values in an attribute must be from the same domain (same data type).
• Each data value associated with an attribute must be atomic (cannot be further divisible into
meaningful subparts). For example, GPhone of relation GUARDIAN has ten digit numbers which
is indivisible.
• No attribute can have many data values in one tuple. For example, Guardian cannot specify
multiple contact numbers under GPhone attribute.
• A special value “NULL” is used to represent values that are unknown or non-applicable to
certain attributes. For example, if a guardian does not share his or her contact number with the
school authorities, then GPhone is set to NULL (data unknown).

Keys in a Relational Database:


 Candidate Key
A relation can have one or more attributes that takes distinct values. Any
of these attributes can be used to uniquely identify the tuples in the relation. Such attributes
are called candidate keys as each of them are candidates for the primary key.

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

 Composite Primary Key


If no single attribute in a relation is able to uniquely distinguish the tuples,
then more than one attribute are taken together as primary key. Such primary key consisting of
more than one attribute is called Composite Primary key.

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

DIFFERENT DATA MODELS

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

RELATIONAL MODEL TERMINOLOGY

1. Relation : A table storing logically related data is called a Relation.

2. Tuple : A row of a relation is generally referred to as a tuple.

3. Attribute : A column of a relation is generally referred to as an attribute.

4. Degree : This refers to the number of attributes in a relation.


5. Cardinality : This refers to the number of tuples in a relation.
6. Primary Key : This refers to a set of one or more attributes that can uniquely identify tuples within the relation.

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.

CLASSIFICATION OF SQL STATEMENTS

SQL commands can be mainly divided into following categories:


1. Data Definition Language(DDL) Commands
Commands that allow you to perform task, related to data definition e.g;
  Creating, altering and dropping.
  Granting and revoking privileges and roles.
 Maintenance commands.
2. Data Manipulation Language(DML) Commands
Commands that allow you to perform data manipulation e.g., retrieval, insertion, deletion and modification
of data stored in a database.

3. Transaction Control Language(TCL) Commands


Commands that allow you to manage and control the transactions e.g.,
  Making changes to database, permanent
  Undoing changes to database, permanent
  Creating savepoints
 Setting properties for current transactions.

MySQL ELEMENTS

1. Literals 2. Datatypes 3. Nulls 4. Comments

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

Numeric Data Type


1. int – used for number without decimal.
2. Decimal(m,d) – used for floating/real numbers. m denotes the total length of number and d is number of decimal
digits.
Date and Time Data Type
1. date – used to store date in YYYY-MM-DD format.
2. time – used to store time in HH:MM:SS format.
String Data Types
1. char(m) – used to store a fixed length string. m denotes max. number of characters.
2. varchar(m) – used to store a variable length string. m denotes max. no. of characters.
DIFFERENCE BETWEEN CHAR AND VARCHAR DATA TYPE

[Link]. Char Datatype Varchar Datatype


1. It specifies a fixed length character It specifies a variable length character string.
String.
2. When a column is given datatype as When a column is given datatype as VARCHAR(n),
CHAR(n), then MySQL ensures that all then the maximum size a value in this column can
values stored in that column have this have is n bytes. Each value that is stored in this
length i.e. n bytes. If a value is shorter column store exactly as you specify it i.e. no blanks
than this length n then blanks are are added if the length is shorter than maximum
added, but the size of value remains length n.
n bytes.
NULL VALUE
If a column in a row has no value, then column is said to be null , or to contain a null. You should use a null value
when the actual value is not known or when a value would not be meaningful.

DATABASE COMMNADS

1. VIEW EXISTING DATABASE


To view existing database names, the command is : SHOW DATABASES ;

2. CREATING DATABASE IN MYSQL


For creating the database in MySQL, we write the following
command : CREATE DATABASE <databasename> ;
e.g. In order to create a database Student, command is :
CREATE DATABASE Student ;
3. ACCESSING DATABASE
For accessing already existing database , we write :
USE <databasename> ;
e.g. to access a database named Student , we write command as :
USE Student ;
4. DELETING DATABASE
For deleting any existing database , the command is :
DROP DATABASE <databasename> ;
e.g. to delete a database , say student, we write command
as ; DROP DATABASE Student ;
5. VIEWING TABLE IN DATABASE
In order to view tables present in currently accessed database , command is : SHOW TABLES ;

CREATING TABLES IN MYSQL


- Tables are created with the CREATE TABLE command. When a table is created, its columns are named, data
types and sizes are supplied for each column.
Syntax of CREATE TABLE command
is : CREATE TABLE <table-name>
( <column name> <data type> ,
<column name> <data type> ,
……… ) ;
E.g. in order to create table EMPLOYEE given below :
ECODE ENAME GENDER GRADE GROSS
We write the following command :
CREATE TABLE employee
( ECODE integer ,
ENAME varchar(20) ,
GENDER char(1) ,
GRADE char(2) ,
GROSS integer ) ;
INSERTING DATA INTO TABLE
- The rows are added to relations(table) using INSERT command of SQL. Syntax of
INSERT is : INSERT INTO <tablename> [<column list>]
VALUE ( <value1> , <value2> , …..) ;
e.g. to enter a row into EMPLOYEE table (created above), we write command as :
INSERT INTO employee
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);

OR
INSERT INTO employee (ECODE , ENAME , GENDER , GRADE , GROSS)
VALUES(1001 , ‘Ravi’ , ‘M’ , ‘E4’ , 50000);

ECODE ENAME GENDER GRADE GROSS


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

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000

INSERTING NULL VALUES

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

INSERT INTO EMPLOYEE


VALUES (1004 , NULL , ‘M’ , ‘B2’ , 38965 ) ;

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 NULL M B2 38965

SIMPLE QUERY USING SELECT COMMAND


- The SELECT command is used to pull information from a table. Syntax of SELECT
command is : SELECT <column name>,<column name>
FROM <tablename>
WHERE <condition name> ;
SELECTING ALL DATA
- In order to retrieve everything (all columns) from a table, SELECT command is used
as : SELECT * FROM <tablename> ;

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

SELECT * FROM Employee ;


SELECTING PARTICULAR COLUMNS
EMPLOYEE
ECODE ENAME GENDER GRADE GROSS
1001 Ravi M E4 50000
1002 Akash M A1 35000
1004 Neela F B2 38965
1005 Sunny M A2 30000
1006 Ruby F A1 45000
1009 Neema F A2 52000
- A particular column from a table can be selected by specifying column-names with SELECT command. E.g. in
above table, if we want to select ECODE and ENAME column, then command is :
SELECT ECODE , ENAME
FROM EMPLOYEE ;
E.g.2 in order to select only ENAME, GRADE and GROSS column, the command is :
SELECT ENAME , GRADE ,
GROSS FROM EMPLOYEE ;

SELECTING PARTICULAR ROWS


We can select particular rows from a table by specifying a condition through WHERE clause along with SELECT
statement. E.g. In employee table if we want to select rows where Gender is female, then command is :
SELECT * FROM EMPLOYEE
WHERE GENDER = ‘F’ ;
E.g.2. in order to select rows where salary is greater than 48000, then command is :
SELECT * FROM EMPLOYEE
WHERE GROSS > 48000 ;

ELIMINATING REDUNDANT DATA


The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement. For example ,
SELECT GENDER FROM EMPLOYEE ;
GENDER
M
M
F
M
F
F

SELECT DISTINCT(GENDER) FROM EMPLOYEE ;


DISTINCT(GENDER)
M
F

VIEWING STRUCTURE OF A TABLE


- If we want to know the structure of a table, we can use DESCRIBE or DESC command, as per following syntax :
DESCRIBE | DESC <tablename> ;
e.g. to view the structure of table EMPLOYEE, command is : DESCRIBE EMPLOYEE ; OR DESC EMPLOYEE ;

USING COLUMN ALIASES


- The columns that we select in a query can be given a different name, i.e. column alias name for output purpose.
Syntax :
SELECT <columnname> AS column alias , <columnname> AS column alias …..
FROM <tablename> ;
e.g. In output, suppose we want to display ECODE column as EMPLOYEE_CODE in output , then command is :
SELECT ECODE AS “EMPLOYEE_CODE”
FROM EMPLOYEE ;

CONDITION BASED ON A RANGE


- The BETWEEN operator defines a range of values that the column values must fall in to make the condition
true. The range include both lower value and upper value.

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 :

ECODE ENAME GRADE


1001 Ravi E4
1006 Ruby A1

CONDITION BASED ON A LIST


- To specify a list of values, IN operator is used. The IN operator selects value that match any value in a given
list of values. E.g.

SELECT * FROM EMPLOYEE


WHERE GRADE IN (‘A1’ , ‘A2’);
Output will be :

ECODE ENAME GENDER GRADE GROSS


1002 Akash M A1 35000
1006 Ruby F A1 45000
1005 Sunny M A2 30000
1009 Neema F A2 52000

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

ECODE ENAME GENDER GRADE GROSS


1001 Ravi M E4 50000
1004 Neela F B2 38965

CONDITION BASED ON PATTERN MATCHES


- LIKE operator is used for pattern matching in SQL. Patterns are described using two special wildcard characters:

1. percent(%) – The % character matches any substring.


2. underscore(_) – The _ character matches any character.

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

e.g. to display details of employee whose second character in name is ‘e’.


SELECT *
FROM EMPLOYEE
WHERE ENAME LIKE ‘_e%’ ;

Output will be :

ECODE ENAME GENDER GRADE GROSS


1004 Neela F B2 38965
1009 Neema F A2 52000

e.g. to display details of employee whose name ends with ‘y’.


SELECT *
FROM EMPLOYEE
WHERE ENAME LIKE ‘%y’ ;

Output will be :

ECODE ENAME GENDER GRADE GROSS


1005 Sunny M A2 30000
1006 Ruby F A1 45000

SEARCHING FOR NULL


- The NULL value in a column can be searched for in a table using IS NULL in the WHERE clause. E.g. to list
employee details whose salary contain NULL, we use the command :
SELECT *
FROM EMPLOYEE
WHERE GROSS IS NULL ;
e.g.
STUDENT
Roll_No Name Marks
1 ARUN NULL
2 RAVI 56
4 SANJAY NULL
to display the names of those students whose marks is NULL, we use the command :
SELECT Name
FROM EMPLOYEE
WHERE Marks IS NULL ;
Output will be :
Name
ARUN
SANJAY
SORTING RESULTS
Whenever the SELECT query is executed , the resulting rows appear in a predecided [Link] ORDER BY clause allow
sorting of query result. The sorting can be done either in ascending or descending order, the default is ascending.

The ORDER BY clause is used as :


SELECT <column name> , <column name>….
FROM <tablename>
WHERE <condition>
ORDER BY <column name> ;

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

MODIFYING DATA IN TABLES


you can modify data in tables using UPDATE command of SQL. The UPDATE command specifies the rows to be
changed using the WHERE clause, and the new data using the SET keyword. Syntax of update command is :
UPDATE <tablename>
SET <columnname>=value , <columnname>=value
WHERE <condition> ;

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

DELETING DATA FROM TABLES


To delete some data from tables, DELETE command is used. The DELETE command removes rows from a
table. The syntax of DELETE command is :
DELETE FROM <tablename>
WHERE <condition> ;
For example, to remove the details of those employee from EMPLOYEE table whose grade is A1.
DELETE FROM EMPLOYEE
WHERE GRADE =’A1’ ;

TO DELETE ALL THE CONTENTS FROM A TABLE


DELETE FROM EMPLOYEE ;

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.

[Link]. DELETE COMMAND DROP TABLE COMMAND


1 It is a DML command. It is a DDL Command.
2 This command is used to delete only rows This command is used to delete all the data of the table
of data from a table along with the structure of the table. The table is no
longer recognized when this command gets executed.
3 Syntax of DELETE command is: Syntax of DROP command is :
DELETE FROM <tablename> DROP TABLE <tablename> ;
WHERE <condition> ;

ALTER TABLE COMMAND


The ALTER TABLE command is used to change definitions of existing tables.(adding columns,deleting columns
etc.). The ALTER TABLE command is used for :
1. adding columns to a table
2. Modifying column-definitions of a table.
3. Deleting columns of a table.
4. Adding constraints to table.
5. Enabling/Disabling constraints.

ADDING COLUMNS TO TABLE

To add a column to a table, ALTER TABLE command can be used as per following syntax:

ALTER TABLE <tablename>


ADD <Column name> <datatype> <constraint> ;
e.g. to add a new column ADDRESS to the EMPLOYEE table, we can write command as :

ALTER TABLE EMPLOYEE


ADD ADDRESS VARCHAR(50);
A new column by the name ADDRESS will be added to the table, where each row will contain NULL
value for the new column.
ECODE ENAME GENDER GRADE GROSS ADDRESS
1001 Ravi M E4 50000 NULL
1002 Akash M A1 35000 NULL
1004 Neela F B2 38965 NULL
1005 Sunny M A2 30000 NULL
1006 Ruby F A1 45000 NULL
1009 Neema F A2 52000 NULL

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 :

ALTER TABLE <table name>


CHANGE <old column name> <new column name> <new datatype>;
If Only data type of column need to be changed, then

ALTER TABLE <table name>


MODIFY <column name> <new datatype>;
e.g.1. In table EMPLOYEE, change the column GROSS to SALARY.

ALTER TABLE EMPLOYEE


CHANGE GROSS SALARY INTEGER;
e.g.2. In table EMPLOYEE , change the column ENAME to EM_NAME and data type from VARCHAR(20) to VARCHAR(30).

ALTER TABLE EMPLOYEE


CHANGE ENAME EM_NAME VARCHAR(30);
e.g.3. In table EMPLOYEE , change the datatype of GRADE column from CHAR(2) to VARCHAR(2).

ALTER TABLE EMPLOYEE


MODIFY GRADE VARCHAR(2);

DELETING COLUMNS

To delete a column from a table, the ALTER TABLE command takes the following form :

ALTER TABLE <table name>


DROP <column name>;
e.g. to delete column GRADE from table EMPLOYEE, we will write :
ALTER TABLE EMPLOYEE
DROP GRADE ;

ADDING/REMOVING CONSTRAINTS TO A TABLE


ALTER TABLE statement can be used to add constraints to your existing table by using it in following manner:


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

ALTER TABLE <table name>


ADD FOREIGN KEY (Column name) REFERENCES Parent Table (Primary key of Parent Table);

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 :

[Link]. Constraints Description


1 NOT NULL Ensures that a column cannot have NULL value
2 DEFAULT Provides a default value for a column when none is specified
3 UNIQUE Ensures that all values in a column are different
4 CHECK Makes sure that all values in a column satisfy certain criteria
5 PRIMARY KEY Used to uniquely identify a row in the table
6 FOREIGN KEY Used to ensure referential integrity of the data

NOT NULL CONSTRAINT


By default, a column can hold NULL. It you not want to allow NULL value in a column, then NOT NULL constraint
must be applied on that column. E.g.

CREATE TABLE Customer


( SID integer NOT NULL ,
Last_Name varchar(30) NOT NULL ,
First_Name varchar(30) );

Columns SID and Last_Name cannot include NULL, while First_Name can include NULL.

An attempt to execute the following SQL statement,


INSERT INTO Customer
VALUES (NULL , ‘Kumar’ , ‘Ajay’);
will result in an error because this will lead to column SID being NULL, which violates the NOT NULL constraint
on that column.

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.

CREATE TABLE Student


( Student_ID integer ,
Name varchar(30) ,
Score integer DEFAULT 80);

When following SQL statement is executed on table created above:


INSERT INTO Student
no value has been provided for score field.
VALUES (10 , ‘Ravi’ );

Then table Student looks like the following:

Student_ID Name Score


10 Ravi 80 score field has got the default value

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 :

SID Last_Name First_Name


1 Kumar Ravi
2 Sharma Ajay
3 Devi Raj

The executing the following SQL statement,


INSERT INTO Customer
VALUES (‘3’ , ‘Cyrus‘ , ‘Grace’) ;
will result in an error because the value 3 already exist in the SID column, thus trying to insert another row
with that value violates the UNIQUE constraint.

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

So, attempting to execute the following statement :


INSERT INTO Customer
VALUES (-2 , ‘Kapoor’ , ‘Raj’);

will result in an error because the values for SID must be greater than 0.

PRIMARY KEY CONSTRAINT


- A primary key is used to identify each row in a table. A primary key can consist of one or more fields(column)
on a table. When multiple fields are used as a primary key, they are called a composite key.

- You can define a primary key in CREATE TABLE command through keywords PRIMARY KEY. e.g.

CREATE TABLE Customer


( SID integer NOT NULL PRIMARY KEY,
Last_Name varchar(30) ,
First_Name varchar(30) ) ;

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.

CREATE TABLE Customer


( Branch integer NOT NULL,
SID integer NOT NULL ,
Last_Name varchar(30) ,
First_Name varchar(30),
PRIMARY KEY (Branch , SID) ) ;

FOREIGN KEY CONSTRAINT


- Foreign key is a non key column of a table (child table) that draws its values from primary key of another
table(parent table).
- The table in which a foreign key is defined is called a referencing table or child table. A table to which a
foreign key points is called referenced table or parent table.

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

CREATE TABLE STUDENT


( ROLL_NO integer NOT NULL PRIMARY KEY ,
NAME VARCHAR(30) ,
CLASS VARCHAR(3) );

CREATE TABLE SCORE


( ROLL_NO integer ,
MARKS integer ,
FOREIGN KEY(ROLL_NO) REFERNCES STUDENT(ROLL_NO) ) ;

* Foreign key is always defined in the child table.


Syntax for using foreign key
FOREIGN KEY(column name) REFERENCES Parent_Table(PK of Parent Table);

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.

Q: Create two tables


Customer(customer_id, name)
Customer_sales(transaction_id, amount , customer_id)
Underlined columns indicate primary keys and bold column names indicate foreign key.
Make sure that no action should take place in case of a DELETE or UPDATE in the parent table.

Sol : CREATE TABLE Customer (


customer_id int Not Null Primary Key ,
name varchar(30) ) ;

CREATE TABLE Customer_sales (


transaction_id Not Null Primary Key ,
amount int ,
customer_id int ,
FOREIGN KEY(customer_id) REFERENCES Customer (customer_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION );

Q: Distinguish between a Primary Key and a Unique key in a table.


[Link]. PRIMARY KEY UNIQUE KEY
1. Column having Primary key can’t contain Column having Unique Key can contain
NULL value NULL value
2. There can be only one primary key in Table. Many columns can be defined as Unique key

Q: Distinguish between ALTER Command and UPDATE command of SQL.


[Link]. ALTER COMMAND UPDATE COMMAND
1. It is a DDL Command It is a DML command
2. It is used to change the definition of It is used to modify the data values present
existing table, i.e. adding column, in the rows of the table.
deleting column, etc.
3. Syntax for adding column in a table: Syntax for using UPDATE command:
ALTER TABLE <tablename> UPDATE <Tablename>
ADD <Column name><Datatype> ; SET <Columnname>=value
WHERE <Condition> ;
AGGREGATE / GROUP FUNCTIONS
Aggregate / Group functions work upon groups of rows , rather than on single row, and return one single
output. Different aggregate functions are : COUNT( ) , AVG( ) , MIN( ) , MAX( ) , SUM ( )

Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20
8912 SUR NULL 3000 10

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.

e.g. SELECT COUNT(*)


FROM EMPL ;
Output
COUNT(*)
5

e.g.2 SELECT COUNT(JOB)


FROM EMPL ;
Output
COUNT(JOB)
4

3. MAX( )
This function returns the maximum value from a given column or expression.

e.g. SELECT MAX(SAL)


FROM EMPL ;
Output
MAX(SAL)
9870
4. MIN( )
This function returns the minimum value from a given column or expression.

e.g. SELECT MIN(SAL)


FROM EMPL ;
Output
MIN(SAL)
2985

5. SUM( )
This function returns the sum of values in given column or expression.

e.g. SELECT SUM(SAL)


FROM EMPL ;

Output
SUM(SAL)
30258

GROUPING RESULT – GROUP BY


The GROUP BY clause combines all those records(row) that have identical values in a particular field(column) or a
group of fields(columns).
GROUPING can be done by a column name, or with aggregate functions in which case the aggregate produces a
value for each group.
Table : EMPL

EMPNO ENAME JOB SAL DEPTNO


8369 SMITH CLERK 2985 10
8499 ANYA SALESMAN 9870 20
8566 AMIR SALESMAN 8760 30
8698 BINA MANAGER 5643 20

e.g. Calculate the number of employees in each grade.


SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB ;
Output
JOB COUNT(*)
CLERK 1
SALESMAN 2
MANAGER 1

e.g.2. Calculate the sum of salary for each department.


SELECT DEPTNO , SUM(SAL)
FROM EMPL
GROUP BY DEPTNO ;
Output
DEPTNO SUM(SAL)
10 2985
20 15513
30 8760
e.g.3. find the average salary of each department.
Sol:

** 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 :

SELECT DEPTNO , JOB , COUNT(EMPNO)


FROM EMPL
GROUP BY DEPTNO , JOB ;
Output
DEPTNO JOB COUNT(EMPNO)
10 CLERK 1
20 SALESMAN 1
20 MANAGER 1
30 SALESMAN 1

PLACING CONDITION ON GROUPS – HAVING CLAUSE


- The HAVING clause places conditions on groups in contrast to WHERE clause that places condition on individual
rows. While WHERE conditions cannot include aggregate functions, HAVING conditions can do so.
- e.g. To display the jobs where the number of employees is less than 2,
SELECT JOB, COUNT(*)
FROM EMPL
GROUP BY JOB
HAVING COUNT(*) < 2 ;
Output
JOB COUNT(*)
CLERK 1
MANAGER 1

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.

TRANSACTION CONTROL COMMANDS (TCL)


The TCL of MySQL consists of following commands :

1. BEGIN or START TRANSACTION – marks the beginning of a transaction.


2. COMMIT – Ends the current transaction by saving database changes and starts a new transaction.
3. ROLLBACK – Ends the current transaction by discarding database changes and starts a new transaction.
4. SAVEPOINT – Define breakpoints for the transaction to allow partial rollbacks.
5. SET AUTOCOMMIT – Enables or disables the default auto commit mode
[Type here] [Type here] [Type here]

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

Figure 10.1: A computer network

In a communication network, each device that is a part of a network and


that can receive, create, store or send data to different network routes is
called a node. A node can be a device such as a modem, hub, bridge, switch,
router, digital telephone handset, a printer, a computer or a server.

10.2 EVOLUTION OF NETWORKING


ARPANET: In the 1960s a research project was commissioned by Advanced Research
Projects Agency Network (ARPANET) in the U.S. Department of Defence to connect the academic
and research institutions located at different places for scientific collaborations.
 Few of the milestones in the magnificent journey of evolution of computer networks is
depicted in the timeline shown in Figure 10.3.

1
[Type here] [Type here] [Type here]

10.3 TYPES OF NETWORKS


Based on the geographical area covered and data transfer rate,
computer networks are broadly categorised as:
• PAN ( Personal Area Network)
• LAN (Local Area Network)
• MAN (Metropolitan Area Network)
• WAN (Wide Area Network)

10.3.1 Personal Area Network (PAN)


 It is a network formed by connecting a few personal devices like computers, laptops,
mobile phones, smart phones, printers etc.
 All thesedevices lie within an approximate range of 10 metres.
 A personal area network may be wired or wireless.
 For example, a mobile phone connected to the laptop through USB forms a
wired PAN while two smartphones communicating with each other through
Bluetooth technology form a wireless PAN or WPAN.

10.3.2 Local Area Network (LAN)


 LAN is a network that connects computers, mobile phones, tablet, mouse, printer,
etc., placed at a limited distance.
 The geographical area covered by a LAN can range from a

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.

10.3.3 Metropolitan Area Network (MAN)


 Metropolitan Area Network (MAN) is an extended form ofLAN which
covers a larger geographical area like a city or a town.
 Data transfer rate in MAN also ranges in Mbps, but it is considerably less
as compared to LAN.
 EX: Cable TV network which can be extended up to 30-40 km.
 Sometimes, many LANs are connected together to form MAN.

10.3.4 Wide Area Network (WAN)


 Wide Area Network connects computers and other LANs and MANs, which are
spread across different geographical locations of a country or continents.
 A WAN could be formed by connecting a LAN to other LANs via
wired/wireless media.
 Large business, educational and government organisations connect their
different branches in different locations across the world through WAN.
 The Internet is the largest WAN that connects billions of computers,
smartphones and millions of LANs from different continents

3
[Type here] [Type here] [Type here]

10.4 NETWORK DEVICES


To communicate data through different transmission media and to configure
networks with different functionality different devices are required.

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

10.4.2 Ethernet Card


 Ethernet card, also known as Network Interface Card (NIC card in short)
is a network adapter used to set up a wired network.
It acts as an interface between computer and the network.
 The Ethernet cable connects the computer to the network through NIC.
 Each NIC has a MAC address, which helps in uniquely identifying the
computer on the network.
10.4.3 RJ45
 RJ 45 or Registered Jack-45 is an eight-pin connector that is used
exclusively with Ethernet cables for networking.
 It is a standard networking interface that can be seen at the end of all
network cables.

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.

10.5 NETWORKING TOPOLOGIES


The arrangement of computers and other peripherals in a network is called its topology.
10.5.1 Mesh Topology
 In this networking topology, each communicating device is connected
with every other device in the network as shown in Figure.
This topology is also more secure & more reliable as compared to other
topologies because each cable between two
nodes carries different data.

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)

10.5.3 Bus Topology


 In bus topology, each communicating device connects to a
transmission medium/ single cable, known as bus.
 Data sent from a node are passed on to the bus in both directions. That
means, data can be received by any of the nodes connected to the bus.
 It is cheaper and easier to maintain.
 Both ring and bus topologies are considered to be less secure and less
reliable.

10.5.4 Star Topology


 In star topology, each communicating device is connected to a central node
called as a hub or a switch.
 Star topology is considered very effective, efficient and fast as each device is
directly connected with the central device.
 any failure in a central networking device may lead to the failure of complete
network.

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 IDENTIFYING NODES IN A NETWORKED COMMUNICATION


 Each node in a network should be uniquely identified so that a network
device can identify the sender and receiver and decide a routing path to
transmit data.
 MAC stands for Media Access Control. The MAC address, also known as the
physical or hardware address, is a unique value associated with a network
adapter called a NIC.

10.6.1 MAC Address


 A (Media access Control) address is a hardware identification number that uniquely
identifies each device on a network (assigned to a NIC by the manufacturer).
 MAC stands for Media Access Control. The MAC address, also known as the
physical or hardware address, is a unique value associated with a network
adapter called a NIC.
 Each MAC address is a 12-digit hexadecimal numbers (48 bits in length), of
which the first six digits (24 bits) contain the manufacturer’s ID called
Organisational Unique Identifier (OUI) and the later six digits (24 bits)
represents the serial number assigned to the card by the manufacturer.
A sample MAC address looks like:

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

10.8 INTERNET, WEB AND THE INTERNET OF THINGS


 A worldwide network of interconnected computer networks and devices that transmit
data and media is called as internet.
 The Internet is the global network of computing devices including desktop,
laptop, servers, tablets, mobile phones, other handheld devices, printers,
scanners, routers, switches, gateways, etc.

10.8.1 The World Wide Web (WWW)


 The World Wide Web (WWW) or web in short, is an ocean of information,
stored in the form of trillions of interlinked web pages and web resources.
 Sir Tim Berners-Lee — a British computer scientist invented the revolutionary
World Wide Web in 1990 by defining three fundamental technologies that lead
to creation of web:
 HTML – HyperText Markup Language. It is a language which is used to
design standardised Web Pages so that the Web contents can be read and
understood from any computer.
 URI – Uniform Resource Identifier. It is a unique address or path for each
resource located on the web. It is also known as Uniform Resource Locator
(URL). Every page on the web has a unique URL. Examples are:
[Link]
It contains other information that completes a web address,
as depicted below:

 HTTP – The HyperText Transfer Protocol is a set of rules which is used to


retrieve linked web pages across the web. The more secure and advanced
version is HTTPS.

10.1 DOMAIN NAME SYSTEM

Each computer server hosting a website or web resource is given a name


against its IP address. These names are called the Domain names or hostnames
corresponding to unique IP addresses assigned to each server.

8
[Type here] [Type here] [Type here]
For example, IP addresses and domain names of some websites are as follows:

10.8.1 DNS Server


 Conversion of the domain name of each web server to its corresponding IP
address is called domain name resolution. It is done through a server called
DNS server.
 Thus, when we enter a URL on a web browser, the HTTP protocol
approaches a computer server called DNS server to obtain the IP address
corresponding to that domain name.

 A DNS server may contain the IP address corresponding to a domain or it will


contain the IP address of other DNS servers, where this domain entry can be
searched.

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.

Figure 11.1: A simple network of computing devices

11.2 COMPONENTS OF DATA COMMUNICATION

Communication between two computing devices using a network has


five most important aspects such as sender, receiver, communication medium,
the message to be communicated, and certain rules called protocols to be
followed during communication.

1. Sender: A sender is a computer or any such device which is capable of


sending data over a network.
EX: a computer, mobile phone, smartwatch, walkie- talkie, video recording
device, etc.
1
[Type here] [Type here] [Type here]

2. Receiver: A receiver is a computer or any such device which is capable of


receiving data from the network.
EX: computer, printer, laptop, mobile phone, television, etc.
3. Message: It is the data or information that needs to be exchanged
between the sender and the receiver.

4. Communication media: It is the path through which the


message travels between source and destination also called as
medium or link which is either wired or wireless.
For example, a television cable, telephone cable, ethernet cable,
satellite link, microwaves, etc.

5. Protocols: It is a set of rules that need to be followed by the


communicating parties in order to have successful and reliable
data communication.
EX: Ethernet and HTTP.

11.3 MEASURING CAPACITY OF COMMUNICATION MEDIA


The capacity of a transmission medium/channel is the maximum amount
of signals or traffic that a channel can carry. It is measured in terms of
bandwidth and data transfer rate

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

Mbps=220 bps=1024 Kbps

1 Gbps=230 bps=1024 Mbps


1 Tbps=240 bps=1024 Gbps

11.4 TYPES OF DATA COMMUNICATION


Data communication between different devices are broadly categorised
into 3 types: Simplex communication, Half- duplex communication, and Full-
duplex communication.

2
[Type here] [Type here] [Type here]

11.4.1 Simplex Communication


 It is a one way or unidirectional communication between two devices in which
one device is sender and other one is receiver.
 For example, data entered through a keyboard or audio sent to a speaker are
one way communications.
 One can control fans, lights, fridge, oven etc. while sitting in the office or
driving a car


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.

11.4.3 Full-duplex Communication


 It is two way or bidirectional communication in which both devices can
send and receive data simultaneously
 for example, in our mobile phones and landline telephones.

3
[Type here] [Type here] [Type here]

11.5 SWITCHING TECHNIQUES


Switching m e a n s r o u t i n g data through various nodes in a network. Two
commonly used switching techniques are — Circuit Switching and Packet
Switching.
11.5.1 Circuit Switching
 In circuit switching, before a communication starts, a dedicated path is
identified between the sender and the receiver.
 All packets follow the same path established during the connection.
 EX: In earlier days, when we placed a telephone call, the switching
equipment within the telephone system finds out a physical path or channel
all the way from our telephone at home to the receiver’s telephone.
11.5.2 Packet Switching
 In packet switching, each information or message to be transmitted between
sender and receiver is broken down into smaller pieces, called packets.
 Different packets of the same message may take different routes depending on
availability.
 Each packet has two parts — a header containing the address of the
destination and other information, and the main message part.

11.6 TRANSMISSION MEDIA


 A transmission medium can be anything that can carry signals or data
between the source (transmitter) and destination (receiver).
 Transmission can be classified as guided or unguided.

4
[Type here] [Type here] [Type here]

 In guided transmission, there is a physical link made of wire/cable through


which data in terms of signals are propagated between the nodes. They are
also known as wired media.
 In unguided transmission, data travels in air in terms of electromagnetic waves
using an antenna. They are also known as wireless media.

11.6.1 Wired Transmission Media


 Any physical link that can carry data in the form of signals belongs to the
category of wired transmission media.
 EX:twisted pair, coaxial cable, and fiber optic cable..

A) Twisted Pair Cable:


 A twisted-pair consists of two copper wires twisted like a DNA helical
structure. Both the copper wires are insulated with plastic covers.
 It minimises the effect of electrical interference.
 Twisted pairs are less expensive and most commonly used in telephone lines
and LANs.
 These cables are of two types: Unshielded twisted-pair (UTP) and Shielded
twisted-pair (STP)

(a) UTP (b) STP

Figure 11.9: UTP Cable and STP Cable


B) Coaxial cable:
 Coaxial cable is another type of data transmission medium.
5
[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.

11.6.2 Wireless Transmission Media


 In wireless communication technology, information travels in the form of
electromagnetic signals through air.
 Electromagnetic spectrum of frequency ranging from 3 KHz to 900 THz is
available for wireless communication
 The electromagnetic spectrum range (3KHz to 900THz) can be divided into
4 categories Radio waves, Microwaves, Infrared waves and Visible or Light
waves, according to their frequency ranges.
6
[Type here] [Type here] [Type here]

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.

Microwaves 1. Electromagnetic waves of frequency range 1GHz - 300GHz.


2. Unidirectional, can move in only one direction.
3. Cannot penetrate solid objects such as walls, hills or mountains.
4. Needs line-of-sight propagation
5. Used in point-to-point communication such as radar and satellite.
6. Provide very large information-carrying capacity.

Infrared waves 1. Electromagnetic waves of frequency range 300GHz - 400THz.


2. Very high frequency waves.
3. Cannot penetrate solid objects such as walls.
4. Used for short-distance point-to-point communication such as mobile-
to-mobile, mobile-to-printer, remote-control-to-TV, and Bluetooth-
enabled devices to other devices like mouse, keyboards etc.

11.6.3 Wireless Technologies

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]

 The international organisation IEEE assigns numbers to each different


standards of LAN. The wireless LAN is number as 802.11, and it is
popularly known as Wi-Fi.

 These networks consist of communicating devices such as laptops and


mobile phones, as well as the network device called APs (access points)
which is installed in buildings or floors.

 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

11.7 MOBILE TELECOMMUNICATION TECHNOLOGIES


The architecture of the mobile network has rapidly evolved over the last few
decades.
They are identified as 1G, 2G, 3G, 4G, and 5G.
1. The first generation (1G) -1982.
 It was used to transmit only voice calls.
 The analog signals were used to carry voices between the caller and receiver.
2. The second generation (2G)- 1991.
 Instead of analog signals, voice calls were transmitted in digital form thus
providing improved call quality.
 It also enabled an additional service to send SMS and MMS (Multimedia
messages).
3. The third generation (3G) - around 2001.
 It offered both digital voice and data services.
 3G provided Internet access via the same radio towers that provide voice service
to the mobile phone.
 It facilitated greater voice and data capacity.

4. The fourth generation(4G)-


 It is much faster than 3G and this has revolutionised the field of
telecommunication by bringing the wireless experience to a new level
altogether.
 4G systems support interactive multimedia, voice, video, wireless internet

8
[Type here] [Type here] [Type here]

and other broadband services.


5. The fifth generation or 5G- is currently under development.
 It is expected to be a milestone development for the success of IoT
and Machine to Machine (M2M) communications.
 Machine to machine (M2M) is direct communication between
devices — wired and wireless.
 5G is expected to allow data transfer in Gbps, which is much
faster than 4G.
11.8 PROTOCOL
In communication, Protocol is a set of standard rules that the communicating
parties — the sender, the receiver, and all other intermediate devices need
to follow.

11.8.1 Need for Protocols


 We need protocols for different reasons such as flow control, access
control, addressing, etc.
 Flow control is required when the sender and receiver have different
speeds of sending and receiving the data.
 Access control is required to decide which nodes in a communication
channel will access the link shared among them at a particular instant of
time.

11.8.2 HyperText Transfer Protocol (HTTP)


 HTTP stands for HyperText Transfer Protocol.
 It is the primary protocol used to access the World Wide Web.
 Tim Berners-Lee led the development of HTTP at CERN in 1989.
 The common use of HTTP is between a web browser (client) and a web
server (server).
 For example, whenever we enter the URL http//
[Link] in a browser, it sends HTTP request to the
web-server where [Link] is hosted. The HTTP response
from the web-server fetches and sends the requested Web-
page, which is displayed on your browser.

11.8.3 File Transfer Protocol (FTP)


 File Transfer Protocol (FTP) is the protocol used for transferring files from one
machine to another. Like HTTP, FTP also works on a client-server model.
 File transfer between two systems seems simple and straightforward
because FTP takes care of issues between two communicating devices, such
as:
9
[Type here] [Type here] [Type here]

• use of different conventions while naming files.


• representation of text and data in different formats.
• having different directory structure

11.8.4 Point to Point Protocol (PPP)


 PPP is a communication protocol which establishes a dedicated and direct
connection between two communicating devices.
 This protocol defines how two devices will authenticate each other and
establish a direct link between them to exchange data.
 For example, two routers with direct connection communicate using PPP.

11.8.5 Simple Mail Transfer Protocol (SMTP)


 SMTP is a protocol used for email services. It uses information written on the
message header, and is not concerned with the content of the email message.
 Each email header contains email addresses of recipients.
 The email containing header and body are entered into a queue of outgoing
mails.

11.8.6 Transmission Control Protocol (TCP)/ Internet Protocol (IP)


 TCP/IP stands for Transmission Control Protocol/ Internet Protocol.
 It is a set of standardised rules that uses a client-server model of
communication in which a user or machine (a client) requests a service by a
server in the network.
 The IP protocol ensures that each computer or node connected to the Internet
is assigned an IP address
 TCP ensures that the message or data is broken into smaller chunks, called
IP packets
 TCP guarantees the delivery of packets on the designated IP address. It is
also responsible for ordering the packets so that they are delivered in
sequence.

10
Chapter 12

In this chapter:

 Threats and Prevention


 Malware
 Antivirus
 Spam
 HTTP vs HTTPS
 Firewall
 Cookies
 Hackers and Crackers
 Network Security Threats

Threats and Prevention


 Being alone is the most ideal situation for an individual in terms of security. It applies to
computers as well.
 A computer with no link to an external device or computer is free from the security
threats arising otherwise.
 However, it is not an ideal solution for a human being or a computer to stay aloof in
order to mitigate any security threats, as the world at present is on its way to become
fully connected.
 This connectedness of various devices and computers has brought into our focus the
various network threats and its prevention
Malware
 Malware is a short term used for MALicious softWARE.
 It is any software developed with an intention to damage hardware devices, steal data,
or cause any other trouble to the user.
 Various types of malware have been created from time-to-time, and large-scale damages
have been inflicted.
 Many of these malware programs have been identified and counter measures have been
initiated.
 However, different types of malware keep on coming on a regular basis that compromise
the security of computer systems and cause intangible damages.
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.

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.

(A) Online Virtual Keyboard Vs On-Screen Keyboard


 The names “on-screen” and “virtual” keyboard refer to any software-based
keyboard and are sometimes used interchangeably.
 But, there exists a notable difference between “on-screen” and “online
virtual” keyboards. Both types of keyboards may look the same, but the
difference is in terms of the layout or ordering of the keys.

Modes of Malware distribution


A malware once designed, can take many routes to reach your computer. Some of the common
distribution channels for malware are:

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

Methods of Malware Identification used by Antivirus

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.

Data mining techniques


 This method employs various data mining and machine learning techniques to classify
the behaviour of a file as either benign or malicious.

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.

Threats due to Cookies


 Usually, cookies are used for enhancing the user’s browsing experience and do not infect
your computer with malware.
 However, some malware might disguise as cookies e.g. “supercookies”.
 There is another type of cookie known as “Zombie cookie” that gets recreated after
being deleted.
 Some third-party cookies might share user data without the consent of the user for
advertising or tracking purposes.

Hackers and Crackers


Hackers and crackers are people having a thorough knowledge of the computer systems,
system software (operating system), computer networks, and programming.
White Hats:
 Ethical Hacker If a hacker uses its knowledge to find and help in fixing the security flaws
in the system, its termed as White Hat hacker.
 These are the hackers with good intentions.
 They are actually security experts. Organizations hire ethical or white hat hackers to
check and fix their systems for potential security threats and loopholes.
 Technically, white hats work against black hats.
Black Hats:
 Crackers If hackers use their knowledge unethically to break the law and disrupt security
by exploiting the flaws and loopholes in a system, then they are called black hat hackers.
Grey Hats:
 The distinction between different hackers is not always clear.
 There exists a grey area in between, which represents the class of hackers that are
neutral, they hack systems by exploiting its vulnerabilities, but they don’t do so for
monetary or political gains.
 The grey hats take system security as a challenge and just hack systems for the fun of it.

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.

(A) Asymmetric Routing


The attacker tends to avoid detection by sending the intrusion packets through multiple
paths, thereby bypassing the network intrusion sensors.
(B) Buffer Overflow Attacks
In this attack, the attacker overwrites certain memory areas of the computers within the
network with code (set of commands) that will be executed later when the buffer
overflow (programming error) occurs. Once the malicious code is executed, an attacker
can initiate a DoS attack or gain access to the network.
(C) Traffic Flooding
It is one of the most trivial methods of network intrusion. It involves flooding the
network intrusion detection system with message packets. This huge load leaves the
network detection system incapable of monitoring the packets adequately. The hacker
takes advantage of this congested and chaotic network environment to sneak into the
system undetected.

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.

APPROACHES FOR S OLVING P ROJECTS


The approach followed for the development and completion of a project plays a pivotal role
in project based learning. There are several approaches to execute a project such as modular
approach, top down approach and bottom up approach.
Different steps involved in project based learning (Figure 13.1) are:
1. Identification of a project: The project idea may come through any real-life
situation. For example, one could think of doing a project for organizing a seminar.
2. Defining a plan: Normally for any kind of project, there are several project members
involved in it. One project leader has to be identified. The roles of proje ct leader and
each project member have to be clearly defined.
3. Fixing of a time frame and processing: Every project is a time relevance project. A
student must understand the importance of time frame for completion of the project.
Identification of Defining a
Project Plan

Fixing timeframe Guidance and


and processing Monitoring

Outcome
of project

Figure 1:Steps in project based learning

4. Providing guidance and monitoring a project: Many times, the participants in


the project get stuck up with a particular process and it becomes impossible to
proceed further.

5. Outcome of a project: One needs to understand thoroughly the outcome of a project.


The outcome can be single, or it can be multiple. The output of a project can be peer
reviewed and can be modified as per the feedback from the guide teacher or other
users.

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.

(A) Communicate with Others


When a group of individuals perform one job, it is necessary to have effective communication between
the members of the team. Such communication can be done via e-mails, telephones or by arranging group
meetings.
(B) Listen to Others
It is necessary to understand the ideas of others while executing a job together. This can be achieved
when the team members listen to each other in group meetings and follow steps that are agreed upon.

(C) Share with Others


Ideas, images and tools need to be shared with each other in order to perform a job. Sharing is an
important component of teamwork
(D) Respect for Others
Every member of the team must be treated respectfully. All the thoughts and ideas that are put forth in the
group meetings may be respected and duly considered.
(E) Help Others
A helping hand from every member is a key to success. Sometimes help from people who are not a part of
the team is also obtained in order to accomplish a job.

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

Project Title 1: Automation of Order Processing in a Restaurant

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.

Project Title 2: Development of a Puzzle

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.

You might also like