STD 12th Computer Books
STD 12th Computer Books
org
GOVERNMENT OF TAMILNADU
HIGHER SECONDARY
SECOND YEAR
COMPUTER SCIENCE
Content Creation
The wise
possess all
II
HOW
This book does not require TO USE
prior knowledge in computer
Technology
THE BOOK
Each unit comprises of simple
activities and demonstrations which can be done by
the teacher
and also students.
Technical terminologies are listed in glossary for easy understanding
The “ Do you know?” boxes enrich the knowledge of reader with
additional information
Workshops are introduced to solve the exercises using software
applications
QR codes are used to link supporting additional
materials in digital form
How to get connected to QR Code?
o Download the QR code scanner from the google play store/
apple app store into your smartphone
o Open the QR code scanner application
o Once the scanner button in the application is clicked, camera opens
www.tntextbooks.org
III
Centre for Development of Advanced Computing https://www.cdac.in/ Artificial Intelligence Database Management
Indian Computing Olympiad https://www.iarcs.org.in/inoi Information Management Systems
International Olympiad of Informatics https://ioinformatics.org and Data Analytics Fundamentals of Algorithms
Microsoft certification exams https://www.microsoft.com/en-in/learning/exam-list.aspx Algorithms Graphics
National Cyber Olympiad http://www.sofworld.org/nco Applied Computer Science Machine Learning
Big Data Analytics Mobile and Web Computing
National Institute of Electronics & Information Technology http://www.nielit.gov.in/
Bio Informatics Mobile Device Programming
National Programme on Technology Enhanced Learning https://nptel.ac.in/
Cloud Computing Modern Programming Practices
Compiler Design & Modern Web Applications
Construction Operating Systems
After Completing +2 Computer and Network Parallel Programming
Security Robotics
Arts & Science BSc Courses | Animation & Multimedia
Computer Networks Software Engineering
Computer Science | Geography
Computer Security Software Engineering
Journalism / Mass Media Communication | Library Science
Computer Simulation Software Testing
Maths / Physics / Chemistry / Statistics | Psychology/ Sociology
Cyber Security Systems Analysis and Design
Social Work | Visual Communication | B.C.A. COMPUTER Data Analytics Web Application Architecture
SCIENCE Data Mining Web Application Programming
IV
Technical Diploma
Scholarships for graduate
Diploma in Engineering and post graduate courses
www.tntextbooks.org
20-02-2019 15:06:40
www.tntextbooks.org
Index.indd 5
After PG courses
A Competitive Exams for Govt. Jobs
MPhil –Computer Science | PhD – Computer Science Airforce Common Admission Test – AFCAT | Army Education Officer Entry- AEC
Combined Defence Services –CDS | Defence Service Staff College, Nilgiris
Following are the latest topics for PhD in computer science:
Indian Defence Services | Indian Military Academy
BioInformatics and Computational Biology
Judge Advocate General Department-JAG | NCC Entry | Railway Board Examination
Capturing and Visualizing Persona Through Faces
SSC NAVY (Pilot/Observer) | SSC Tech Entry – Officers Training School
Comprehensive analysis of RNA sequencing experiments Staff Selection Examination | Tamil Nadu Public Service Commission
Designing and Evaluating Information Gathering Robots Teacher Recruitment Board | Technical Graduate Course –TGC
Digital Pathology: Diagnostic Errors, Territorial Army | Union Public Service Examination | Women Special Entry Scheme
Viewing Behavior and Image Characteristics
Embedded Systems | Game Theory | Graph Theory
Graphics and Visualization | Human Computer Interaction – HCI Computer Related Jobs
Improving Fault Tolerance and Performance of Data Center Networks
Increasing Access to Computer Science for Blind Students Applications Software Developer | Big Data Analysts
In-situ Semantic 3D Modeling Cloud Computing Programmer | College/ University Faculty
Intelligent Crowdsourcing for Natural Language Computer Programmer | Computer Teacher
Learning and Other AI Applications Computer Vocational Instructor | Computer Information Research Scientist
Learning Robust Tractable Models for Vision COMPUTER Computer Information Systems Manager | Computer Network Architect
V
SCIENCE Computer Support Specialist | Computer System Analysts
Manipulators And Manipulation In High Dimensional Spaces
Data Mining Specialist | Database Administrator
New Algorithmic Tools for Distributed Similarity Search
Information Security Analysts | Market Research Analysts
Reproducible measurements of web security and privacy Network & Computer System Administrator | Research Assistant
The Security and Privacy of Web and Mobile Advertising Systems Software Developer | User Interface Designer | Web Developer
Towards More Practical Reinforcement Learning,
www.tntextbooks.org
20-02-2019 15:06:41
www.tntextbooks.org
www.tntextbooks.org
Table of Contents
Computer Science-II Year
Page.
UNIT No. Chapter Title
No
UNIT- I 1 Function 1
Problem 2 Data Abstraction 11
Solving 3 Scoping 21
Techniques 4 Algorithmic Strategies 31
5 Python -Variables and Operators 47
CHAPTER 1
Unit I
FUNCTION
After the completion of this chapter, the A function is a unit of code that is
student will be able to: often defined within a greater code structure.
Specifically, a function contains a set of
• Understand Function Specification.
code that works on many kinds of inputs,
• Parameters (and arguments). like variants, expressions and produces a
• Interface Vs Implementation. concrete output.
• Pure functions. 1.2.1 Function Specification
• Side - effects (impure functions). Let us consider the example a:= (24).
a:= (24) has an expression in it but (24)
1.1 Introduction is not itself an expression. Rather, it is a
The most important criteria in function definition. Definitions bind values
writing and evaluating the algorithm is the to names, in this case the value 24 being
time it takes to complete a task. To have bound to the name ‘a’. Definitions are not
a meaningful comparison of algorithms, expressions, at the same time expressions are
the duration of computation time must be also not treated as definitions. Definitions
independent of the programming language, are distinct syntactic blocks. Definitions can
compiler, and computer used. As you have expressions nested inside them, and
aware that algorithms are expressed using vice-versa.
statements of a programming language. If a 1.2.2 Parameters (and arguments)
bulk of statements to be repeated for many
numbers of times then subroutines are used Parameters are the variables in a
to finish the task. function definition and arguments are
the values which are passed to a function
Subroutines are the basic building definition.
blocks of computer programs. Subroutines
1. Parameter without Type
are small sections of code that are used to
perform a particular task that can be used Let us see an example of a function
www.tntextbooks.org
3 Function
let min 3 x y z :=
ENGINE if x < y then
if x < z then x else z
else
if y < z then y else z
getSpeed
1.4 Pure functions
Internally, the engine of the car is The above function square is a pure
doing all the things. It's where fuel, air, function because it will not give different
pressure, and electricity come together to results for same input.
create the power to move the vehicle. All of
There are various theoretical
these actions are separated from the driver,
advantages of having pure functions. One
who just wants to go faster. Thus we separate
advantage is that if a function is pure, then
interface from implementation.
if it is called several times with the same
Let us see a simple example, consider arguments, the compiler only needs to
the following implementation of a function actually call the function once. Lt’s see an
that finds the minimum of its three example
arguments:
let i: = 0;
if i <strlen (s) then
www.tntextbooks.org
let y: = 0
1.4.1 Impure functions
(int) inc (int) x
The variables used inside the
y: = y + x;
function may cause side effects though the
return (y)
functions which are not passed with any
arguments. In such cases the function is
In the above example the value of y
called impure function. When a function
get changed inside the function definition
depends on variables or functions outside
due to which the result will change each
of its definition block, you can never be
time. The side effect of the inc () function is
sure that the function will behave the same
it is changing the data of the external visible
every time it’s called. For example the
variable ‘y’. As you can see some side effects
mathematical function random() will give
are quite easy to spot and some of them may
different outputs for the same function call.
tricky. A good sign that our function impure
let Random number (has side effect) is that it doesn’t take any
arguments and it doesn’t return any value.
let a := random()
if a > 10 then From all these examples and
return: a definitions what we can understand about
www.tntextbooks.org
5 Function
monochromatize (a, b, c)
Now let’s see the example of a pure
function to determine the greatest common
-- inputs : a = A, b = B, c = C, a = b
divisor (gcd) of two positive integer numbers.
-- outputs : a = b = 0, c = A+B+C
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a;; In each iterative step, two chameleons
output of the two types (equal in number) meet and
gcd 13 27;; change their colors to the third one. For
- : int = 1 example, if A, B, C = 4, 4, 6, then the series
gcd 20536 7826;; of meeting will result in
- : int = 2
iteration a b c
In the above example program ‘gcd’ is
the name of the function which recursively 0 4 4 4
called till the variable ‘b’ becomes ‘0’.
1 3 3 8
Remember b and (a mod b) are two
arguments passed to ‘a’ and ‘b’ of the gcd 2 2 2 10
function.
www.tntextbooks.org
3 1 1 12
4 0 0 14
Points to remember:
• Algorithms are expressed using statements of a programming language
• Subroutines are small sections of code that are used to perform a particular task that
can be used repeatedly
• A function is a unit of code that is often defined within a greater code structure
• A function contains a set of code that works on many kinds of inputs and produces a
concrete output
• Definitions are distinct syntactic blocks
• Parameters are the variables in a function definition and arguments are the values
which are passed to a function definition through the function definition.
• When you write the type annotations the parentheses are mandatory in the function
definition
• An interface is a set of action that an object can do
• Interface just defines what an object can do, but won’t actually do it
• Implementation carries out the instructions defined in the interface
• Pure functions are functions which will give exact result when the same arguments
are passed
• The variables used inside the function may cause side effects though the functions
www.tntextbooks.org
which are not passed with any arguments. In such cases the function is called impure
function
7 Function
Hands on Practice
Evaluation
Part - I
Choose the best answer (1 Mark)
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) Curly braces (B) Parentheses (C) Square brackets (D) indentations
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
www.tntextbooks.org
10. The functions which cause side effects to the arguments passed are called
(A) impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
Part - II
9 Function
Part - IV
REFERENCES
www.tntextbooks.org
CHAPTER 2
Unit I
DATA ABSTRACTION
11
2.3 constructors and selectors Notice that you don’t need to know
how these functions were implemented. You
Constructors are functions that are assuming that someone else has defined
build the abstract data type. Selectors are them for us.
functions that retrieve information from
It’s okay if the end user doesn’t know
the data type.
how functions were implemented. However,
For example, say you have an abstract the functions still have to be defined by
data type called city. This city object will someone.
hold the city’s name, and its latitude and
Let us identify the constructors and
longitude. To create a city object, you’d use a
selectors in the above code
function like
As you already know that
city = makecity (name, lat, lon) Constructors are functions that build the
abstract data type. In the above pseudo code
To extract the information of a city
the function which creates the object of the
object, you would use functions like
city is the constructor.
• getname(city) city = makecity (name, lat, lon)
• getlat(city)
Here makecity (name, lat, lon) is the
• getlon(city) constructor which creates the object city.
The following pseudo code will (name, lat, lon) value passed as parameter
compute the distance between two city
objects:
make city ( )
distance(city1, city2):
lt1, lg1 := getlat(city1), getlon(city1)
city
lt2, lg2 := getlat(city2), getlon(city2)
return ((lt1 - lt2)**2 + (lg1 - lg2)**2))1/2 lat lon
In the above code read distance(), Fig 1 constructor
getlat() and getlon() as functions and read
lt as latitude and lg longitude. Read := as Selectors are nothing but the
“assigned as” or “becomes” functions that retrieve information from the
data type. Therefore in the above code
lt1, lg1 := getlat(city1), getlon(city1)
• getname(city)
is read as lt1 becomes the value of • getlat(city)
www.tntextbooks.org
city value passed as parameter city value passed as parameter city value passed as parameter
should use data in such a way, as to make Actually dividing integers produces a float
as few assumptions about the data as approximation, losing the exact precision of
possible. At the same time, a concrete data integers.
13 Data Abstraction
Representing Rational Numbers Using access the first element with nums[0] and
List the second with nums[1].
You can now represent a rational
number as a pair of two integers in pseudo
15 Data Abstraction
As you already know that List allow but such a representation doesn't explicitly
data abstraction in that you can give a name specify what each part represents.
to a set of memory cells. For instance, in the
game Mastermind, you must keep track of For this problem instead of using a
a list of four colors that the player guesses. list, you can use the structure construct (In
Instead of using four separate variables OOP languages it's called class construct)
(color1, color2, color3, and color4) you can to represent multi-part objects where each
use a single variable ‘Predict’, e.g., part is named (given a name). Consider the
following pseudo code:
Predict =['red', 'blue', 'green', 'green']
class Person:
What lists do not allow us to do
creation( )
is name the various parts of a multi- item
object. In the case of a Predict, you don't firstName := " "
really need to name the parts: lastName := " "
id := " "
using an index to get to each color suffices.
email := " "
But in the case of something more
complex, like a person, we have a multi- The new data type Person is pictorially
item object where each 'item' is a named represented as
thing: the firstName, the
creation ( )
function belonging to the new datatype
}
first Name
email
www.tntextbooks.org
The class (structure) construct So far, you've seen how a class defines
defines the form for multi-part objects that a data abstraction by grouping related data
represent a person. Its definition adds a new items. A class is not just data, it has functions
data type, in this case a type named Person. defined within it. We say such functions are
Once defined, we can create new variables subordinate to the class because their job is
(instances) of the type. In this example to do things with the data of the class, e.g.,
Person is referred to as a class or a type, to modify or analyze the data of a Person
while p1 is referred to as an object or an object.
instance. You can think of class Person as a Therefore we can define a class as
cookie cutter, and p1 as a particular cookie. bundled data and the functions that work
Using the cookie cutter you can make many on that data. From All the above example
cookies. Same way using class you can create and explanation one can conclude the
many objects of that type. beauty of data abstraction is that we can
treat complex data in a very simple way.
Points to remember:
• Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by
a set of value and a set of operations.
• The definition of ADT only mentions what operations are to be performed but not
how these operations will be implemented.
• ADT does not specify how data will be organized in memory and what algorithms
will be used for implementing the operations
• Constructors are functions that build the abstract data type.
• Selectors are functions that retrieve information from the data type.
• Concrete data types or structures (CDT's) are direct implementations of a relatively
simple concept.
www.tntextbooks.org
• Abstract Data Types (ADT's) offer a high level view (and use) of a concept independent
of its implementation.
17 Data Abstraction
Points to remember:
• A concrete data type is a data type whose representation is known and in abstract data
type the representation of a data type is unknown
• Pair is a compound structure which is made up of list or Tuple
• List is constructed by placing expressions within square brackets separated by commas
• The elements of a list can be accessed in two ways. The first way is via multiple
assignment and the second method is by the element selection operator
• Bundling two values together into one can be considered as a pair
• List does not allow to name the various parts of a multi-item object.
Evaluation
Part - I
Part - II
Part - III
19 Data Abstraction
Part - IV
Reference Books
1. Data structure and algorithmic thinking with python by narasimha karumanchi
2. sign and analysis of algorithms by s sridhar
3. Data Structures and Algorithms in Python by Goodrich, Tamassia & Goldwasser
4. https://www.tutorialspoint.com
www.tntextbooks.org
CHAPTER 3
Unit I
SCOPING
21
2. a:=7
for scope resolution. The scopes are listed
When you try to display the value of below in terms of hierarchy (highest to
a outside the procedure the program flags lowest).
BUILT-IN
GLOBAL
ENCLOSED
LOCAL
2. a:=7 7
Disp( ):
3. print a a:=7
print a
4. Disp() Disp ( )
www.tntextbooks.org
On execution of the above code the variable a displays the value 7, because it is defined
and available in the local scope.
23 Scoping
2. Disp(): a:=10 7
Disp( )
3. a:=7 a:=7 10
print a
4. print a Disp 1( ):
print a
5. Disp()
6. print a
On execution of the above code the variable a which is defined inside the function
displays the value 7 for the function call Disp() and then it displays 10, because a is defined in
global scope.
3.4.3. Enclosed Scope
All programming languages permit functions to be nested. A function (method) with
in another function is called nested function. A variable which is declared inside a function
which contains another function definition with in it, the inner function can also access the
variable of the outer function. This scope is called enclosed scope.
When a compiler or interpreter search for a variable in a program, it first search Local,
and then search Enclosing scopes. Consider the following example
2. a:=10 10
Disp( )
3. Disp1(): a:=10 10
Disp 1( ):
print a
4. print a
Disp 1( ):
5. Disp1() print a
Disp( )
6. print a
www.tntextbooks.org
7. Disp()
In the above example Disp1() is defined with in Disp(). The variable ‘a’ defined in Disp()
can be even used by Disp1() because it is also a member of Disp().
3.4.4. Built-in Scope
Finally, we discuss about the widest scope. The built-in scope has all the names that are
pre-loaded into the program scope when we start the compiler or interpreter. Any variable or
module which is defined in the library functions of a programming language has Built-in or
module scope. They are loaded as soon as the library files are imported to the program.
Disp( )
Disp 1( ):
print a
Disp 1( ):
print a
Disp( )
Normally only Functions or modules come along with the software, as packages.
Therefore they will come under Built in scope.
25 Scoping
3.5.2 The benefits of using modular oriented languages, such as C++ and Java,
programming include control the access to class members by
• Less code to be written. public, private and protected keywords.
Private members of a class are denied access
• A single procedure can be developed for from the outside the class. They can be
reuse, eliminating the need to retype the handled only from within the class.
code many times.
Public members (generally methods
• Programs can be designed more easily
declared in a class) are accessible from
because a small team deals with only a
outside the class. The object of the same class
small part of the entire code.
is required to invoke a public method. This
• Modular programming allows many arrangement of private instance variables
programmers to collaborate on the same and public methods ensures the principle of
application. data encapsulation.
• The code is stored across multiple files. Protected members of a class are
• Code is short, simple and easy to accessible from within the class and are also
understand. available to its sub-classes. No other process
• Errors can easily be identified, as they is permitted access to it. This enables specific
are localized to a subroutine or function. resources of the parent class to be inherited
by the child class.
• The same code can be used in many
applications. Python doesn't have any mechanism
• The scoping of variables can easily be that effectively restricts access to any instance
controlled. variable or method. Python prescribes a
convention of prefixing the name of the
3.5.3 Access Control variable or method with single or double
Access control is a security technique underscore to emulate the behaviour of
that regulates who or what can view or use protected and private access specifiers.
resources in a computing environment.
All members in a Python class are
It is a fundamental concept in security
public by default, whereas by default in C++
that minimizes risk to the object. In other
and java they are private. Any member can be
words access control is a selective restriction
accessed from outside the class environment
of access to data. IN Object oriented
in Python which is not possible in C++ and
programming languages it is implemented
java.
through access modifiers. Classical object-
www.tntextbooks.org
Points to remember:
• Scope refers to the visibility of variables, parameters and functions in one part of a
program to another part of the same program.
• The process of binding a variable name with an object is called mapping.= (equal to
sign) is used in programming languages to map the variable and object.
• Namespaces are containers for mapping names of variables to objects.
• The scope of a variable is that part of the code where it is visible.
• The LEGB rule is used to decide the order in which the scopes are to be searched for
scope resolution.
• Local scope refers to variables defined in current function.
• A variable which is declared outside of all the functions in a program is known as
global variable.
• A function (method) with in another function is called nested function.
• A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
• Built-in scope has all the names that are pre-loaded into program scope when we start
the compiler or interpreter.
• A module is a part of a program. Programs are composed of one or more independently
developed modules.
• The process of subdividing a computer program into separate sub-programs is called
Modular programming.
• Access control is a security technique that regulates who or what can view or use
resources in a computing environment. It is a fundamental concept in security that
minimizes risk to the object.
• Public members (generally methods declared in a class) are accessible from outside
the class.
• Protected members of a class are accessible from within the class and are also available
to its sub-classes
• Private members of a class are denied access from the outside the class. They can be
handled only from within the class.
• Python prescribes a convention of prefixing the name of the variable/method with
single or double underscore to emulate the behaviour of protected and private access
specifiers.
• C++ and Java, control the access to class members by public, private and protected
keywords
• All members in a Python class are public by default whereas by default in C++ and java
all members are private.
www.tntextbooks.org
27 Scoping
Hands on Practice
1. Observe the following diagram and Write the pseudo code for the following
sum( )
num 1:=20
sum1( )
num 1:=nim 1 + 10
sum2( )
num 1: = num 1 + 10
sum2( )
sum1( )
num1:=10
sum( )
print num 1
Evaluation
Part - I
Part - II
Part - III
29 Scoping
Part - IV
REFERENCES
CHAPTER 4
Unit I
ALGORITHMIC STRATEGIES
31
33 Algorithmic Strategies
Analysis of an algorithm usually deals with gives the running time and/or the storage
the running and execution time of various space required by the algorithm in terms of
operations involved. The running time of n as the size of input data.
an operation is calculated as how many
programming instructions executed per 4.2.1 Time Complexity
operation. The Time complexity of an algorithm
Analysis of algorithms and is given by the number of steps taken by the
performance evaluation can be divided into algorithm to complete the process.
two different phases:
4.2.2. Space Complexity
1. A Priori estimates: This is a theoretical Space complexity of an algorithm
performance analysis of an algorithm. is the amount of memory required to run
Efficiency of an algorithm is measured to its completion. The space required by
by assuming the external factors. an algorithm is equal to the sum of the
following two components:
2. A Posteriori testing: This is called
performance measurement. In this A fixed part is defined as the total
analysis, actual statistics like running space required to store certain data and
time and required for the algorithm variables for an algorithm. For example,
executions are collected. simple variables and constants used in an
algorithm.
An estimation of the time and
space complexities of an algorithm A variable part is defined as the
for varying input sizes is called total space required by variables, which sizes
algorithm analysis. depends on the problem and its iteration.
For example: recursion used to calculate
factorial of a given value n.
4.2 Complexity of an
Algorithm 4.3 Efficiency of an algorithm
maximum memory space required by the we wish to minimize resource usage. The
algorithm. important resources such as time and space
The complexity of an algorithm f (n) complexity cannot be compared directly,
so time and space complexity could be tradeoff is a way of solving in less time by
considered for an algorithmic efficiency. using more storage space or by solving
a given algorithm in very little space by
4.3.1 Method for determining Efficiency spending more time.
(best-case).
4.3.2 Space-Time tradeoff
A space-time or time-memory
35 Algorithmic Strategies
index 0 1 2 3 4
values 10 12 20 25 30
Example 1:
Input: values[] = {5, 34, 65, 12, 77, 35}
target = 77
Output: 4
Example 2:
Input: values[] = {101, 392, 1, 54, 32, 22, 90, 93}
target = 200
Output: -1 (not found)
10 20 30 40 50 60 70 80 90 99
2. When a match is found, display success
0 1 2 3 4 5 6 7 8 9
message with the index of the element
matched.
37 Algorithmic Strategies
Now we compare the value stored next or right side of the element, move
at location 5 with our search element. We to the next element. Go to Step 1 and
found that it is a match. repeat until end of the index is reached.
Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a pictorial
representation of how bubble sort will sort the given array.
15>11
15 11 16 12 14 13
So interchange
15>16
15 11 16 12 14 13
No swapping
16>12
11 15 16 12 14 13
So interchange
16>14 11 15 12 16 14 13
So interchange
16>13
11 15 12 14 16 13
So interchange
11 15 12 14 13 16
The above pictorial example is for iteration-1. Similarly, remaining iteration can be
done. The final iteration will give the sorted array.
At the end of all the iterations we will get the sorted values in an array as given below:
11 12 13 14 15 16
This algorithm repeatedly selects the next-smallest element and swaps in into the right
place for every pass. Hence it is called selection sort.
www.tntextbooks.org
Pseudo code
1. Start from the first element i.e., index-0, we search the smallest element in the array, and
replace it with the element in the first position.
39 Algorithmic Strategies
2. Now we move on to the second element 4. This is repeated, until the array is
position, and look for smallest element completely sorted.
present in the sub-array, from starting
Let's consider an array with values {13, 16,
index to till the last index of sub - array.
11, 18, 14, 15}
3. Now replace the second smallest
identified in step-2 at the second position Below, we have a pictorial representation of
in the or original array, or also called first how selection sort will sort the given array.
position in the sub array.
11 13 16 14 14 14
18 18 18 18 15 15
14 14 14 16 16 16
15 15 15 15 18 18
In the first pass, the smallest element will be Finally we will get the sorted array
11, so it will be placed at the first position. end of the pass as shown above diagram.
Step 3 − Compare with all elements in the Step 5 − Insert the value
sorted sub-list
Step 6 − Repeat until list is sorted
Step 4 − Shift all the elements in the sorted
sub-list that is greater than the value to be
sorted
Assume 44 is a soted
44 16 83 07 67 21 34 45 10
list of 1 item
16 44 83 07 67 21 34 45 10 inserted 16
16 44 83 07 67 21 34 45 10 inserted 83
07 16 44 83 67 21 34 45 10 inserted 07
07 16 44 67 83 21 34 45 10 inserted 67
07 16 21 44 67 83 34 45 10 inserted 21
07 16 21 34 44 67 83 45 10 inserted 34
07 16 21 34 44 45 67 83 10 inserted 45
07 10 16 21 34 44 45 67 83 inserted 10
At the end of the pass the insertion algorithm will try to check the results of
sort algorithm gives the sorted output in the previously solved sub-problems. The
ascending order as shown below: solutions of overlapped sub-problems are
combined in order to get the better solution.
07 10 16 21 34 44 45 67 83
Steps to do Dynamic programming
4.6. Dynamic programming
• The given problem will be divided into
smaller overlapping sub-problems.
Dynamic programming is an
algorithmic design method that can be • An optimum solution for the given
used when the solution to a problem can problem can be achieved by using result
be viewed as the result of a sequence of of smaller sub-problem.
decisions. Dynamic programming approach
• Dynamic algorithms uses Memoization.
is similar to divide and conquer. The given
problem is divided into smaller and yet
smaller possible sub-problems. Note
Memoization or memoisation
Dynamic programming is used
is an optimization technique used
whenever problems can be divided into
primarily to speed up computer
similar sub-problems. so that their results
programs by storing the results of
can be re-used to complete the process.
www.tntextbooks.org
41 Algorithmic Strategies
Points to remember:
• Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by
a set of value and a set of operations.
• The definition of ADT only mentions what operations are to be performed but not
how these operations will be implemented.
• ADT does not specify how data will be organized in memory and what algorithms
will be used for implementing the operations
• Constructors are functions that build the abstract data type.
• Selectors are functions that retrieve information from the data type.
• Concrete data types or structures (CDT's) are direct implementations of a relatively
simple concept.
• Abstract Data Types (ADT's) offer a high level view (and use) of a concept independent
of its implementation.
• A concrete data type is a data type whose representation is known and in abstract data
www.tntextbooks.org
Points to remember:
• List in is constructed by placing expressions within square brackets separated by
commas
• The elements of a list can be accessed in two ways. The first way is via multiple
assignment and the second method is by the element selection operator
• Bundling two values together into one can be considered as a pair
• List does not allow to name the various parts of a multi-item object.
Evaluation
Part - I
43 Algorithmic Strategies
Part - II
1. What is an Algorithm?
2. Define Pseudo code.
3. Who is an Algorist?
4. What is Sorting?
5. What is searching? Write its types.
Part - III
Part - IV
Reference Books
Web References
www.wickipedia.org
1. Create an algorithm for grading systems of your class student’s Quarterly examination
marks by satisfying all necessary conditions.
www.tntextbooks.org
45 Algorithmic Strategies
This is the question that is fretting The above statistical data has
the minds of teachers and students. maintained its grip with Python scoring
The present book is organized in 100 and C++ language stands second
such a way that even a novice reader can nipping at its heels with a 99.7 score.
grasp and work on python programming. Python being popular is used by a number
Testimonies of tech giants like Google, Instagram,
Pinterest, Yahoo, Disney, IBM, Nokia etc.
• "Python has been an important part
1. Python 100.0
of Google since the beginning and
2. C++ 99.7
remains so as the system grows and 3. Java 97.5
evolves. Today dozens of Google 4. C 96.7
engineers use Python, and we're 5. C# 89.4
looking for more people with skills 6. PHP 84.9
in this language." -- Peter Norvig, 7. R 82.8
director of search quality at Google, 8. JavaScript 82.6
Inc. 9. Go 76.4
10. Assembly 74.1
• "Python is fast enough for our
site and allows us to produce Many businesses are advised to choose
maintainable features in record times, Python for the following reasons:-
with a minimum of developers," • Easy syntax and readability
-- Cuong Do, Software Architect, • High level scripting language with
YouTube.com oops
• famous for enormous functions, add-
Python’s popularity has seen on modules, libraries, frameworks and
a steady and unflagging growth over tool-kits.
the recent years. Today, familiarity • Built-in functions supports scientific
with Python is an advantage for every computing.
programmer, as Python has infiltrated With the advent of computers,
every niche and has useful roles to play in there have been significant changes in the
any software solution. way we work in almost all the fields. The
Python has experienced an computerization has helped to improve
productivity and accelerate decision
impressive growth as compared to the
making in every organization. Even for
other languages. The IEEE Spectrum individuals, be it engineers, doctors,
www.tntextbooks.org
CHAPTER 5
Unit II
PYTHON VARIABLES AND OPERATORS
Learning Objectives
5.1 Introduction
47
(Or)
the prompt on screen means IDLE is working in interactive mode. Now let us try as a simple
calculator by using a simple mathematical expressions.
Example 1: Example 2:
>>> 5 + 10 >>>print (“Python Programming Language”)
15 Python Programming Language
>>>x=10
>>> 5 + 50 *10
>>>y=20
505 >>>z=x + y
>>> 5 ** 2 >>>print (“The Sum”, z)
25 The Sum = 30
b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)
www.tntextbooks.org
(3) In the Save As dialog box, select the location where you want to save your Python code,
and type the file name in File Name box. Python files are by default saved with extension
.py. Thus, while creating Python scripts using Python Script editor, no need to specify
the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5
a=100
b=350
c=a+b
print ("The Sum=", c)
(2) If your code has any error, it will be shown in red color in the IDLE window, and Python
describes the type of error occurred. To correct the errors, go back to Script editor, make
corrections, save the file using Ctrl + S or File → Save and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in
Figure 5.8
Output
www.tntextbooks.org
A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions. The input() function helps to enter data at run time
by the user and the output function print() is used to display the result of the program on the
screen after execution.
5.4.1 The print() function
In Python, the print() function is used to display result on the screen. The syntax for
print() is as follows:
Example
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
Example
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
The print ( ) evaluates the expression before printing it on the monitor. The print
() displays an entire statement which is specified within print ( ). Comma ( , ) is used as a
separator in print ( ) to print more than one item.
Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable. If prompt string is not given in input( ) no message is
displayed on the screen, thus, the user will not know what is to be typed as input.
>>> city=input()
Rajarajan
>>> print (I am from", city)
I am from Rajarajan
Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input( ).
The input ( ) accepts all data as string or characters but not as numbers. If a numerical
value is entered, the input values should be explicitly converted into numeric data type. The
int( ) function is used to convert string data as integer data explicitly. We will learn about more
such functions in later chapters.
Example 3:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
www.tntextbooks.org
Enter Number 2: 56
The sum = 90
5.6 Indentation
Python uses whitespace such as spaces and tabs to define program blocks whereas
other languages like C, C++, java use curly braces { } to indicate blocks of codes for class,
functions or body of the loops and block of selection command. The number of whitespaces
(spaces and tabs) in the indentation is not fixed, but all statements within the block must be
indented with same amount spaces.
5.7 Tokens
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens, identifiers or keywords.
www.tntextbooks.org
5.7.1. Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.
5.7.2. Keywords
Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Table 5.1 Python’s Keywords
as elif If or yield
5.7.3 Operators
In computer programming languages operators are special symbols which represent
computations, conditional matching etc. The value of an operator used is called operands.
Operators are categorized as Arithmetic, Relational, Logical, Assignment etc. Value and
variables when used with operator are known as operands.
(i) Arithmetic operators
www.tntextbooks.org
An arithmetic operator is a mathematical operator that takes two operands and performs
a calculation on them. They are used for simple arithmetic. Most computer languages contain a
set of such operators that can be used within equations to perform different types of sequential
calculations.
XII Std Computer Science 56
on a condition being true or false. It simply allows testing a condition in a single line replacing
the multiline if-else making the code compact.
Example :
Output:
The Minimum of A and B is 20
5.7.4 Delimiters
Python uses the symbols and symbol combinations as delimiters in expressions, lists,
dictionaries and strings. Following are the delimiters.
( ) [ ] { }
, : . ‘ = ;
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
5.7.5 Literals
Literal is a raw data given in a variable or constant. In Python, there are various types
of literals.
1) Numeric
2) String
3) Boolean
www.tntextbooks.org
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
print ("Integer Literals :",a,b,c,d)
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
print ("Float Literals :",float_1,float_2)
#Complex Literal
x = 1 + 3.14 j
print ("Complex Literals :", x)
Print ("x = ", x , "Imaginary part of x = ", x.imag, "Real part of x = ", x.real)
#End of the Program
Output:
Integer Literals : 10 100 200 300
Float Literals : 10.5 150.0
Complex Literals :
x = (1.3.14) Imaginary part of x = 3.14 Real part of 9 x = 1.0
Output:
www.tntextbooks.org
This is Python
C
This is a multiline string with more than one line code.
OX102, oX876, OX432 # Hexadecimal integers
34L, 523L # Long decimal integers
A floating point data is represented by a sequence of decimal digits that includes a
decimal point. An Exponent data contains decimal digit part, decimal point, exponent part
followed by one or more digits.
Example :
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data
Complex number is made up of two floating point values, one each for the real and
imaginary parts.
5.8.2 Boolean Data type
A Boolean data can have any of the two values: True or False.
Example :
Bool_var1=True
Bool_var2=False
Example :
Char_data = ‘A’
www.tntextbooks.org
Points to remember:
• Python is a general purpose programming language created by Guido Van Rossum.
• Python shell can be used in two ways, viz., Interactive mode and Script mode.
• Python uses whitespace (spaces and tabs) to define program blocks
• Whitespace separation is necessary between tokens, identifiers or keywords.
• A Program needs to interact with end user to accomplish the desired task, this is done
using Input-Output facility.
• Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.
• Keywords are special words that are used by Python interpreter to recognize the
structure of program.
Evaluation
Part - I
Choose the best answer (1 Marks)
1. Who developed Python ?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<<
C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F
C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($)
C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers
www.tntextbooks.org
C) Keyword D) Operators
Part - II
Answer the following questions : (2 Marks)
1. What are the different modes that can be used to test Python Program ?
2. Write short notes on Tokens.
3. What are the different operators that can be used in Python ?
4. What is a literal? Explain the types of literals ?
5. Write short notes on Exponent data?
Part - III
Answer the following questions : (3 Marks)
1. Write short notes on Arithmetic operator with examples.
2. What are the assignment operators that can be used in Python?
3. Explain Ternary operator with examples.
4. Write short notes on Escape sequences with examples.
5. What are string literals? Explain.
Part - IV
Answer the following questions : (5 Marks)
www.tntextbooks.org
CHAPTER 6
Unit II
CONTROL STRUCTURES
Learning Objectives
• To learn through the syntax how to use conditional construct to improve the efficiency of
the program flow.
• To apply iteration structures to develop code to repeat the program segment for specific
number of times or till the condition is satisfied.
6.1 Introduction
Programs may contain set of statements. These statements are the executable segments
that yield the result. In general, statements are executed sequentially, that is the statements
are executed one after another. There may be situations in our real life programming where
we need to skip a segment or set of statements and execute another segment based on the test
of a condition. This is called alternative or branching. Also, we may need to execute a set of
statements multiple times, called iteration or looping. In this chapter we are to focus on the
various control structures in Python, their syntax and learn how to develop the programs
using them.
67
Sequential
Alternative or
Branching
Iterative or Looping
Example 6.1
# Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN
Syntax:
if <condition>:
statements-block1
In the above syntax if the condition is true statements - block 1 will be executed.
Example 6.2
# Program to check the age and print whether eligible for voting
x=int (input("Enter your age :"))
if x>=18:
print ("You are eligible for voting")
Output 1:
Enter your age :34
You are eligible for voting
Output 2:
Enter your age :16
>>>
As you can see in the second execution no output will be printed, only the Python
prompt will be displayed because the program does not check the alternative process when the
condition is failed.
(ii) if..else statement
The if .. else statement provides control to check the true block as well as the false
block. Following is the syntax of ‘if..else’ statement.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
www.tntextbooks.org
69 Control Structures
Entry
if condition is if condition is
true condition false
Statement Statement
block -1 block -2
Exit
Fig. 6.1 if..else statement execution
if..else statement thus provides two possibilities and the condition determines which
BLOCK is to be executed.
An alternate method to rewrite the above program is also available in Python. The
complete if..else can also written as:
Syntax:
variable = variable1 if condition else variable 2
www.tntextbooks.org
Note
The condition specified in the if is checked, if it is true, the value of variable1 is
stored in variable on the left side of the assignment, otherwise variable2 is taken as the
value.
71 Control Structures
Test false
Expression
of if
True
Body of else
Body of elif
Note
if..elif..else statement is similar to nested if statement which you have learnt in C++.
www.tntextbooks.org
Average Grade
>=80 and above A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
Otherwise E
Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
Output 2 :
Enter mark in first subject : 67
Note
The two blocks of code in our example of if-statement are both indented four
spaces, which is a typical amount of indentation for Python. In most other programming
languages, indentation is used only to help make the code look pretty. But in Python, it
is required to indicate to which block of code the statement belongs to.
www.tntextbooks.org
73 Control Structures
Example 6.5a: #Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)
Output 1:
Enter a character :e
e is a vowel
Output 2:
Enter a character :x
x the letter is not a/b/c
Iteration or loop are used in situation when the user need to execute a block of code
several of times or till the condition is satisfied. A loop statement allows to execute a statement
or group of statements multiple times.
False
Condition
True else
Statement 1
Statement 1 Statement 2
Statement 2 ...
... Statementn
Statementn
Further
Statements
of Program
Fig 6.3 Diagram to illustrate how looping construct gets executed
www.tntextbooks.org
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
while Expression:
Statement (s)
Condition
if conditions is true
if condition is
Conditional Code
false
Example 6.6: program to illustrate the use of while loop - to print all numbers
from 10 to 15
Output:
10 11 12 13 14 15
www.tntextbooks.org
75 Control Structures
Note
That the control variable is i, which is initialized to 10, the condition is tested
i<=15, if true value of i gets printed, then the control variable i gets updated as i=i+1 (this
can also be written as i +=1 using shorthand assignment operator). When i becomes 16,
the condition is tested False and this will terminate the loop.
Note
print can have end, sep as parameters. end parameter can be used when we need to give
any escape sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be
used to specify any special characters like, (comma) ; (semicolon) as separator between
values (Recall the concept which you have learnt in previous chapter about the formatting
options in print()).
Example 6.7: program to illustrate the use of while loop - with else part
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
www.tntextbooks.org
statements-block 2]
The counter_variable mentioned in the syntax is similar to the control variable that we
used in the for loop of C++ and the sequence refers to the initial, final and increment value.
Usually in Python, for loop uses the range() function in the sequence to specify the initial, final
and increment values. range() generates a list of values starting from start till stop-1.
range (start,stop,[step])
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
Example 6.8: Examples for range()
range (1,30,1) will start the range of values from 1 and end at 29
range (2,30,2) will start the range of values from 2 and end at 28
range (30,3,-3) - will start the range of values from 30 and end at 6
range (20) will consider this value 20 as the end value(or upper limit) and starts the
range count from 0 to 19 (remember always range() will work till stop -1
value only)
Yes
Last item
reached?
No
Body of for
Exit loop
Fig 6.5 for loop execution
www.tntextbooks.org
77 Control Structures
Example 6.9: #program to illustrate the use of for loop - to print single
digit even number
for i in range (2,10,2):
print (i, end=' ')
Output:
2468
Note
In Python, indentation is important in loop and other control statements. Indentation
only creates blocks and sub-blocks like how we create blocks within a set of { } in languages
like C, C++ etc.
Here is another program which illustrates the use of range() to find the sum of numbers
1 to 100
of counter variable and stored in sum. Note that the for loop will iterate from 1 till
the upper limit -1 (ie. Value of n is set as 100, so this loop will iterate for values from
1 to 99 only, that is the reason why we have set the upper limit as n+1)
Note
range () can also take values from string, list, dictionary etc. which will be dealt
in the later chapters.
Output
Computer
End of the loop
79 Control Structures
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
False
Condition
True else
Statement 1
Statement 1 Statement 2
... ...
break Statementn
...
continue Further
... Statements
Statementn of Program
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax:
break
Enter loop
false
Condition
true
break?
yes
Exit loop
no
Remaining body of loop
The working of break statement in for loop and while loop is shown below.
81 Control Structures
The above program will repeat the iteration with the given “Jump Statement” as string.
Each letter of the given string sequence is tested till the letter ‘e’ is encountered, when it is
encountered the control is transferred outside the loop block or it terminates. As shown in the
output, it is displayed till the letter ‘e’ is checked after which the loop gets terminated.
One has to note an important point here is that ‘if a loop is left by break, the else part
is not executed’. To explain this lets us enhance the previous program with an ‘else’ part and
see what output will be:
Note that the break statement has even skipped the ‘else’ part of the loop and has
transferred the control to the next line following the loop block.
Syntax:
continue
Enter loop
Test false
Expression
of loop
true
yes
continue?
Exit loop
no
Remaining body of loop
The working of continue statement in for and while loop is shown below.
for var in sequence:
# code inside for loop
if condition:
continue
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
continue
#code inside while loop
#code outside while loop www.tntextbooks.org
83 Control Structures
The above program is same as the program we had written for ‘break’ statement except
that we have replaced it with ‘continue’. As you can see in the output except the letter ‘e’ all the
other letters get printed.
Syntax:
pass
Note
pass statement is generally used as a placeholder. When we have a loop or function
that is to be implemented in the future and not now, we cannot develop such functions
or loops with empty body segment because the interpreter would raise an error. So, to
avoid this we can use pass statement to construct a body that does nothing.
Example 6.18: Program to illustrate the use of pass statement in for loop
for val in “Computer”:
pass
print (“End of the loop, loop structure will be built in future”)
Output:
End of the loop, loop structure will be built in future.
Points to remember:
85 Control Structures
Hands on Experience
Evaluation
Part - I
statements-block 2
A) ; B) :
C) :: D) !
87 Control Structures
Part -II
CHAPTER 7
Unit II
PYTHON FUNCTIONS
Table – 7.1 – Python Functions and it's • The code block always comes after a
Description colon (:) and is indented.
Now let’s check out functions in action so you can visually see how they work within a
program. Here is an example for a simple function to display the given string.
Example:
def hello():
print (“hello - Python”)
return
Output
hello – Python
Alternatively we can call the “hello()” function within the print() function as in the
example given below.
Example:
def hello():
print (“hello - Python”)
return
print (hello())
If the return has no argument, “None” will be displayed as the last statement of the
output.
The above function will output the following.
www.tntextbooks.org
Output:
hello – Python
None
91 Python Functions
Let us see the use of parameters while defining functions. The parameters that you
place in the parenthesis will be used by the function itself. You can pass all sorts of data to the
functions. Here is an example program that defines a function that helps to pass parameters
into the function.
Example:
# assume w = 3 and h = 5
def area(w,h):
return w * h
print (area (3,5))
The above code assigns the width and height values to the parameters w and h. These
parameters are used in the creation of the function “area”. When you call the above function,
it returns the product of width and height as output.
The value of 3 and 5 are passed to w and h respectively, the function will return 15 as
output.
We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them. Parameters are the variables used in the function
definition whereas arguments are the values we pass to the function parameters
Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.
www.tntextbooks.org
Function Arguments
1 Required arguments
2 Keyword arguments
3 Default arguments
4 Variable-length arguments
Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is
www.tntextbooks.org
Output:
Example - Required arguments
Welcome
93 Python Functions
Output:
Example-1 Keyword arguments
Name :Gshan
Example:
def printdata (name):
print (“Example-2 Keyword arguments”)
print (“Name :”, name)
return
# Now you can call printdata() function
printdata (name1 = “Gshan”)
Example:
def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
www.tntextbooks.org
Output:
Example-3 Keyword arguments
Name : Gshan
Age : 25
Note
In the above program the parameters orders are changed
Example:
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)
Output:
Name: Mani
Salary: 3500
When the above code is changed as print info(“Ram”,2000) it produces the following
output:
Output:
Name: Ram
Salary: 2000
www.tntextbooks.org
In the above code, the value 2000 is passed to the argument salary, the default value
already assigned for salary is simply ignored.
95 Python Functions
Example:
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)
Example:
def printnos (*nos): Output:
for n in nos: Printing two values
print(n) 1
return 2
# now invoking the printnos() function Printing three values
print ('Printing two values') 10
printnos (1,2) 20
print ('Printing three values') 30
printnos (10,20,30)
Evaluate Yourself ?
www.tntextbooks.org
In the above program change the function name printnos as printnames in all places
wherever it is used and give the appropriate data Ex. printnos (10, 20, 30) as printnames ('mala',
'kala', 'bala') and see output.
In Variable Length arguments we can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
Non-keyword variable arguments are called tuples. You will learn more about tuples in
the later chapters. The Program given is an illustration for non keyword variable argument.
Note
Keyword variable arguments are beyond the scope of this book.
Note
filter(), map() and reduce() functions are beyond the scope of this book.
Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.
www.tntextbooks.org
97 Python Functions
The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().
• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return
This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
www.tntextbooks.org
Example :
# return statment
def usr_abs (n):
if n>=0:
return n
else:
return –n
# Now invoking the function
x=int (input(“Enter a number :”)
print (usr_abs (x))
Output 1:
Enter a number : 25
25
Output 2:
Enter a number : -25
25
7.8 Scope of Variables
Scope of variable refers to the part of the program, where it is accessible, i.e., area where
you can refer (use) it. We can say that scope holds the current set of variables and their values.
We will study two types of scopes - local scope and global scope.
99 Python Functions
When we run the above code, the output shows the following error:
The above error occurs because we are trying to access a local variable ‘y’ in a global
scope.
add()
Output:
1
def add():
print(c)
add()
Output:
1
Note
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.
In the above program, x is defined as a global variable. Inside the add() function, global
keyword is used for x and we increment the variable x by 5. Now We can see the change on the
global variable x outside the function i.e the value of x is 5.
In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.
x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)
Output:
local x: 10
global x: 5
In above code, we used same name ‘x’ for both global variable and local variable. We get
different result when we print same variable because the variable is declared in both scopes, i.e.
the local scope inside the function loc() and global scope outside the function loc().
www.tntextbooks.org
2. Second Output:1
argument x value is rounded to 18
(ndigits) y value is rounded to 22
is used to z value is rounded to -18
specify the n1=17.89
number print (round (n1,0))
of decimal print (round (n1,1))
digits print (round (n1,2))
desired after
rounding. Output:2
18.0
17.9
17.89
pow ( ) Returns the a= 5
computation of b= 2
ab i.e. (a**b ) c= 3.0
a raised to the print (pow (a,b))
power of b. print (pow (a,c))
pow (a,b) print (pow (a+b,3))
Output:
25
125.0
343
Mathematical Functions
Note
Import math module for all mathematical functions.
26
-27
-24
When a function calls itself is known as recursion. Recursion works like loop but
sometimes it makes more sense to use recursion than loop. You can convert any loop to
recursion.
A recursive function calls itself. Imagine a process would iterate indefinitely if not
stopped by some condition! Such a process is known as infinite iteration. The condition that
is applied in any recursive function is known as base condition. A base condition is must in
every recursive function otherwise it will continue to execute like an infinite loop.
Example :
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
print(fact (2000)) will give Runtime Error maximum recursion depth exceeded in
comparison. This happens because python stops calling recursive function after
1000 calls by default. It also allows you to change the limit using sys.setrecursionlimit
(limit_value).
Example:
import sys
sys.setrecursionlimit(3000)
def fact(n):
if n == 0:
return 1
else:
www.tntextbooks.org
return n * fact(n-1)
print(fact (2000))
Points to remember:
• Functions are named blocks of code that are designed to do one specific job.
• Types of Functions are User defined, Built-in, lambda and recursion.
• Function blocks begin with the keyword “def ” followed by function name and
parenthesis ().
• A “return” with no arguments is the same as return None. Return statement
is optional in python.
• In Python, statements in a block should begin with indentation.
• A block within a block is called nested block.
• Arguments are used to call a function and there are primarily 4 types of
functions that one can use: Required arguments, Keyword arguments, Default
arguments and Variable-length arguments.
• Required arguments are the arguments passed to a function in correct
positional order.
• Keyword arguments will invoke the function after the parameters are
recognized by their parameter names.
• A Python function allows us to give the default values for parameters in the
function definition. We call it as Default argument.
• Variable-Length arguments are not specified in the function’s definition and
an asterisk (*) is used to define such arguments.
• Anonymous Function is a function that is defined without a name.
• Scope of variable refers to the part of the program, where it is accessible, i.e.,
area where you can refer (use) it.
• The value returned by a function may be used as an argument for another
function in a nested manner. This is called composition.
• A function which calls itself is known as recursion. Recursion works like a
loop but sometimes it makes more sense to use recursion than loop.
www.tntextbooks.org
Hands on Experience
1. Try the following code in the above program
1 eval(‘25*2-5*4')
2 math.sqrt(abs(-81))
3 math.ceil(3.5+4.6)
4 math.floor(3.5+4.6)
4) round(0.5120,3)
7 1) format(66, 'c')
2) format(10, 'x')
3) format(10, 'X')
4) format(0b110, 'd')
5) format(0xa, 'd')
8 1) pow(2,-3)
2) pow(2,3.0)
3) pow(2,0)
4) pow((1+2),2)
5) pow(-3,2)
6) pow(2*2,2)
Evaluation
Part - I
Choose the best answer: (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching
(c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion
(c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion
(c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for
(c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return
(c) finally (d) def
www.tntextbooks.org
Part - II
Part - III
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from tutorialspoint.com
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert
www.tntextbooks.org
CHAPTER 8
Unit II
STRINGS AND STRING MANIPULATION
Learning Objectives
8.1 Introduction
String is a data type in python, which is used to handle array of characters. String is
a sequence of Unicode characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.
Example
In python, strings are immutable, it means, once you define a string, it cannot be
changed during execution.
8.2 Creating Strings
As we learnt already, a string in Python can be created using single or double or even
triple quotes. String in single quotes cannot hold any other single quoted character in it, because
the compiler will not recognize where to start and end the string. To overcome this problem,
you have to use double quotes. Strings which contains double quotes should be define within
www.tntextbooks.org
triple quotes. Defining strings within triple quotes also allows creation of multiline strings.
Example
#A string defined within single quotes
>>> print (‘Greater Chennai Corporation’)
Greater Chennai Corporation
#single quoted string defined within single quotes
>>> print ('Greater Chennai Corporation's student')
SyntaxError: invalid syntax
The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.
Example
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1
www.tntextbooks.org
Example
>>> str1="How are you"
>>> str1[0]="A"
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str1[0]="A"
TypeError: 'str' object does not support item assignment
In the above example, string variable str1 has been assigned with the string “How are
you” in statement 1. In the next statement, we try to update the first character of the string with
character ‘A’. But python will not allow the update and it shows a TypeError.
To overcome this problem, you can define a new string value to the existing string
variable. Python completely overwrite new string on the existing string.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> str1="How about you"
>>> print (str1)
How about you
Usually python does not support any modification in its strings. But, it provides a
function replace() to change all occurrences of a particular character in a string.
General formate of replace function:
replace(“char1”, “char2”)
The replace function replaces all occurrences of char1 with char2.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> print (str1.replace("o", "e"))
Hew are yeu
www.tntextbooks.org
Similar as modification, python will not allow deleting a particular character in a string.
Whereas you can remove entire string variable using del command.
Example
>>> str1="Welcome to "
Example IV : slice a substring using index 0 to 4 but without specifying the end index.
>>> print (str1[6:])
KURAL
119 Strings and String Manipulation
str1="COMPUTER"
index=0
for i in str1:
print (str1[:index+1])
index+=1
Output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER
Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er
>>> print (str1[::3])
Wceoenyo
Example
>>> str1 = "Welcome to learn Python"
>>> print(str1[::-2])
nhy re teolW
8.6 String Formatting Operators
The string formatting operator is one of the most exciting feature of python. The
formatting operator % is used to construct strings, replacing parts of the strings with the data
stored in variables.
Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))
Example
name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))
Output
Name: Rajarajan and Marks: 98
Example
# String within triple quotes to display a string with single quote
>>> print ('''They said, "What's there?"''')
They said, "What's there?"
# String within single quotes to display a string with single quote using escape sequence
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
# String within double quotes to display a string with single quote using escape sequence
>>> print ("They said, \"What's there?\"")
He said, "What's there?"
The format( ) function used with strings is very versatile and powerful function used
for formatting strings. The curly braces { } are used as placeholders or replacement fields which
get replaced along with format( ) function.
Example
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))
Out Put
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88
>>>str1.find(‘ma’,2,5)
3
Example
str1=input ("Enter a string: ")
str2="chennai"
if str2 in str1:
print ("Found")
else:
print ("Not Found")
Output : 1
Enter a string: Chennai G HSS, Saidapet
Found
www.tntextbooks.org
Output : 2
Enter a string: Govt G HSS, Ashok Nagar
Not Found
or not
str1 = input ("Enter a string: ")
str2 = ' '
index=-1
for i in str1:
str2 += str1[index]
index -= 1
print ("The given string = { } \n The Reversed string = { }".format(str1, str2))
if (str1==str2):
print ("Hence, the given string is Palindrome")
else:
print ("Hence, the given is not a palindrome")
Output : 1
Enter a string: malayalam
The given string = malayalam
The Reversed string = malayalam
Hence, the given string is Palindrome
Output : 2
Enter a string: welcome
The given string = welcome
The Reversed string = emoclew
Hence, the given string is not a palindrome
*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)
i+=1
Output
*
www.tntextbooks.org
* *
* * *
* * * *
* * * * *
Output
Enter a string: Tamilnadu School Education
The given string contains 11 vowels and 15 consonants
Example 8.11.4 : Program that accept a string from the user and display
the same after removing vowels from it
def rem_vowels(s):
temp_str=''
for i in s:
if i in "aAeEiIoOuU":
pass
else:
temp_str+=i
print ("The string without vowels: ", temp_str)
str1= input ("Enter a String: ")
rem_vowels (str1)
www.tntextbooks.org
Output
Enter a String: Mathematical fundations of Computer Science
The string without vowels: Mthmtcl fndtns f Cmptr Scnc
Points to remember:
• String is a data type in python.
• Strings are immutable, that means once you define string, it cannot be changed during
execution.
• Defining strings within triple quotes also allows creation of multiline strings.
• In a String, python allocate an index value for its each character which is known as
subscript.
• The subscript can be positive or negative integer numbers.
• Slice is a substring of a main string.
• Stride is a third argument in slicing operation.
• Escape sequences starts with a backslash and it can be interpreted differently.
• The format( ) function used with strings is very versatile and powerful function used
for formatting strings.
• The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string
is present in another string.
Hands on Experience
www.tntextbooks.org
4. Write a program to print integers with ‘*’ on the right of specified width.
5. Write a program to create a mirror of the given string. For example, “wel” = “lew“.
9. Write a program to replace a string with another string without using replace().
10. Write a program to count the number of characters, words and lines in a given string.
Evaluation
Part - I
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in
upper case?
(a) %e (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced
along with format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative
(c) Both (a) and (b) (d) Either (a) or (b)
Part -II
COM
CO
C
Part -IV
Reference Books
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
www.tntextbooks.org
CHAPTER 9
Unit III
LISTS, TUPLES, SETS AND DICTIONARY
Learning Objectives
Python programming language has four collections of data types such as List, Tuples,
Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an
ordered collection of values enclosed within square brackets [ ]. Each value of a list is called
as element. It can be of any type such as numbers, characters, strings and even the nested lists
as well. The elements can be modified or mutable which means the elements can be replaced,
added or removed. Every element rests at some position in the list. The position of an element
is indexed with numbers beginning with zero which is used to locate and access a particular
element. Thus, lists are similar to arrays, what you learnt in XI std.
9.1.1 Create a List in Python
In python, a list is simply created by using square bracket. The elements of list should
be specified within square brackets. The following syntax explains the creation of list.
Syntax:
Variable = [element-1, element-2, element-3 …… element-n]
www.tntextbooks.org
Example
Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]
In the above example, the list Marks has four integer elements; second list Fruits has
four string elements; third is an empty list. The elements of a list need not be homogenous type
of data. The following list contains multiple type elements.
In the above example, Mylist contains another list as an element. This type of list is
known as “Nested List”.
Example
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1
Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).
To access an element from a list, write the name of the list, followed by the index of the
element enclosed within square brackets.
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
www.tntextbooks.org
In the above example, print command prints 10 as output, as the index of 10 is zero.
Example
Marks = [10, 23, 41, 75]
i=0
while i < 4:
print (Marks[i])
i=i+1
Output
10
23
41
75
In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each
element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively.
Here, the while loop is used to read all the elements. The initial value of the loop is zero, and
www.tntextbooks.org
the test condition is i < 4, as long as the test condition is true, the loop executes and prints the
corresponding output.
During the first iteration, the value of i is zero, where the condition is true. Now, the
following statement print (Marks [i]) gets executed and prints the value of Marks [0] element
ie. 10.
The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of
control shifts to the while statement for checking the test condition. The process repeats to
print the remaining elements of Marks list until the test condition of while loop becomes false.
The following table shows that the execution of loop and the value to be print.
print
Iteration i while i < 4 i=i+1
(Marks[i])
5 4 4 < 4 False -- --
Example
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1
Output
75
41
23
10
www.tntextbooks.org
The following table shows the working process of the above python coding
Syntax:
www.tntextbooks.org
Here, index_var represents the index value of each element in the list. Python reads
this “for” statement like English: “For (every) element in (the list of) list and print (the name of
the) list items”
Example
In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The
Python reads the for loop and print statements like English: “For (every) element (represented
as x) in (the list of) Marks and print (the values of the) elements”.
Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed
Where, index from is the beginning index of the range; index to is the upper limit of
the range which is excluded in the range. For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to
4, it should be specified as [1:5].
www.tntextbooks.org
Example
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> print(MyList)
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
>>> MyList.insert(3, 'Ramakrishnan')
>>> print(MyList)
[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
www.tntextbooks.org
In the above example, insert( ) function inserts a new element ‘Ramakrishnan’ at the
index value 3, ie. at the 4th position. While inserting a new element in between the existing
elements, at a particular location, the existing elements shifts one position to the right.
Syntax:
del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list
Example
>>> MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> print (MySubjects)
['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> del MySubjects[1]
>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths']
In the above example, the list MySubjects has been created with four elements. print
statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an
element whose index value is 1 and the following print shows the remaining elements of the
list.
Example
>>> del MySubjects[1:3]
>>> print(MySubjects)
['Tamil']
In the above codes, >>> del MySubjects[1:3] deletes the second and third elements
from the list. The upper limit of index is specified within square brackets, will be taken as -1 by
www.tntextbooks.org
the python.
Example
>>> del MySubjects
>>> print(MySubjects)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(MySubjects)
NameError: name 'MySubjects' is not defined
Here, >>> del MySubjects, deletes the list MySubjects entirely. When you try to print the
elements, Python shows an error as the list is not defined. Which means, the list MySubjects
has been completely deleted.
As already stated, the remove( ) function can also be used to delete one or more elements
if the index value is not known. Apart from remove( ) function, pop( ) function can also be
used to delete an element using the given index value. pop( ) function deletes and returns the
last element of a list if the index is not given.
The function clear( ) is used to delete all the elements in list, it deletes only the elements
and retains the list. Remember that, the del statement deletes entire list.
Syntax:
List.remove(element) # to delete a particular element
List.pop(index of an element)
List.clear( )
Example
>>> MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']
>>> print(MyList)
[12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin']
>>> MyList.remove(89)
>>> print(MyList)
[12, 34, 'Kannan', 'Gowrisankar', 'Lenin']
In the above example, MyList has been created with three integer and three string
elements, the following print statement shows all the elements available in the list. In the
statement >>> MyList.remove(89), deletes the element 89 from the list and the print statement
shows the remaining elements.
www.tntextbooks.org
Example
>>> MyList.pop(1)
34
>>> print(MyList)
[12, 'Kannan', 'Gowrisankar', 'Lenin']
In the above code, pop( ) function is used to delete a particular element using its index
value, as soon as the element is deleted, the pop( ) function shows the element which is
deleted. pop( ) function is used to delete only one element from a list. Remember that, del
statement deletes multiple elements.
Example
>>> MyList.clear( )
>>> print(MyList)
[]
In the above code, clear( ) function removes only the elements and retains the list. When
you try to print the list which is already cleared, an empty square bracket is displayed without
any elements, which means the list is empty.
where,
• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of
values.
www.tntextbooks.org
Syntax:
List_Varibale = list ( range ( ) )
Note
www.tntextbooks.org
Example
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements. Thus,
Even_List list has the elements of first five even numbers.
Similarly, we can create any series of values using range( ) function. The following example
explains how to create a list with squares of first 10 natural numbers.
In the above program, an empty list is created named “squares”. Then, the for loop
generates natural numbers from 1 to 10 using range( ) function. Inside the loop, the current
value of x is raised to the power 2 and stored in the variables. Each new value of square is
appended to the list “squares”. Finally, the program shows the following values as output.
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Syntax:
List = [ expression for variable in range ]
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In the above example, x ** 2 in the expression is evaluated each time it is iterated. This
is the shortcut method of generating series of values.
MyList=[21,76,98,23]
Returns the maximum print(max(MyList))
max( ) max(list)
value in a list. Output:
98
MyList=[21,76,98,23]
Returns the minimum print(min(MyList))
min( ) min(list)
value in a list. Output:
21
MyList=[21,76,98,23]
Returns the sum of print(sum(MyList))
sum( ) sum(list)
values in a list. Output:
218
9.1.12 Programs using List
Output
Enter the name of the country: Japan
Japan is not a member of BRICS
Program 3: Python program to read marks of six subjects and to print the
marks scored in each subject and show the total marks
marks=[]
subjects=['Tamil', 'English', 'Physics', 'Chemistry', 'Comp. Science', 'Maths']
for i in range(6):
m=int(input("Enter Mark = "))
marks.append(m)
for j in range(len(marks)):
print("{ }. { } Mark = { } ".format(j1+,subjects[j],marks[j]))
print("Total Marks = ", sum(marks))
Output
Enter Mark = 45
Enter Mark = 98
Enter Mark = 76
Enter Mark = 28
Enter Mark = 46
Enter Mark = 15
1. Tamil Mark = 45
2. English Mark = 98
3. Physics Mark = 76
4. Chemistry Mark = 28
5. Comp. Science Mark = 46
6. Maths Mark = 15
Total Marks = 308
items=[]
prod=1
for i in range(5):
print ("Enter price for item { } : ".format(i+1))
p=int(input())
items.append(p)
for j in range(len(items)):
print("Price for item { } = Rs. { }".format(j+1,items[j]))
prod = prod * items[j]
print("Sum of all prices = Rs.", sum(items))
print("Product of all prices = Rs.", prod)
www.tntextbooks.org
Output:
Enter price for item 1 :
5
Enter price for item 2 :
10
Enter price for item 3 :
15
Enter price for item 4 :
20
Enter price for item 5 :
25
Price for item 1 = Rs. 5
Price for item 2 = Rs. 10
Price for item 3 = Rs. 15
Price for item 4 = Rs. 20
Price for item 5 = Rs. 25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0
count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))
s=int(input())
salary.append(s)
for j in range(len(salary)):
annual_salary = salary[j] * 12
print ("Annual Salary of Employee { } is:Rs. { }".format(j+1,annual_salary))
if annual_salary >= 100000:
count = count + 1
print("{ } Employees out of { } employees are earning more than Rs. 1 Lakh per annum".
format(count, n))
www.tntextbooks.org
Output:
Enter no. of employees: 5
No. of Employees 5
Enter Monthly Salary of Employee 1 Rs.:
3000
Enter Monthly Salary of Employee 2 Rs.:
9500
Enter Monthly Salary of Employee 3 Rs.:
12500
Enter Monthly Salary of Employee 4 Rs.:
5750
Enter Monthly Salary of Employee 5 Rs.:
8000
Annual Salary of Employee 1 is:Rs. 36000
Annual Salary of Employee 2 is:Rs. 114000
Annual Salary of Employee 3 is:Rs. 150000
Annual Salary of Employee 4 is:Rs. 69000
Annual Salary of Employee 5 is:Rs. 96000
2 Employees out of 5 employees are earning more than Rs. 1 Lakh per annum
Output
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]
www.tntextbooks.org
9.2 Tuples
Introduction to Tuples
Tuples consists of a number of values separated by comma and enclosed within
parentheses. Tuple is similar to list, values in a list can be changed but not in a tuple.
The term Tuple is originated from the Latin word represents an abstraction of the
sequence of numbers:
single(1), double(2), triple(3), quadruple(4), quintuple(5), sextuple(6), septuple(7),
octuple(8), ..., n tuple, ...,
‑
9.2.1 Advantages of Tuples over list
1. The elements of a list are changeable (mutable) whereas the elements of a tuple are
unchangeable (immutable), this is the key difference between tuples and list.
2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are
www.tntextbooks.org
enclosed by paranthesis.
Syntax:
# Empty tuple
Tuple_Name = ( )
Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
>>> MyTup2 = 23, 56, 89, 'A', 'E', 'I', "Tamil"
>>> print (MyTup2)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
(i) Creating tuples using tuple( ) function
The tuple( ) function is used to create Tuples from a list. When you create a tuple, from a
list, the elements should be enclosed within square brackets.
Syntax:
Tuple_Name = tuple( [list elements] )
Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
www.tntextbooks.org
>>> type (MyTup3)
<class ‘tuple’>
151 Lists, Tuples, Sets and Dictionary
Note
Type ( ) function is used to know the data type of a python object.
Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>
9.2.3 Accessing values in a Tuple
Like list, each element of tuple has an index number starting from zero. The elements of
a tuple can be easily accessed by using index number.
Example
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)
www.tntextbooks.org
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
XII Std Computer Science 152
Example
# Program to join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)
Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
Syntax:
del tuple_name
Example
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)
Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp 1.py", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined
Note that, the print statement in the above code prints the elements. Then, the del statement
deletes the entire tuple. When you try to print the deleted tuple, Python shows the error.
Tuple assignment is a powerful feature in Python. It allows a tuple variable on the left
of the assignment operator to be assigned to the values on the right side of the assignment
a b c
= 34 90 76
Example
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
# expression are evaluated before assignment
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False
Note that, when you assign values to a tuple, ensure that the number of values on both sides of
the assignment operator are same; otherwise, an error is generated by Python.
Output:
Maximum value = 99
www.tntextbooks.org
Minimum value = 1
Example
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
Note
All the functions used in List can be applicable even for tuples.
Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
www.tntextbooks.org
Value of A = 38
Value of B = 54
Program 2: Write a program using a function that returns the area and
circumference of a circle whose radius is passed as an argument.two values
using tuple assignment
pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)
Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002
Program 3: Write a program that has a list of positive and negative numbers.
Create a new tuple that has only positive numbers from the list
Output:
Positive Numbers: (5, 6, 8, 3, 1)
9.3 Sets
Introduction
In python, a set is another type of collection data type. A Set is a mutable and an unordered
collection of elements without duplicates. That means the elements within a set cannot be
www.tntextbooks.org
repeated. This feature used to include membership testing and eliminating duplicate elements.
Syntax:
Set_Variable = {E1, E2, E3 …….. En}
Example
>>> S1={1,2,3,'A',3.14}
>>> print(S1)
{1, 2, 3, 3.14, 'A'}
>>> S2={1,2,2,'A',3.14}
>>> print(S2)
{1, 2, 'A', 3.14}
In the above examples, the set S1 is created with different types of elements without
duplicate values. Whereas in the set S2 is created with duplicate values, but python accepts
only one element among the duplications. Which means python removed the duplicate value,
because a set in python cannot have duplicate elements.
Note
When you print the elements from a set, python shows the values in different order.
Example
MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)
www.tntextbooks.org
Output:
{2, 4, 6, 8, 10}
Set A Set B
In python, the operator | is used to union of two sets. The function union( ) is also used
to join two sets in python.
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
www.tntextbooks.org
Set A Set B
The operator & is used to intersect two sets in python. The function intersection( ) is
also used to intersect two sets in python.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))
Output:
{'A', 'D'}
www.tntextbooks.org
(iii) Difference
It includes all elements that are in first set (say set A) but not in the second set (say set B)
Set A Set B
The minus (-) operator is used to difference set operation in python. The function
difference( ) is also used to difference operation.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference(set_B))
Output:
{2, 4}
www.tntextbooks.org
Set A Set B
The caret (^) operator is used to symmetric difference set operation in python. The
function symmetric_difference( ) is also used to do the same operation.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))
Output:
{2, 4, 'B', 'C'}
www.tntextbooks.org
Example
9.4 Dictionaries
Introduction
In python, a dictionary is a mixed collection of elements. Unlike other collection data
types such as a list or tuple, the dictionary type stores a key along with its element. The keys in
a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the
elements. The key value pairs are enclosed with curly braces { }.
www.tntextbooks.org
……..
Key_n:Value_n
}
Key in the dictionary must be unique case sensitive and can be of any valid Python type.
Syntax
Dict = { expression for variable in sequence [if condition] }
The if condition is optional and if specified, only those values in the sequence are evaluated
using the expression which satisfy the condition.
Example
Note that, the first print statement prints all the values of the dictionary. Other statements
are printing only the specified values which is given within square brackets.
In an existing dictionary, you can add more values by simply assigning the value along
with key. The following syntax is used to understand adding more elements in a dictionary.
dictionary_name [key] = value/element
Modification of a value in dictionary is very similar as adding elements. When you assign
a value to a key, it will simply overwrite the old value.
www.tntextbooks.org
In Python dictionary, del keyword is used to delete a particular element. The clear( )
function is used to delete all the elements in a dictionary. To remove the dictionary, you can
use del keyword with dictionary name.
XII Std Computer Science 164
Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary
Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{}
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined
(2) The index values can be used to access a particular element. But, in dictionary key
www.tntextbooks.org
(3) Lists are used to look up a value whereas a dictionary is used to take one value and look
up another value.
Points to remember:
• Python programming language has four collections of data types such as List, Tuple,
Set and Dictionary.
• A list is known as a “sequence data type”. Each value of a list is called as element.
• The elements of list should be specified within square brackets.
• Each element has a unique value called index number begins with zero.
• Python allows positive and negative values as index.
• Loops are used access all elements from a list.
• The “for” loop is a suitable loop to access all the elements one by one.
• The append ( ), extend ( ) and insert ( ) functions are used to include more elements
in a List.
• The del, remove ( ) and pop ( ) are used to delete elements from a list.
• The range ( ) function is used to generate a series of values.
• Tuples consists of a number of values separated by comma and enclosed within
parentheses.
• Iterating tuples is faster than list.
• The tuple ( ) function is also used to create Tuples from a list.
• Creating a Tuple with one element is called “Singleton” tuple.
• A Set is a mutable and an unordered collection of elements without duplicates.
• A set is created by placing all the elements separated by comma within a pair of curly
brackets.
• A dictionary is a mixed collection of elements.
Hands on Experience
3. Write a program that finds the sum of all the numbers in a Tuples using while loop.
www.tntextbooks.org
7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by 3 or
divisible by 6.
8. Write a program to create a list of numbers in the range 1 to 20. Then delete all the numbers
from the list that are divisible by 3.
9. Write a program that counts the number of times a value appears in the list. Use a loop to
do the same.
10. Write a program that prints the maximum and minimum value in a dictionary.
Evaluation
Part - I
print(S)
(a) [0,1,2,4,5] (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple
(b) To know the type of an element in tuple.
(c) To know the data type of python object.
(d) To create a list.
9. Which of the following statement is not correct?
(a) A list is mutable
(b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a list.
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}
11. Which of the following set operation includes all the elements that are in two sets but not
the one that are common to two sets?
(a) Symmetric difference (b) Difference
(c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c)+ (d) :
Part - II
x=len(List1)
4. Differentiate del with remove( ) function of List.
Part - III
Part - IV
References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford
University press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
www.tntextbooks.org
CHAPTER 10
Unit III
PYTHON CLASSES AND OBJECTS
Learning Objectives
10.1 Introduction
Python is an Object Oriented Programming language. Classes and Objects are the key
features of Object Oriented Programming. Theoretical concepts of classes and objects are very
similar to that of C++. But, creation and implementation of classes and objects is very simple
in Python compared to C++.
Class is the main building block in Python. Object is a collection of data and function
that act on those data. Class is a template for the object. According to the concept of Object
Oriented Programming, objects are also called as instances of a class or class variable. In
Python, everything is an object. For example, all integer variables that we use in our program
is an object of class int. Similarly all string variables are also object of class string.
10.2 Defining classes
In Python, a class is defined by using the keyword class. Every class has a unique name
followed by a colon ( : ).
Syntax:
class class_name:
statement_1
statement_2
…………..
www.tntextbooks.org
…………..
statement_n
Syntax:
Object_name = class_name( )
Note that the class instantiation uses function notation ie. class_name with
Value of x = 10
Value of y = 20
Value of x and y = 30
In the above code, the name of the class is Sample. Inside the class, we have assigned
the variables x and y with initial value 10 and 20 respectively. These two variables are called as
class variables or member variables of the class. In class instantiation process, we have created
an object S to access the members of the class. The first two print statements simply print the
value of class variable x and y and the last print statement add the two values and print the
result.
Note
The statements defined inside the class must be properly indented.
Example 10.2: Program to find total and average marks using class
class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable
def process(self): #class method
sum = Student.mark1 + Student.mark2 + Student.mark3
avg = sum/3
print("Total Marks = ", sum)
print("Average Marks = ", avg)
return
S=Student()
S.process()
www.tntextbooks.org
In the above program, after defining the class, an object S is created. The statement
S.process( ), calls the function to get the required output.
Note that, we have declared three variables mark1, mark2 and mark3 with the values
45, 91, 71 respectively. We have defined a method named process with self argument, which
means, we are not going to pass any value to that method. First, the process method adds the
values of the class variables, stores the result in the variable sum, finds the average and displays
the result.
Thus the above code will show the following output.
Output
Total Marks = 207
Average Marks = 69.0
class Odd_Even:
even = 0 #class varaiable
def check(self, num):
if num%2==0:
print(num," is Even number")
else:
print(num," is Odd number")
n=Odd_Even()
x = int(input("Enter a value: "))
n.check(x)
When you execute this program, Python accepts the value entered by the user
and passes it to the method check through object.
Output 1
Enter a value: 4
4 is Even number
Output 2
Enter a value: 5
5 is Odd number
but only difference is, it is executed automatically when the object is created. This constructor
function can be defined with or without arguments. This method is used to initialize the class
variables.
The above class “Sample”, has only a constructor with one argument named as num.
When the constructor gets executed, first the print statement, prints the “Constructor of class
Sample….”, then, the passing value to the constructor is assigned to self.num and finally it
prints the value passed along with the given string.
The above constructor gets executed automatically, when an object S is created with
actual parameter 10. Thus, the Python display the following output.
S2=Sample(35)
S3=Sample(45)
In the above program, class variable num is shared by all three objects of the class
Sample. It is initialized to zero and each time an object is created, the num is incremented by
1. Since, the variable shared by all objects, change made to num by one object is reflected in
other objects as well. Thus the above program produces the output given below.
Output
The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3
Note: class variable is similar to static type in C++
Destructor is also a special method gets executed automatically when an object exit
from the scope. It is just opposite to constructor. In Python, __del__( ) method is used as
destructor.
Example : Program to illustrate about the __del__( ) method
class Sample:
num=0
def __init__(self, var):
Sample.num+=1
self.var=var
print("The object value is = ", var)
print("The value of class variable is= ", Sample.num)
def __del__(self):
Sample.num-=1
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.
www.tntextbooks.org
In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is defined to
show the values passed to these two variables.
The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method
defined inside the class. But, when we try to access the value of n2 from outside the class
Python throws an error. Because, private variable cannot be accessed from outside the class.
Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002
class Library:
def __init__(self):
self.bookname=""
self.author=""
def getdata(self):
self.bookname = input("Enter Name of the Book: ")
self.author = input("Enter Author of the Book: ")
def display(self):
print("Name of the Book: ",self.bookname)
print("Author of the Book: ",self.author)
print(“\n”)
www.tntextbooks.org
if(resp==1):
L=Library()
L.getdata()
book.append(L)
elif(resp==2):
for x in book:
x.display()
else:
print("Invalid input....")
Output:
1. Add New Book
2.Display Books
Enter your choice : 1
Enter Name of the Book: Programming in C++
Enter Author of the Book: K. Kannan
Do you want continue....y
class String:
def __init__(self):
self.uppercase=0
self.lowercase=0
self.vowels=0
self.consonants=0
self.spaces=0
self.string=""
def getstr(self):
self.string=str(input("Enter a String: "))
www.tntextbooks.org
def count_upper(self):
for ch in self.string:
if (ch.isupper()):
self.uppercase+=1
def count_lower(self):
for ch in self.string:
if (ch.islower()):
self.lowercase+=1
def count_vowels(self):
for ch in self.string:
if (ch in ('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'l', 'L')):
self.vowels+=1
def count_consonants(self):
for ch in self.string:
if (ch not in ('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'l', 'L')):
self.consonants+=1
def count_space(self):
for ch in self.string:
if (ch==" "):
self.spaces+=1
def execute(self):
self.count_upper()
self.count_lower()
self.count_vowels()
self.count_consonants()
self.count_space()
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.uppercase)
print("%d Lowercase letters"%self.lowercase)
print("%d Vowels"%self.vowels)
print("%d Consonants"%self.consonants)
print("%d Spaces"%self.spaces)
www.tntextbooks.org
S = String()
S.getstr()
S.execute()
S.display()
Output
Enter a String: Welcome To Learn Computer Science
The given string contains...
5 Uppercase letters
24 Lowercase letters
13 Vowels
20 Consonants
4 Spaces
Program 4: Write a program to store product and its cost price. Display all the
available products and prompt to enter quantity of all the products. Finally
generate a bill which displays the total amount to be paid
class MyStore:
__prod_code=[]
__prod_name=[]
__cost_price=[]
__prod_quant=[]
def getdata(self):
self.p = int(input("Enter no. of products you need to store: "))
for x in range(self.p):
self.__prod_code.append(int(input("Enter Product Code: ")))
self.__prod_name.append(str(input("Enter Product Name: ")))
self.__cost_price.append(int(input("Enter Cost price: ")))
www.tntextbooks.org
def display(self):
print("Stock in Stores")
print("----------------------------------------------------------")
print("Product Code \t Product Name \t Cost Price")
print("----------------------------------------------------------")
for x in range(self.p):
print(self.__prod_code[x], "\t\t", self.__prod_name[x], "\t\t", self.__cost_
price[x])
print("----------------------------------------------------------")
def print_bill(self):
total_price = 0
for x in range(self.p):
q=int(input("Enter the quantify for the product code %d : "%self.__
prod_code[x]))
self.__prod_quant.append(q)
total_price = total_price +self.__cost_price[x]*self.__prod_quant[x]
S=MyStore()
S.getdata()
S.display()
S.print_bill()
Output:
Enter no. of products you need to store: 5
Enter Product Code: 101
Enter Product Name: Product-A
Enter Cost price: 25
Enter Product Code: 201
Enter Product Name: Product-B
Enter Cost price: 35
Enter Product Code: 301
Enter Product Name: Product-C
Enter Cost price: 35
Enter Product Code: 401
Enter Product Name: Product-D
Enter Cost price: 50
Enter Product Code: 501
Enter Product Name: Product-E
Enter Cost price: 120
Stock in Stores
--------------------------------------------------------------------------------------
Product Code Product Name Cost Price
--------------------------------------------------------------------------------------
101 Product-A 25
201 Product-B 35
301 Product-C 35
401 Product-D 50
501 Product-E 120
--------------------------------------------------------------------------------------
www.tntextbooks.org
Invoice Receipt
---------------------------------------------------------------------------------------------------
Product Code Product Name Cost Price Quantity Total Amount
---------------------------------------------------------------------------------------------------
101 Product-A 25 10 250
201 Product-B 35 15 525
301 Product-C 35 10 350
401 Product-D 50 20 1000
501 Product-E 120 10 1200
----------------------------------------------------------------------------------------------
Total Amount = 3325
----------------------------------------------------------------------------------------------
Points to remember
Hands on Experience
1. Write a program using class to store name and marks of students in list and print total
marks.
2. Write a program using class to accept three sides of a triangle and print its area.
3. Write a menu driven program to read, display, add and subtract two distances.
Evaluation
Part - I
Part -II
1. What is class?
2. What is instantiation?
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
4. How will you create constructor in Python?
www.tntextbooks.org
Part -III
References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
www.tntextbooks.org
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
CHAPTER 11
Unit IV
DATABASE CONCEPTS
computer. A data may contain any character, operations to create a database, storing of
text, word or a number. data and for updating data, etc. DBMS also
provides protection and security to the
189
2. Reduced Redundancy In the modern world hard drives are very cheap, but earlier
when hard drives were too expensive, unnecessary repetition
of data in database was a big problem But DBMS follows
Normalisation which divides the data in such a way that
repetition is minimum.
4. Support Multiple user DBMS allows multiple users to work on it(update, insert,
and Concurrent Access delete data) at the same time and still manages to maintain the
data consistency.
5.Query Language DBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and updated
in a database.
6. Security The DBMS also takes care of the security of data, protecting
the data from unauthorized access. In a typical DBMS, we can
create user accounts with different access permissions, using
which we can easily secure our data by restricting user access.
7. DBMS Supports It allows us to better handle and manage data integrity in real
Transactions world applications where multi-threading is extensively used.
1. Hardware: The computer, hard disk, I/O Each table column represents a Field,
channels for data, and any other physical which groups each piece or item of data
component involved in storage of data among the records into specific categories or
types of data. Eg. StuNo., StuName, StuAge,
2. Software: This main component is
StuClass, StuSec.
a program that controls everything. The
DBMS software is capable of understanding A Table is known as a RELATION
the Database Access Languages and
A Row is known as a TUPLE
interprets into database commands for
execution. A column is known as an ATTRIBUTE
www.tntextbooks.org
Table / Relation
DataBase Structure
Fig 11.2
11.6 Data Model
• A data model describes how the data can be represented and accessed from a software after
complete implementation
• It is a simple abstraction of complex real world data gathering environment.
• The main purpose of data model is to give an idea as how the final system or software will
look like after development is completed.
• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model
1. Hierarchical Model
Hierarchical model was developed by IBM as Information Management System.
In Hierarchical model, data is represented as a simple tree like structure form. This
model represents a one-to-many relationship ie parent-child relationship. One child can have
only one parent but one parent can have many children. This model is mainly used in IBM
Main Frame computers.
www.tntextbooks.org
School
Course Resources
Theory Lab
2. Relational Model
The Relational Database model was first proposed by E.F. Codd in 1970 . Nowadays, it
is the most widespread data model used for database applications around the world.
The basic structure of data in relational model is tables (relations). All the information’s
related to a particular type is stored in rows of that table. Hence tables are also known as
relations in a relational model. A relation key is an attribute which uniquely identifies a
particular tuple (row in a relation (table)).
3. Network Model
Network database model is an extended form of hierarchical data model. The difference
www.tntextbooks.org
• In a Network model, a child may have many parent nodes. It represents the data in many-
to-many relationships.
• This model is easier and faster to access the data.
School
Library Office Staff Room This child has one parent node
Network Model
Fig. 11.5
5. Object Model
Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance. This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing. It is used in file
Management System. It represents real world objects, attributes and behaviors. It provides a
clear modular structure. It is easy to maintain and modify the existing code.
Shape
get_area()
get_perimeter()
An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects
in this model.
• Circle has the attribute radius.
• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
• The objects Circle, Rectangle and Triangle inherit from the object Shape.
management system. DBA takes care of the security of the DBMS, managing the license keys,
managing user accounts and access etc.
Database normalization was first proposed by Dr. Edgar F Codd as an integral part
www.tntextbooks.org
of RDBMS in order to reduce data redundancy and improve data integrity. These rules are
known as E F Codd Rules.
2. One-to-Many Relationship
Computer Bindhu
3. Many-to-One Relationship
4. Many-to-Many Relationship Tamil Radha
1. One-to-One Relationship
In One-to-One Relationship, one Maths Ramesh
entity is related with only one other entity.
One row in a table is linked with only one
row in another table and vice versa. Malaiarasu
STUDENT
Table 11.1
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical subset of
Relation.
Course
Big Data
R language
Python Programming
Note
duplicate row is removed in the result
www.tntextbooks.org
Table A Table B
Result
Table A B
-
cs4 Padmaja
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.
A∩B
cs1 Kannan
cs3 Lenin
1 S 1 S
2 1 R
R
3 2 S
2 R
Table A = 3
Table B = 2 3 S
Table A x B = 3 x 2 = 6
3 R
Cartesian Product
Fig. 11.12
Table A Table B
studno name studno subject
cs1 Kannan cs28 Big Data
www.tntextbooks.org
Points to remember:
• DBMS is a computer based record keeping system
• Data is unprocessed data which contains any character, text, word or number
has no meaning
• Information is processed data, organized and formatted.
• Examples of RDBMS are mysql, oracle, sql server, ibm db2
• Redundancy means duplication of data in a database.
• Data Consistency means that data values are the same at all instances of a
database
• Data Integrity is security from unauthorized users
• Table is known a relation
• A row is called a tuple
• A column is known as an attribute
• Types of data model are Hierarchical, Relational, Network, ER and Object
model.
• Hierarchical model is a simple tree like structure form with one-to-one
relationship called parent-child relationship
• Relational Model represents data as relations or tables
• Network model is similar to Hierarchical model but it allows a record to have
more than one parent
www.tntextbooks.org
Points to remember:
• Object model stores data as objects, attributes, methods, classes and inheritance
• Normalization reduces data redundancy and improves data integrity
• Different types of Relationship are one-to-one, one-to-many, many-to-one and
many-to-many relationships
• Database Normalization was proposed by Dr.Edgar F Codd
• Relational Algebra is used for modeling data stored in relational databases and
for defining queries on it.
Evaluation
Part - A
Part - B
CHAPTER 12
Unit IV
STRUCTURED QUERY LANGUAGE
Learning Objectives
Note
Latest SQL standard as of now is SQL 2008, released in 2008.
RDBMS stands for Relational DataBase Management System. Oracle, MySQL, MS SQL
Server, IBM DB2 and Microsoft Access are RDBMS packages. SQL is a language used to access
data in such databases.
205
In general, Database is a collection of tables that store sets of data that can be queried
for use in other applications. A database management system supports the development,
administration and use of database platforms. RDBMS is a type of DBMS with a row-based
table structure that connects related data elements and includes functions related to Create,
Read, Update and Delete operations, collectively known as CRUD.
The data in RDBMS, is stored in database objects, called Tables. A table is a collection
of related data entries and it consist of rows and columns.
A field is a column in a table that is designed to maintain specific related information
about every record in the table. It is a vertical entity that contains all information associated
with a specific field in a table. The fields in a student table may be of the type AdmnNo,
StudName, StudAge, StudClass, Place etc.
A Record is a row, which is a collection of related fields or columns that exist in a table.
A record is a horizontal entity in a table which represents the details of a particular student in
a student table.
XII
XII Std
Std Computer
Computer Science
Science 206
WAMP stands for “Windows, Apache, MySQL and PHP”. WAMP is a variation of
LAMP for windows systems and is installed as a software bundle (Apache, MySQL
and PHP). It is often used for web development and internal testing, but may also be used
to serve live websites.
The Data Definition Language (DDL) consist of SQL statements used to define the
database structure or schema. It simply deals with descriptions of the database schema and is
used to create and modify the structure of database objects in databases.
www.tntextbooks.org
The DDL provides a set of definitions to specify the storage structure and access
methods used by the database system.
1. It should identify the type of data division such as data item, segment, record and database
file.
2. It gives a unique name to each data item type, record type, file type and data base.
3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values that a data item may use.
6. It may specify privacy locks for preventing unauthorized data entry.
SQL commands which comes under Data Definition Language are:
Create To create tables in the database.
Truncate Remove all records from a table, also release the space occupied by those records.
XII
XII Std
Std Computer
Computer Science
Science 208
Delete Deletes all records from a table, but not the space occupied by them.
The data in a database is stored based on the kind of value stored in it. This is identified
www.tntextbooks.org
as the data type of the data or by assigning each field a data type. All the values in a given field
must be of same type.
The ANSI SQL standard recognizes only Text and Number data type, while some
commercial programs use other datatypes like Date and Time etc. The ANSI data types are
listed below in Table 12.1
Data Type Description
char Fixed width string value. Values of this type is enclosed in single quotes.
(Character) For ex. Anu’s will be written as ‘Anu’ ‘s’.
Variable width character string. This is similar to char except the size of the
varchar
data entry vary considerably.
It represents a fractional number such as 15.12, 0.123 etc. Here the size
argument consist of two parts : precision and scale. The precision indicates
dec (Decimal) how many digits the number may have and the scale indicates the maximum
number of digits to the right of the decimal point. The size (5, 2) indicates
precision as 5 and scale as 2. The scale cannot exceed the precision.
It is same as decimal except that the maximum number of digits may not
numeric
exceed the precision argument.
int It represents a number without a decimal point. Here the size argument is
(Integer) not used.
smallint It is same as integer but the default size may be smaller than Integer.
It is same as float, except the size argument is not used and may define a
real
precision up to a maximum of 64.
Tables are the only way to store data, therefore all the information has to be arranged in
the form of tables. The SQL provides a predetermined set of commands to work on databases.
Keywords They have a special meaning in SQL. They are understood as instructions.
www.tntextbooks.org
They are instructions given by the user to the database also known as
Commands
statements.
Clauses They begin with a keyword and consist of keyword and argument.
XII
XII Std
Std Computer
Computer Science
Science 210
Arguments They are the values given to make the clause complete.
Now let us use the above syntax to store some information about the students of a class
in a database, for this you first need to create table. To create a student table, let us take some
information related to students like admission number which we can use it in short form as
(admno), name of student (name), gender, age etc. of the student. Let us create a table having
the field names Admno, Name, Gender, Age and Place.
The SQL command will be as follows:
CREATE TABLE Student
(Admno integer,
Name char(20),
Gender char(1),
Age integer,
Place char(10),
);
The above one is a simple table structure without any restrictions. You can also set
constraints to limit the type of data that can go into the fields of the table. Constraints are used
to limit the type of data that can go into a table. This ensures the accuracy and reliability of the
data in the database. Constraints could be either on a column level or a table level.
Note
Constraint is a condition applicable on a field or set of fields.
Following is an example for student table with “NOT NULL” column constraint. This
constraint enforces a field to always contain a value.
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20)NOT NULL,
Gender char(1),
Age integer,
Place char(10),
);
The above command creates a table “student” in which the field Admno of integer type
is defined NOT NULL, Name of char type is defined as NOT NULL which means these two
fields must have values. The fields Gender, Age and Place do not have any constraints.
12.7.2 Type of Constraints
Constraints ensure database integrity, therefore known as database integrity constraints.
The different types of constraints are :
Unique Constraint
Primary Key Constraint
Constraint
Default Constraint
Check Constraint
(i)Unique Constraint
This constraint ensures that no two rows have the same value in the specified columns.
For example UNIQUE constraint applied on Admno of student table ensures that no two
students have the same admission number and the constraint can be used as:
www.tntextbooks.org
XII
XII Std
Std Computer
Computer Science
Science 212
The UNIQUE constraint can be applied only to fields that have also been declared as
NOT NULL.
When two constraints are applied on a single field, it is known as multiple constraints. In
the above Multiple constraints NOT NULL and UNIQUE are applied on a single field Admno,
the constraints are separated by a space and at the end of the field definition a comma(,) is
added. By adding these two constraints the field Admno must take some value ie. will not be
NULL and should not be duplicated.
In the above example the Admno field has been set as primary key and therefore will
help us to uniquely identify a record, it is also set NOT NULL, therefore this field value cannot
be empty.
(iii) DEFAULT Constraint
www.tntextbooks.org
The DEFAULT constraint is used to assign a default value for the field. When no value
is given for the specified field having DEFAULT constraint, automatically the default value will
be assigned to the field.
In the above example the “Age” field is assigned a default value of 17, therefore when no
value is entered in age by the user, it automatically assigns 17 to Age.
(iv) Check Constraint
This constraint helps to set a limit value placed for a field. When we define a check
constraint on a single column, it allows only the restricted values on that field. Example
showing check constraint in the student table:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer (CHECK<=19), → Check Constraint
Place char(10),
);
In the above example the check constraint is set to Age field where the value of Age
must be less than or equal to 19.
Note
The check constraint may use relational and logical operators for condition.
XII
XII Std
Std Computer
Computer Science
Science 214
The order of values must match the order of columns in the CREATE TABLE command.
Specifying the column names is optional if data is to be added for all columns. The command
to add values into the student table can also be used in the following way:
INSERT INTO Student VALUES ( 102, ‘Akshith’, ‘M’, ‘17,’ ‘Bangalore’);
102 Akshith M 17 Bangalore
www.tntextbooks.org
The above command inserts the record into the student table.
To add data to only some columns in a record by specifying the column name and their data,
it can be done by:
In the INSERT command the fields that are omitted will have either default value
defined or NULL value.
The table will be empty now and could be destroyed using the DROP command
(Discussed in section 12.7.4.3).
XII
XII Std
Std Computer
Computer Science
Science 216
To add a new column “Address” of type ‘char’ to the Student table, the command is used as
ALTER TABLE Student ADD Address char;
To modify existing column of table, the ALTER TABLE command can be used with MODIFY
clause like wise:
ALTER <table-name> MODIFY<column-name><data type><size>;
For example to rename the column Address to City, the command is used as :
ALTER TABLE Student RENAME Address TO City;
The ALTER command can also be used to remove a column or all columns, for example
to remove a particular column, the DROP COLUMN is used with the ALTER TABLE to
remove a particular field, the command can be used as:
ALTER <table-name> DROP COLUMN <column-name>;
To remove the column City from the Student table, the command is used as :
For example to delete all the records of the student table and delete the table the SQL statement
is given as follows:
TRUNCATE TABLE Student;
The table Student is removed and the space is freed.
drop a table, all the rows in the table is deleted and the table structure is removed from the
database. Once a table is dropped we cannot get it back, so be careful while using DROP
TABLE command. But there is a condition for dropping a table; it must be an empty table.
XII
XII Std
Std Computer
Computer Science
Science 218
Remove all the rows of the table using DELETE command. The DELETE command is already
explained.
To delete all rows, the command is given as :
DELETE * FROM Student;
Once all the rows are deleted, the table can be deleted by DROP TABLE command in the
following way:
DROP TABLE table-name;
The DELETE command deletes only the rows from the table based on
the condition given in the where clause or deletes all the rows from the
DELETE
table if no condition is specified. But it does not free the space containing
the table.
The TRUNCATE command is used to delete all the rows, the structure
TRUNCATE
remains in the table and free the space containing the table.
The DROP command is used to remove an object from the database. If you
DROP drop a table, all the rows in the table is deleted and the table structure is
removed from the database. Once a table is dropped we cannot get it back.
SELECT <column-list>FROM<table-name>;
• Table-name is the name of the table from which the information is retrieved.
For example to view only admission number and name of students from the Student table the
command is given as follows:
In the above output you can see, there would be no duplicate rows in the place field.
When the keyword DISTINCT is used, only one NULL value is returned, even if more NULL
values occur.
XII
XII Std
Std Computer
Computer Science
Science 220
For example to display the students admission number and name of only those students who
belong to Chennai, the SELECT command is used in the following way :
SELECT Admno, Name, Place FROM Student WHERE Place =”Chennai”;
106 Devika 19
The relational operators like =, <, <=, >, >=, <> can be used to compare two values in
the SELECT command used with WHERE clause. The logical operaors OR, AND and NOT
can also be used to connect search conditions in the WHERE clause. For example :
SELECT Admno, Name, Age, Place FROM Student WHERE (Age>=18 AND Place = "Delhi");
The NOT BETWEEN is reverse of the BETWEEN operator where the records not satisfying
the condition are displayed.
SELECT Admno, Name, Age FROM Student WHERE Age NOT BETWEEN 18 AND 19;
(iv) IN Keyword
The IN keyword is used to specify a list of values which must be matched with the
record values. In other words it is used to compare a column with more than one value. It is
similar to an OR condition.
www.tntextbooks.org
For example :
SELECT Admno, Name, Place FROM Student WHERE Place IN (“Chennai”, “Delhi”);
XII
XII Std
Std Computer
Computer Science
Science 222
For example:
SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (“Chennai”, “Delhi”);
will display students only from places other than “Chennai” and “Delhi”.
Admno Name Age
102 Akshith Bangalore
106 Devika Bangalore
NULL Value :
The NULL value in a field can be searched in a table using the IS NULL in the WHERE
clause. For example to list all the students whose Age contains no value, the command is used
as:
SELECT * FROM Student WHERE Age IS NULL;
Note
Non NULL values in a table can be listed using IS NOT NULL.
For example :
To display the students in alphabetical order of their names, the command is used as
Note
The ORDER BY clause does not affect the original table.
XII
XII Std
Std Computer
Computer Science
Science 224
Note
Sorting can be done on multiple fields.
Gender count(*)
M 5
F 3
Note
The * is used with the COUNT to include the NULL values.
The GROUP BY applies the aggregate functions independently to a series of groups that
are defined by having a field value in common. The output of the above SELECT statement
gives a count of the number of Male and Female students.
Gender count(*)
M 2
F 2
The above output shows the number of Male and Female students in Chennai from the
table student.
COMMIT;
with SAVEPOINT command to jump to a particular savepoint location. The syntax for the
ROLLBACK command is :
ROLL BACK TO save point name;
XII
XII Std
Std Computer
Computer Science
Science 226
ROLLBACK TO A;
Points to remember:
• SQL is a language that helps to create and operate relational databases.
• MySQL is a database management system.
• The various components of SQL are Data Definition Language (DDL), Data
Manipulation Language (DML), Data Query Language (DQL), Transactional
Control Language (TCL), Data Control Language (DCL).
• The DDL provides statements for creation and deletion of tables.
• The DML provides statements to insert, update and delete data of a table.
• The DCL provides authorization commands to access data.
• The TCL commands are used to manage transactions in a database.
www.tntextbooks.org
XII
XII Std
Std Computer
Computer Science
Science 228
Points to remember:
• SQL is a language that helps to create and operate relational databases.
• MySQL is a database management system.
• The various components of SQL are Data Definition Language (DDL), Data
Manipulation Language (DML), Data Query Language (DQL), Transactional
Control Language (TCL), Data Control Language (DCL).
• The DDL provides statements for creation and deletion of tables.
• The DML provides statements to insert, update and delete data of a table.
• The DCL provides authorization commands to access data.
• The TCL commands are used to manage transactions in a database.
• The DQL commands help to generate queries in a database.
• The CREATE TABLE command creates a new table.
Hands on Experience
1. Create a query of the student table in the following order of fields name, age, place and
admno.
2. Create a query to display the student table with students of age more than 18 with unique
city.
3. Create a employee table with the following fields employee number, employee name,
designation, date of joining and basic pay.
4. In the above table set the employee number as primary key and check for NULL values in
any field.
Evaluation
Part - I
Part -II
XII
XII Std
Std Computer
Computer Science
Science 230
Part -III
CHAPTER 13
Unit IV
PYTHON AND CSV FILES
Learning Objectives
13.1 Introduction
Python has a vast library of modules that are included with its distribution. One among
the module is the CSV module which gives the Python programmer the ability to parse CSV
(Comma Separated Values) files. A CSV file is a human readable text file where each line
has a number of fields, separated by commas or some other delimiter. You can assume each
line as a row and each field as a column. The CSV module will be able to read and write the vast
majority of CSV files.
13.2 Difference between CSV and XLS file formats
The difference between Comma-Separated Values (CSV) and eXceL Sheets(XLS) file
formats is
Excel CSV
Excel is a binary file that holds information CSV format is a plain text format with a
about all the worksheets in a file, including series of values separated by commas.
both content and formatting
XLS files can only be read by applications CSV can be opened with any text editor
that have been especially written to read their in Windows like notepad, MS Excel,
format, and can only be written in the same OpenOffice, etc.
way.
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv
www.tntextbooks.org
Excel consumes more memory while Importing CSV files can be much faster, and
importing data it also consumes less memory
CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
Since they're plain text, they're easier to import into a spreadsheet or another storage database,
regardless of the specific software you're using.
You can open CSV files in a spreadsheet program like Microsoft Excel or in a text editor
or through a database which make them easier to read.
Note
CSV File cannot store charts or graphs. It stores data but does not contain
formatting, formulas, macros, etc.
A CSV file is also known as a Flat File. Files in the CSV format can be
imported to and exported from programs that store data in tables, such as Microsoft
Excel or OpenOfficeCalc
13.4 Creating a CSV file using Notepad (or any text editor)
A CSV file is a text file, so it can be created and edited using any text editor, But more
frequently a CSV file is created by exporting a spreadsheet or database in the program that
created it.
Save this content in a file with the extension .csv . You can then open the same using
Microsoft Excel or any other spreadsheet program. Here we have opened using Microsoft
Excel. It would create a table of data similar to the following:
In the above CSV file, you can observe the fields of data were separated by commas. But
what happens if the data itself contains commas in it?
If the fields of data in your CSV file contain commas, you can protect them by enclosing
those data fields in double-quotes (“). The commas that are part of your data will then be kept
separate from the commas which delimit the fields themselves.
To retain the commas in “Address” column, you can enclose the fields in quotation
marks. For example:
As you can see, only the fields that contain commas are enclosed in quotes. If you open
this in MS Excel, It looks like as follows
The same goes for newlines which may be part of your field data. Any fields containing
a newline as part of its data need to be enclosed in double-quotes.
For Example
RollNo Name Address
12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai
12103 Ram Gopalapuram, Chennai
13.4.3 Creating CSV File That contains Double Quotes With Data
If your fields contain double-quotes as part of their data, the internal quotation
marks need to be doubled so that they can be interpreted correctly. For Example, given the
following data:
2. The last record in the file may or may not have an ending line break. For example:
ppp, qqq
yyy, xxx
3. There may be an optional header line appearing as the first line of the file with the same
format as normal record lines. The header will contain names corresponding to the fields
in the file and should contain the same number of fields as the records in the rest of the
file. For example: field_name1,field_name2,field_name3
www.tntextbooks.org
aaa,bbb,ccc
zzz,yyy,xxx CRLF( Carriage Return and Line Feed)
4. Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored. The last field in the record
must not be followed by a comma. For example: Red , Blue
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes. For example:
Red, “,”, Blue CRLF # comma itself is a field value.so it is enclosed with double quotes
Red, Blue , Green
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field
must be preceded with another double quote. For example:
“Red, ” “Blue”, “Green”, # since double quotes is a field value it is enclosed with another double quotes
, , White
Note
The last row in the above example begins with two commas because the first two
fields of that row were empty in our spreadsheet. Don't delete them — the two commas
are required so that the fields correspond from row to row. They cannot be omitted.
To create a CSV file using Microsoft Excel, launch Excel and then open the file you
want to save in CSV format. For example, below is the data contained in our sample Excel
worksheet: www.tntextbooks.org
Python provides a module named CSV, using this you can do several operations on the
CSV files. The CSV library contains objects and other code to read, write, and process data
from and to CSV files.
When you want to read from or write to a file ,you need to open it. Once the reading
is over it needs to be closed. So that, resources that are tied with the file are freed. Hence, in
Python, a file operation takes place in the following order
Note
File name or the complete path name can be represented either with in “ “ or in ‘ ‘
in the open command.
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
For Example
You can specify the mode while opening a file. In mode, you can specify whether you
want to read 'r', write 'w' or append 'a' to the file. you can also specify “text or binary” in which
the file is to be opened.
The default is reading in text mode. In this mode, while reading from the file the data
would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a new file
if it does not exist.
't' Opren in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
f=open("sample.txt")
#equivalent to 'r' or 'rt'
f = open("sample.txt",'w') # write in text mode
f = open("image1.bmp",'r+b') # read and write in binary mode
Python has a garbage collector to clean up unreferenced objects but, one must not
rely on it to close the file.
The above method is not entirely safe. If an exception occurs when you are performing
some operation with the file, the code exits without closing the file. The best way to do this is
using the “with” statement. This ensures that the file is closed when the block inside with is
exited. You need not to explicitly call the close() method. It is done internally.
with open("test.txt",’r’) as f:
# f is file object to perform file operations
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
f = open("sample.txt")
# perform file operations
f.close()
from csv files of different formats like quotes (" "), pipe (|) and comma (,).
The syntax for csv.reader() is
csv.reader(fileobject,delimiter,fmtparams)
where
file object :- passes the path and the mode of the file
delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
fmtparams: optional parameter which help to override the default values of the dialects like
skipinitialspace,quoting etc. Can be omitted
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
As you can see in “sample2.csv” there are spaces after the delimiter due to which the
output is also displayed with spaces.
Note
By default “skipinitialspace” has a value false
The following program reads “sample2.csv” file, which contains spaces after the delimiter.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
www.tntextbooks.org
Note
A dialect is a class of csv module which helps to define parameters for
reading and writing CSV. It allows you to create, store, and re-use various formatting
parameters for your data.
SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."
3, "Work hard dream big never give up and believe yourself."
4, "Failure is the opportunity to begin again more intelligently."
5, "The successful warrior is the average man, with laser-like focus."
The following Program read “quotes.csv” file, where delimiter is comma (,) but the
quotes are within quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,
skipinitialspace=True)
f=open('c:\\pyprg\\quotes.csv','r')
reader = csv.reader(f, dialect='myDialect')
for row in reader:
print(row)
OUTPUT
['SNO', 'Quotes']
['1', 'The secret to getting ahead is getting started.']
['2', 'Excellence is a continuous process and not an accident.']
['3', 'Work hard dream big never give up and believe yourself.']
['4', 'Failure is the opportunity to begin again more intelligently.']
['5', 'The successful warrior is the average man, with laser-like focus. ']
www.tntextbooks.org
In the above program, register a dialect with name myDialect. Then, we used csv.
QUOTE_ALL to display all the characters after double quotes.
The following program read the file “sample4.csv” with user defined delimiter “|”
import csv
csv.register_dialect('myDialect', delimiter = '|') OUTPUT
with open('c:\\pyprg\\sample4.csv', 'r') as f: ['RollNo', 'Name', 'City']
reader = csv.reader(f, dialect='myDialect') ['12101', 'Arun', 'Chennai']
for row in reader: ['12102', 'Meena', 'Kovai']
print(row) ['12103', 'Ram', 'Nellai']
f.close()
In the above program, a new dialects called myDialect is registered. Use the delimiter=|
where a pipe (|) is considered as column separator.
import csv
#opening the csv file which is in different location with read mode
f=open("c:\\pyprg\\ch13sample5.csv",'r')
#reading the File with the help of csv.reader()
readFile=csv.reader(f)
#printing the selected column
for col in readFile :
print col[0],col[3]
f.close()
www.tntextbooks.org
A B C D
OUTPUT
Item Name Profit
Keyboard 1152
Monitor 10400
Mouse 2000
import csv
# other way of declaring the filename
inFile= 'c:\\pyprg\\sample.csv'
F=open(inFile,'r')
reader = csv.reader(F)
# declaring array
arrayValue = []
# displaying the content of the list
for row in reader:
arrayValue.append(row)
print(row)
F.close()
sample.csv opened in MS-Excel
www.tntextbooks.org
A1 fx Topic 1
>
A B C
1 Topic 1 Topic 2 Topic 3
2 One two three
3 Example 1 Example 2 Example 3
4
sample5.csv File with selected col
OUTPUT
['Topic1', 'Topic2', 'Topic3']
[' one', 'two', 'three']
['Example1', 'Example2', 'Example3']
Note
A list is a data structure in Python that is a mutable, or changeable,
ordered sequence of elements.
List literals are written within square brackets [ ]. Lists work similarly to strings
13.6.4 Read A CSV File And Store A Column Value In A List For Sorting
In this program you are going to read a selected column from the “sample6.csv” file by
getting from the user the column number and store the content in a list.
www.tntextbooks.org
Fig 13.6.4 CSV file Data for a selected column for sorting
Since the row heading is also get sorted, to avoid that the first row should be skipped.
This is can be done by using the command “next()”. The list is sorted and displayed.
www.tntextbooks.org
python file
F=open(inFile,’r’)
# reading the File with the help of csv.reader()
reader = csv.reader(F)
# skipping the first row(heading)
next(reader)
# declaring a list
arrayValue = []
a = int(input (“Enter the column number 1 to 3:-“))
# sorting a particular column-cost
for row in reader:
arrayValue.append(row[a])
arrayValue.sort()
for row in arrayValue:
print (row)
F.close()
OUTPUT
Enter the column number 1 to 3:- 2
50
12
10
Read a specific column in a csv file and display its result in Descending
(Reverse) order.
sample8.csv in Notepad
ItemName ,Quantity
Keyboard, 48
Monitor,52
Mouse ,20
[‘Mouse ‘, ‘20’]
[‘Keyboard ‘, ‘48’]
[‘Monitor’, ‘52’]
Note
The sorted() method sorts the elements of a given item in a specific order –
Ascending or Descending. Sort() method which performs the same way as sorted().
Only difference, sort() method doesn’t return any value and changes the original list
itself.
Add one more column “cost” in “sample8.csv” and sort it in descending order
of cost by using the syntax
sortedlist = sorted(data, key=operator.itemgetter(Col_number),reverse=True)
In the above program, DictReader() is used to read “sample8.csv” file and map into
a dictionary. Then, the function dict() is used to print the data in dictionary format without
order.
XII Std Computer Science 252
252
Remove the dict() function from the above program and use print(row).Check
you are getting the following output
OrderedDict([(‘ItemName ‘, ‘Keyboard ‘), (‘Quantity’, ‘48’)])
OrderedDict([(‘ItemName ‘, ‘Monitor’), (‘Quantity’, ‘52’)])
OrderedDict([(‘ItemName ‘, ‘Mouse ‘), (‘Quantity’, ‘20’)])
13.6.7 Reading CSV File With User Defined Delimiter Into A Dictionary
You can also register new dialects and use it in the DictReader() methods. Suppose
“sample8.csv” is in the following format
ItemName Quantity
Keyboard 48
Monitor 52
Mouse 20
Then “sample8.csv” can be read into a dictionary by registering a new dialect
import csv
csv.register_dialect(‘myDialect’,delimiter = ‘|’,skipinitialspace=True)
filename = ‘c:\\pyprg\\ch13\\sample8.csv’
with open(filename, ‘r’) as csvfile:
reader = csv.DictReader(csvfile, dialect=’myDialect’)
for row in reader:
print(dict(row))
csvfile.close()
OUTPUT
{‘ItemName ,Quantity’: ‘Keyboard ,48’}
{‘ItemName ,Quantity’: ‘Monitor,52’}
{‘ItemName ,Quantity’: ‘Mouse ,20’}
Note
DictReader() gives OrderedDict by default in its output. An OrderedDict is a
dictionary subclass which saves the order in which its contents are added. To remove the
OrderedDict use dict().
As you know Python provides an easy way to work with CSV file and has csv module
to read and write data in the csv file. In the previous topics, You have learned how to read CSV
files in Python. In similar way, You can also write a new or edit an existing CSV files in Python.
253 Python and CSV files
The csv.writer() method returns a writer object which converts the user’s data into
delimited strings on the given file-like object. The writerow() method writes a row of data
into the specified file.
The syntax for csv.writer() is
csv.writer(fileobject,delimiter,fmtparams)
where
fileobject : passes the path and the mode of the file.
delimiter : an optional parameter containing the standard dilects like , | etc can
be omitted.
fmtparams : optional parameter which help to override the default values of the
dialects like skipinitialspace,quoting etc. can be omitted.
You can create a normal CSV file using writer() method of csv module having
default delimiter comma (,)
Here’s an example.
www.tntextbooks.org
The following Python program converts a List of data to a CSV file called “Pupil.csv”
that uses, (comma) as a value separator.
Import csv
csvData = [[‘Student’, ‘Age’], [‘Dhanush’, ‘17’], [‘Kalyani’, ‘18’], [‘Ram’, ‘15’]]
with open(‘c:\\pyprg\\ch13\\Pupil.csv’, ‘w’) as CF:
writer = csv.writer(CF) # CF is the file object
writer.writerows(csvData) # csvData is the List name
CF.close()
When you open the “Pupil.csv” file with a text editor, it will show the content as
follows.
Student, Age
Keyboard 17
Monitor 18
Mouse 15
In the above program, csv.writer() method converts all the data in the list “csvData” to
strings and create the content as file like object. The writerows () method writes all the data in
to the new CSV file “Pupil.csv”.
Note
The writerow() method writes one row at a time. If you need to write all the data at
once you can use writerows() method.
The following program modify the “student.csv” file by modifying the value of an
existing row in student.csv
www.tntextbooks.org
import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, ‘r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines[3] = row
with open(‘student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile)
#writerows()method writes multiple rows to a csv file
writer.writerows(lines)
readFile.close()
writeFile.close()
When we open the student.csv file with text editor, then it will show:
1 Harshini, Chennai
2 Adhith, Mumbai
3 Dhuruv, Bengaluru
4 egiste, Tiruchy
5 Venkat, Madurai
In the above program,the third row of “student.csv” is modified and saved. First the
“student.csv” file is read by using csv.reader() function. Then, the list() stores each row of the
file. The statement “lines[3] = row”, changed the third row of the file with the new content in
“row”. The file object writer using writerows (lines) writes the values of the list to “student.csv”
file.
import csv
row = [‘6’, ‘Sajini ‘, ‘Madurai’]
with open(‘student.csv’, ‘a’) as CF: # append mode to add data at the end
writer = csv.writer(CF)
writer.writerow(row) # writerow() method write a single row of data in file
CF.close()
1 Harshini, Chennai
2 Adhith, Mumbai
3 Meena Bengaluru
4 egiste, Tiruchy
5 Venkat, Madurai
6 Sajini , Madurai
In the above program, a new row is appended into “student.csv”. For this, purpose only
the CSV file is opened in ‘a’ append mode. Append mode write the value of row after the last
line of the “student.csv file.”
The ‘w’ write mode creates a new file. If the file is already existing ‘w’ mode
over writs it. Where as ‘a’ append mode add the data at the end of the file if the file
already exists otherwise creates a new one.
Note
writerow() takes 1-dimensional data (one row), and writerows takes 2-dimensional
data (multiple rows) to write in a file.
import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],
[‘1’, ‘Madhu’, ‘18/12/2001’],
[‘2’, ‘Sowmya’,’19/2/1998’],
[‘3’, ‘Sangeetha’,’20/3/1999’],
[‘4’, ‘Eshwar’, ‘21/4/2000’],
[‘5’, ‘Anand’, ‘22/5/2001’]]
csv.register_dialect(‘myDialect’,quoting=csv.QUOTE_ALL)
with open(‘c:\\pyprg\\ch13\\person.csv’, ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect’)
for row in info:
writer.writerow(row)
f.close()
When you open “person.csv” file, we get following output :
“SNO”,”Person”,”DOB” ”1”,”Madhu”,”18/12/2001”
”2”,”Sowmya”,”19/2/1998” ”3”,”Sangeetha”,”20/3/1999”
”4”,”Eshwar”,”21/4/2000”
“5”,”Anand”,”22/5/2001”
import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],
[‘1’, ‘Madhu’, ‘18/12/2001’],
[‘2’, ‘Sowmya’,’19/2/1998’],
[‘3’, ‘Sangeetha’,’20/3/1999’],
[‘4’, ‘Eshwar’, ‘21/4/2000’],
[‘5’, ‘Anand’, ‘22/5/2001’]]
csv.register_dialect(‘myDialect’,delimiter = ‘|’)
with open(‘c:\pyprg\ch13\dob.csv’, ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect’)
www.tntextbooks.org
Note
The dialect parameter skipinitialspace when it is True, whitespace immediately following
the delimiter is ignored. The default is False.
import csv
Data = [[‘Fruit’, ‘Quantity’], [‘Apple’, ‘5’], [‘Banana’, ‘7’], [‘Mango’, ‘8’]]
csv.register_dialect(‘myDialect’, delimiter = ‘|’, lineterminator = ‘\n’)
with open(‘c:\\pyprg\\ch13\\line.csv’, ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect’)
writer.writerows(Data)
f.close()
When we open the line.csv file, we get following output with spacing between lines:
Fruit Quantity
Apple 5
Banana 7
Mango 8
In the above code, the new dialect “myDialect uses the delimiter=’|’ where a | (pipe) is
considered as column separator. The line terminator=’\r\n\r\n’ separates each row and display
www.tntextbooks.org
Note
Python’s CSV module only accepts \r\n, \n or \r as line terminator.
import csv
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], [‘3’,’Pencil’]]
csv.register_dialect(‘myDialect’,delimiter = ‘|’,quotechar = ‘”’,
quoting=csv.QUOTE_ALL)
with open(‘c:\\pyprg\\ch13\\quote.csv’, ‘w’) as csvFile:
writer = csv.writer(csvFile, dialect=’myDialect’)
writer.writerows(csvData)
print(“writing completed”)
csvFile.close()
When you open the “quote.csv” file in notepad, we get following output:
Sl.No ”Items”
1 ”Pen”
2 ”Book”
3 ”Pencil”
In the above program, myDialect uses pipe (|) as delimiter and quotechar as doublequote
‘”’ to write inside the file.
13.7.7 Writing CSV File Into A Dictionary
Using DictWriter() class of csv module, we can write a csv file into a dictionary. It
creates an object which maps data into a dictionary. The keys are given by the fieldnames
parameter. The following program helps to write the dictionary in to file.
import csv
data = [{‘MOUNTAIN’ : ‘Everest’, ‘HEIGHT’: ‘8848’},
{‘MOUNTAIN’ : ‘Anamudi ‘, ‘HEIGHT’: ‘2695’},
{‘MOUNTAIN’ : ‘Kanchenjunga’, ‘HEIGHT’: ‘8586’}]
with open(‘c:\\pyprg\\ch13\\peak.csv’, ‘w’) as CF:
fields = [‘MOUNTAIN’, ‘HEIGHT’]
w = csv.DictWriter(CF, fieldnames=fields)
w.writeheader()
www.tntextbooks.org
w.writerows(data)
print(“writing completed”)
CF.close()
When you open the “peak.csv” file in notepad, you get the following output:
MOUNTAIN, HEIGHT
Everest, 8848
Anamudi , 2695
Kanchenjunga, 8586
In the above program, use fieldnames as headings of each column in csv file. Then, use
a DictWriter() to write dictionary data into “peak.csv” file.
13.7.7.1 Writing Dictionary Into CSV File With Custom Dialects
import csv
csv.register_dialect(‘myDialect’, delimiter = ‘|’, quoting=csv.QUOTE_ALL)
with open(‘c:\\pyprg\\ch13\\grade.csv’, ‘w’) as csvfile:
fieldnames = [‘Name’, ‘Grade’]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=”myDialect”)
writer.writeheader()
writer.writerows([{‘Grade’: ‘B’, ‘Name’: ‘Anu’},
{‘Grade’: ‘A’, ‘Name’: ‘Beena’},
{‘Grade’: ‘C’, ‘Name’: ‘Tarun’}])
print(“writing completed”)
“Name” ”Grade”
”Anu” ”B”
”Beena” ”A”
“Tarun” ”C”
In the above program, a custom dialect called myDialect with pipe (|) as delimiter uses
the fieldnames as headings of each column to write in a csv file. Finally, we use a DictWriter()
to write dictionary data into “grade.csv” file.
import csv
with open(‘c:\\pyprg\\ch13\\dynamicfile.csv’, ‘w’) as f:
w = csv.writer(f)
ans=’y’
while (ans==’y’):
name = input(“Name?: “)
date = input(“Date of birth: “)
place = input(“Place: “)
w.writerow([name, date, place])
ans=input(“Do you want to enter more y/n?: “)
F=open(‘c:\\pyprg\\ch13\\dynamicfile.csv’,’r’)
reader = csv.reader(F)
for row in reader:
print(row)
F.close()
OUTPUT
Name?: Nivethitha
Date of birth: 12/12/2001
Place: Chennai
Do you want to enter more y/n?: y
Name?: Leena
Date of birth: 15/10/2001
Place: Nagercoil
Do you want to enter more y/n?: y
H8 fx
>
Name?: Padma A B C
Date of birth: 18/08/2001 1 Nivethitha 12/12/2001 Chennai
Place: Kumbakonam 2
Do you want to enter more y/n?: n 3 Leena 15/10/2001 Nagercoil
[‘Nivethitha’, ‘12/12/2001’, ‘Chennai’] 4
[] 5 Padma 18/08/2001 Kumbakonam
[‘Leena’, ‘15/10/2001’, ‘Nagercoil’] 6
[]
[‘Padma’, ‘18/08/2001’, ‘Kumbakonam’]
www.tntextbooks.org
Points to remember:
• A CSV file is a human readable text file where each line has a number of fields, separated
by commas or some other delimiter
• Excel is a binary file whereas CSV format is a plain text format
• The two ways to read a CSV file are using csv.reader() function and using DictReader
class.
• The default mode of csv file in reading and writing is text mode
• Binary mode can be be used when dealing with non-text files like image or exe files.
• Python has a garbage collector to clean up unreferenced objects
• close() method will free up the resources that were tied with the file
• By default CSV files should open automatically in Excel
• The CSV library contains objects and other code to read, write, and process data from
and to CSV files.
• “skipinitialspace” is used for removing whitespaces after the delimiter
• To sort by more than one column operator.itemgetter() can be used
• DictReader() class of csv module creates an object which maps data to a dictionary
• CSV file having custom delimiter is read with the help of csv.register_dialect().
• To sort by more than one column itemgetter() with multiple indices is used.
• csv.reader and csv.writer work with list/tuple, while csv.DictReader and csv.DictWriter
work with dictionary .
• csv.DictReader and csv.DictWriter take additional argument fieldnames that are used
as dictionary keys.
• The function dict() is used to print the data in dictionary format without order.
• The csv.writer() method returns a writer object which converts the user’s data into
delimited strings.
• The writerow() method writes one row at a time. Writerows() method is used to write
all the data at once
• Adding a new row at the end of the file is called appending a row.
www.tntextbooks.org
Hands on Experience
1. Write a Python program to read the following Namelist.csv file and sort the data in
alphabetically order of names in a list and display the output
A B C
1 SNO NAME OCCUPATION
2 1 NIVETHITHA ENGINEER
3 2 ADHITH DOCTOR
4 3 LAVANYA SINGER
5 4 VIDHYA TEACHER
6 5 BINDHU LECTURER
2. Write a Python program to accept the name and five subjects mark of 5 students .Find
the total and store all the details of the students in a CSV file
Evaluation
Part - I
4. Which of the following mode is used when dealing with non-text files like image or exe files?
(A) Text mode (B) Binary mode
(C) xls mode (D) csv mode
5. The command used to skip a row in a CSV file is
(A) next() (B) skip()
(C) omit() (D) bounce()
6. Which of the following is a string used to terminate lines produced by writer()method of
csv module?
(A) Line Terminator (B) Enter key
(C) Form feed (D) Data Terminator
7. What is the output of the following program? import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d:
print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
mumbai,andheri
import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
Part - II
Part - III
Part - IV
1. Python for Data Analysis, Data Wrangling with Pandas, NumPy, and IPython By
www.tntextbooks.org
William McKinney
2. CSV File Reading and Writing - Python 3.7.0 documentation
3. https://docs.python.org
XII Std Computer Science 266
266
CHAPTER 14
Unit V
IMPORTING C++ PROGRAMS IN PYTHON
Learning Objectives
14.1 Introduction
Python and C++ are general-purpose programming language. However, Python is
quite different from C++.
Yet these two languages complement one another perfectly. Python is mostly used as a
scripting or "glue", language. That is, the top level program mostly calls routines written in C
or C++. This is useful when the logic can be written in terms of existing code (For example a
program written in C++) but can be called and manipulated through Python program.
www.tntextbooks.org
9
6
Basically, all scripting languages are programming languages. The theoretical difference
between the two is that scripting languages do not require the compilation step and are rather
interpreted. For example, normally, a C++ program needs to be compiled before running
whereas, a scripting language like JavaScript or Python need not be compiled. A scripting
language requires an interpreter while a programming language requires a compiler. A given
language can be called as a scripting or programming language depending on the environment
they are put to use.
numbers, images, scientific data and just about anything else you might save on a computer.
Now a days, large applications are written almost exclusively in Python.
Note
Python deletes unwanted objects (built-in types or class instances) automatically
to free the memory space. The process by which Python periodically frees and reclaims
blocks of memory that no longer are in use is called Garbage Collection.
MinGw-W64 (version of MinGW) is the best compiler for C++ on Windows. To compile
and execute the C++ program, you need ‘g++’ for Windows. MinGW allows to compile and
execute C++ program dynamically through Python program using g++.
269
Importing C++ programs in Python
Python program that contains the C++ coding can be executed only through
minGW-w64 project’ run terminal. The run terminal open the command-line window through
which Python program should be executed.
g++ is a program that calls GCC (GNU C Compiler) and automatically links the
required C++ library files to the object code.
cd <absolute path>
where “cd” command refers to change directory and absolute path refers to the complete
path where Python is installed.
Figure 14.1
In this Example to go to the folder where Python is located we should type the following
command “cd C:\Program Files\OpenOffiice 4\Program”. See that highlighted area in the
above window.
Consider the Example pycpp.py is a Python program which will read the C++program
Pali.cpp. The “Pali.cpp” program accepts a number and display whether it is a “Palindrome or
www.tntextbooks.org
Not”. For example the entered input number is 232 the output displayed will be “Palindrome”.
The C++ program Pali is typed in notepad and saved as pali.cpp. Same way the Python
program pycpp.py code is also typed in notepad and saved as pycpp.py.
3. To execute our program double click the run terminal change the path to the Python
folder location. The syntax to execute the Python program is
Python <filename.py> -i <C++ filename without cpp extension>
Where,
-i input mode
For example type Python pycpp.py –i pali in the command prompt and press enter key.
If the compilation is successful you will get the desired output. Otherwise the error will be
displayed.
Note
In the execution command, the input file doesn’t require its extension. For
example, it is enough to mention just the name “pali” instead of “pali.cpp”.
Now let us will see the execution through our example pycpp.py and pali.cpp. These
two programs are stored in the folder c:\pyprg. If the programs are not located in same folder
where the Python exe file is there then the complete path must be specified for the files during
execution. The output is displayed below
Fig 14.2
271
Importing C++ programs in Python
Note
To clear the screen in command window use cls command.
Now let us will see how to write the Python program for compiling C++ code.
14.6 Python Program to import C++
Python contains many modules. For a problem Python allow programmers to have the
flexibility in using different module as per their convenience. The Python program what we
have written contains a few new commands which we have not come across in basic Python
program. Since our program is an integration of two different languages, we have to import the
modules like os, sys and getopt.
14.6.1 MODULE
Modular programming is a software design technique to split your code into separate
parts. These parts are called modules. The focus for this separation should have modules with no
or just few dependencies upon other modules. In other words: Minimization of dependencies
is the goal.
But how do we create modules in Python? Modules refer to a file containing Python
statements and definitions. A file containing Python code, for e.g. factorial.py, is called a module
and its module name would be factorial. We use modules to break down large programs into
small manageable and organized files. Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
Example:
def fact(n):
f=1
if n == 0:
return 0
elif n == 1:
return 1
else:
for i in range(1, n+1):
f= f*i
print (f)
Output:
>>>fact (5)
120
www.tntextbooks.org
For example:
>>> factorial.fact(5)
120
Function call
Dot operator
Module name
Python has number of standard (built in) modules. Standard modules can be imported
the same way as we import our user-defined modules. We are now going to see the Standard
modules which are required for our program to run C++ code.
(i) Python’s sys module
This module provides access to some variables used by the interpreter and to functions
that interact strongly with the interpreter.
sys.argv
sys.argv is the list of command-line arguments passed to the Python program. argv
contains all the items that come along via the command-line input, it's basically an array
holding the command-line arguments of the program.
To use sys.argv, you will first have to import sys. The first argument, sys.argv[0], is
always the name of the program as it was invoked, and sys.argv[1] is the first argument you
pass to the program (here it is the C++ file). For example
www.tntextbooks.org
273
Importing C++ programs in Python
main(sys.argv[1]) Accepts the program file (Python program) and the input file (C++
file) as a list(array). argv[0] contains the Python program which
is need not to be passed because by default __main__ contains
source code reference and argv[1] contains the name of the C++
file which is to be processed.
where,
variable_name1:- Name of the C++ file without extension .cpp in string format
variable_name2 :- Name of the executable file without extension .exe in string format
For example the command to compile and execute C++ program is given below
Note
‘+’ in os.system() indicates that all strings are concatenated as a single string
www.tntextbooks.org
In our examples since the entire command line commands are parsed and no leftover
argument, the second argument args will be empty []. If args is displayed using print()
command it displays the output as [].
www.tntextbooks.org
>>>print(args)
[]
275
Importing C++ programs in Python
Note
You can check out the full list of Python standard modules and what they are
for. These files are in the Lib directory inside the location where Python is installed.
if __name__=='__main__':
main(sys.argv[1:])
if __name__ == '__main__':
main (sys.argv[1:])
if the command line Python program itself is going to execute first, then __main__
contains the name of that Python program and the Python special variable __name__ also
contain the Python program name. If the condition is true it calls the main which is passed
with C++ file as argument.
Note
sys.argv[1:] - get everything after the script name(file name).
Remember “string slicing” you have studied in chapter 8.
Now let us write a Python program to read a C++ coding and execute its result. The
steps for executing the C++ program to check a given number is palindrome or not is given
below
Example:- 14.7.1 - Write a C++ program to enter any number and check
whether the number is palindrome or not using while loop.
/*. To check whether the number is palindrome or not using while loop.*/
//Now select File->New in Notepad and type the C++ program
#include <iostream>
using namespace std;
int main()
{
int n, num, digit, rev = 0;
cout<< "Enter a positive number: ";
cin>>num;
n = num;
while(num)
{ digit = num % 10;
rev = (rev * 10) + digit;
num = num / 10; }
cout<< " The reverse of the number is: " << rev <<endl;
if (n == rev)
cout<< " The number is a palindrome";
else
cout<< " The number is not a palindrome";
return 0;
}
// Save this file as pali_cpp.cpp
www.tntextbooks.org
277
Importing C++ programs in Python
Python not only execute the successful C++ program, it also helps to display even errors
if any in C++ statement during compilation. For example in the following C++ program an
error is there. Let us see what happens when you compile through Python.
Example 14.8.1
// C++ program to print the message Hello
//Now select File→New in Notepad and type the C++ program
#include<iostream>
using namespace std;
int main()
{
std::cout<<"hello"
return 0;
www.tntextbooks.org
}
// Save this file as hello.cpp
279
Importing C++ programs in Python
#Now select File→New in Notepad and type the Python program as main.py
# Program that compiles and executes a .cpp file
# Python main.py -i hello
Note
In the above program Python helps to display the error in C++. The error is
displayed along with its line number. The line number starts from python script.
}
return 0;
}
281
Importing C++ programs in Python
You would have noticed the Python program used to execute the transpose of a matrix
is also the same as what you have used in palindrome program. From this what you have
understood?
The Python script (program) in this chapter is mainly used to read the C++ file along
with the type of mode used like ‘i’/’o’. It Parses (splits) each value of the command line and pass
as argument to the List called “opts”. The entire C++ code is referenced for reading by “long
option ifile” along with the mode.
The List ‘o’ in “for loop” contains the mode (‘i’) and the variable ‘a’ contains the C++ file
with its complete path (Example [<‘c:\pyprg\cpp_file’>,’ trans_cpp’ ]) The extensions like cpp/
exe are added by the Python script.
__name__ variable directs the program to start from the Python script’s “main”
definition. The “main” definition does the Parsing and adding the extensions. The “run”
definition invoke the “g++” compiler and creates the exe file. The system() command of “os”
module executes the exe file and you will get the desired output. The file extensions are added
by the Python script due to which you can even execute the C programs.
Now you are going to test the Python script to run a C++ program having functions
and function calls.
Example 14.10.1 - Write a C++ program using a user defined function to function
cube of a number
/*Write a C++ program using a user defined function to function cube of a
number.*/
//Now select File→New in Notepad and type the C++ program
#include <iostream>
using namespace std;
// Function declaration
int cube(int num);
int main()
{
int num;
int c;
cout<<"Enter any number: "<<endl;
cin>>num;
c = cube(num);
cout<<"Cube of " <<num<< " is "<<c;
return 0;
}
//Function to find cube of any number
int cube(int num)
www.tntextbooks.org
{
return (num * num * num);
}
283
Importing C++ programs in Python
Now you are going to execute a class program of C++. The class program is of multilevel
inheritance. This also gives output using Python script
Example 14.11.1 - C++ program to implement Multilevel Inheritance
285
Importing C++ programs in Python
From all these example One can understand the Python script (program) used for
integrating C++ is common. Only the name of the Python script file and the C++ (cpp)
file have changed. Remember it is not mandatory to type the C++ coding if one’s computer
contain already the C++ file. In this chapter to show all the types of C++ programs like normal,
function, inheritance program can be executed through python the coding of C++ is explicitly
mentioned. Using this Python script you can even compile and execute C program also. Since
python automates the C++ program file to execute without it’s IDE, Python can be called as a
www.tntextbooks.org
Scripting Language.
Points to remember:
• C++ is a compiler based language while Python is an interpreter based language.
• C++is compiled statically whereas Python is interpreted dynamically
• A static typed language like C++ requires the programmer to explicitly tell the
computer what “data type” each data value is going to use.
• A dynamic typed language like Python, doesn’t require the data type to be given
explicitly for the data. Python manipulate the variable based on the type of value.
• A scripting language is a programming language designed for integrating and
communicating with other programming languages
• MinGW refers to a set of runtime header files, used in compiling and linking the code
of C, C++ and FORTRAN to be run on Windows Operating System
• The dot (.) operator is used to access the functions of a imported module
• sys module provides access to some variables used by the interpreter and to functions
that interact with the interpreter
• OS module in Python provides a way of using operating system dependent functionality
• The getopt module of Python helps you to parse (split) command-line options and
arguments
Hands on Experience
1. Write a C++ program to create a class called Student with the following details
Protected member
Rno integer
Public members
void Readno(int); to accept roll number and assign to Rno
void Writeno(); To display Rno.
The class Test is derived Publically from the Student class contains the following details
Protected member
Mark1 float
Mark2 float
Public members
void Readmark(float, float); To accept mark1 and mark2
www.tntextbooks.org
score integer
Public members
void Readscore(int); To accept the score
void Writescore(); To display the score
The class Result is derived Publically from Test and Sports class contains the following
details
Private member
Total float
Public member
void display() assign the sum of mark1, mark2, score in total.
invokeWriteno(), Writemark() and Writescore(). Display the total also.
Save the C++ program in a file called hybrid. Write a python program to execute the
hybrid.cpp
2. Write a C++ program to print boundary elements of a matrix and name the file as Border.
cpp. Write a python program to execute the Border.cpp
Evaluation
Part - I
9. Which of the following can be used for processing text, numbers, images, and scientific
data?
(A) HTML (B) C (C) C++ (D) PYTHON
10. What does __name__ contains ?
(A) c++ filename (B) main() name
(C) python filename (D) os module name
Part - II
289
Importing C++ programs in Python
Part - III
Part - IV
REFERENCES
1. Learn Python The Hard Way by Zed Shaw
2. Python Programming Advanced by Adam Stuart or Powerful Python by Aaron Maxwell
3. https://docs.python.org
www.tntextbooks.org
CHAPTER 15
Unit V
DATA MANIPULATION THROUGH SQL
Learning Objectives
After the completion of this chapter, the student will be able to write Python script to
• Create a table and to add new rows in the database.
• Update and Delete record in a table.
• Query the table.
• Write the Query in a CSV file.
15.1 Introduction
A database is an organized collection of data. The term "database" can both refer to the
data themselves or to the database management system. The Database management system is
a software application for the interaction between users and the databases. Users don't have
to be human users. They can be other programs and applications as well. We will learn how
Python program can interact as a user of an SQL database.
15.2 SQLite
SQLite is a simple relational database system, which saves its data in regular data files
or even in the internal memory of the computer. It is designed to be embedded in applications,
instead of using a separate database server program such as MySQLor Oracle. SQLite is fast,
rigorously tested, and flexible, making it easier to work. Python has a native library for SQLite.
To use SQLite,
import sqlite3
Step 1
Step 2 create a connection using connect () method and pass the name of the database File
Step 3
Set the cursor object cursor = connection. cursor ()
www.tntextbooks.org
• Connecting to a database in step2 means passing the name of the database to be accessed.
If the database already exists the connection will open the same. Otherwise, Python will
open a new database file with the specified name.
291
• Cursor in step 3: is a control structure used to traverse and fetch the records of the
database.
• Cursor has a major role in working with Python. All the commands will be executed
using cursor object only.
To create a table in the database, create an object and write the SQL command in it.
Example:- sql_comm = "SQL statement"
For executing the command use the cursor method and pass the required sql command
as a parameter. Many number of commands can be stored in the sql_comm and can be executed
one after other. Any changes made in the values of the record should be saved by the commend
"Commit" before closing the "Table connection".
15.3 Creating a Database using SQLite
The following example 15.3 explains how a connection to be made to a database through
Python sqlite3
# Python code to demonstrate table creation and insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect ("Academy.db")
# cursor
cursor = connection.cursor()
In the above example a database with the name "Academy" would be created. It's
similar to the sql command "CREATE DATABASE Academy;" to SQL server."sqlite3.connect
('Academy.db')" is again used in some program, "connect" command just opens the already
created database.
cursor object. Usually, a cursor in SQL and databases is a control structure to traverse over
the records in a database. So it's used for the fetching of the results.
Note
Cursor is used for performing all SQL commands.
The cursor object is created by calling the cursor() method of connection. The cursor is
used to traverse the records from the result set. You can define a SQL command with a triple
quoted string in Python. The reason behind the triple quotes is sometime the values in the
table might contain single or double quotes.
Example 15.3.1
sql_command = """
CREATE TABLE Student (
Rollno INTEGER PRIMARY KEY ,
Sname VARCHAR(20),
Grade CHAR(1),
gender CHAR(1),
Average DECIMAL(5,2),
birth_date DATE);"""
In the above example the Emp_no field as "INTEGER PRIMARY KEY" A column
which is labeled like this will be automatically auto-incremented in SQLite3. To put it in other
words: If a column of a table is declared to be an INTEGER PRIMARY KEY, then whenever
a NULL will be used as an input for this column, the NULL will be automatically converted
into an integer which will one larger than the highest value so far used in that column. If
the table is empty, the value 1 will be used.
293
Data Manipulation through SQL
Example
import sqlite3
connection = sqlite3.connect ("Academy.db")
cursor = connection.cursor()
# delete
cursor.execute ("""DROP TABLE Student;""")
sql_command = """
CREATE TABLE Student (
Rollno INTEGER PRIMARY KEY , Sname VARCHAR(20), Grade CHAR(1),
gender CHAR(1), Average DECIMAL (5, 2), birth_date DATE);"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average,
birth_date)
VALUES (NULL, "Akshay", "B", "M","87.8", "2001-12-12");""" cursor.execute(sql_
command)
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average,
birth_date)
VALUES (NULL, "Aravind", "A", "M","92.50","2000-08-17");""" cursor.execute(sql_
command)
# never forget this, if you want the changes to be saved:
connection.commit()
connection.close()
print("STUDENT TABLE CREATED")
OUTPUT
STUDENT TABLE CREATED
Of course, in most cases, you will not literally insert data into a SQL table. You will
rather have a lot of data inside of some Python data type e.g. a dictionary or a list, which has
to be used as the input of the insert statement.
The following working example, assumes that you have an already existing database
www.tntextbooks.org
Academy.db and a table Student. We have a list with data of persons which will be used in the
INSERT statement:
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
student_data = [("BASKAR", "C", "M","75.2","1998-05-17"),
("SAJINI", "A", "F","95.6","2002-11-01"),
("VARUN", "B", "M","80.6","2001-03-14"),
("PRIYA", "A", "F","98.6","2002-01-01"),
("TARUN", "D", "M","62.3","1999-02-01") ]
for p in student_data:
format_str = """INSERT INTO Student (Rollno, Sname, Grade, gender,Average,
birth_date)
VALUES (NULL,"{name}", "{gr}", "{gender}","{avg}","{birthdate}");"""
sql_command = format_str.format(name=p[0], gr=p[1], gender=p[2],avg=p[3],
birthdate = p[4])
cursor.execute(sql_command)
connection.commit()
connection.close()
print("RECORDS ADDED TO STUDENT TABLE ")
OUTPUT
RECORDS ADDED TO STUDENT TABLE
The time has come now to finally query our “Student” table. Fetching the data from
record is as simple as inserting them. The execute method uses the SQL command to get all
the data from the table.
is used to retrieve or fetch data from a table in a database. The syntax for using this statement
is “Select * from table_name” and all the table data can be fetched in an object in the form of
list of lists.
295
Data Manipulation through SQL
If you run this program, saved as "sql_Academy_query.py", you would get the following
result, depending on the actual data:
It should be noted that the database file that will be created will be in the same folder as
that of the python file. If we wish to change the path of the file, change the path while opening
the file.
Example
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("fetchall:")
result = cursor.fetchall()
for r in result:
print(r)
OUTPUT
fetchall:
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
www.tntextbooks.org
Note
cursor.fetchall() -fetchall () method is to fetch all rows from the database table
cursor.fetchone() - The fetchone () method returns the next row of a query result set or
None in case there is no row left.
cursor.fetchmany() method that returns the next number of rows (n) of the result set
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("\nfetch one:")
res = cursor.fetchone()
print(res)
OUTPUT
fetch one:
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
Example
import sqlite3 OUTPUT
connection = sqlite3.connect("Academy.db") fetching all records one by one:
cursor = connection.cursor() (1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
cursor.execute("SELECT * FROM student") (2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
print("fetching all records one by one:") (3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
result = cursor.fetchone() (4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
while result is not None: (5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
www.tntextbooks.org
297
Data Manipulation through SQL
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("fetching first 3 records:")
result = cursor.fetchmany(3)
print(result)
OUTPUT
fetching first 3 records:
[(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12'), (2, 'Aravind', 'A', 'M', 92.5, '2000-08-17'), (3,
'BASKAR', 'C', 'M', 75.2, '1998-05-17')]
Example : Program to display the content of tuples in newline without using loops
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("fetching first 3 records:")
result = cursor.fetchmany(3)
print(*result,sep="\n")
OUTPUT
fetching first 3 records:
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
Note
symbol is used to print the list of all elements in a single line with space. To print all
www.tntextbooks.org
elements in new lines or separated by space use sep= "\n" or sep= "," respectively.
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student")
result = cursor.fetchall()
print(result)
OUTPUT
[('B',), ('A',), ('C',), ('D',)]
Without the keyword “distinct” in the above examples 7 records would have been
displayed instead of 4, since in the original table there are actually 7 records and some are with
the duplicate values.
299
Data Manipulation through SQL
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
('B',)
('A',)
('C',)
('D',)
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT gender,count(gender) FROM student Group BY gender")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
('F', 2)
('M', 5)
order. In this example name and Rollno of the students are displayed in alphabetical order of
names
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student Order BY sname")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(6, 'PRIYA')
(4, 'SAJINI')
(7, 'TARUN')
(5, 'VARUN')
The WHERE clause can be combined with AND, OR, and NOT operators. The AND
www.tntextbooks.org
and OR operators are used to filter records based on more than one condition. In this example
you are going to display the details of students who have scored other than ‘A’ or ‘B’ from the
“student table”
301
Data Manipulation through SQL
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student where grade<>'A' and Grade<>'B'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,Same,Average FROM student WHERE
(Average>=80 AND Average<=90)")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay', 87.8)
(5, 'VARUN', 80.6)
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student WHERE (Average<60
OR Average>70)")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(4, 'SAJINI')
(5, 'VARUN')
(6, 'PRIYA')
In this example we are going to display the name and grade of students who have born
in the year 2001
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student
WHERE(Birth_date>='2001-01-01' ANDBirth_date<='2001-12-01')")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(5, 'VARUN')
www.tntextbooks.org
303
Data Manipulation through SQL
These functions are used to do operations from the values of the column and a single
value is returned.
• COUNT() • AVG()
• SUM() • MAX()
• MIN()
15.7.1 COUNT() function
The SQL COUNT() function returns the number of rows in a table satisfying the criteria
specified in the WHERE clause. COUNT() returns 0 if there were no matching rows.
Example
EXAMPLE
Note
NULL values are not counted. In case if we had null in one of the records in
student table for example in Average field then the output would be 6.
15.7.2AVG():
The following SQL statement in the python program finds the average mark of all
students.
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT AVG(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
OUTPUT
[(84.65714285714286,)]
Note
NULL values are ignored.
15.7.3 SUM():
The following SQL statement in the python program finds the sum of all average in the
Average field of “Student table”.
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT SUM(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
OUTPUT
[(592.6,)]
Note
www.tntextbooks.org
305
Data Manipulation through SQL
Example
import sqlite3
connection = sqlite3.connect("Organization.db")
cursor = connection.cursor()
print("Displaying the name of the Highest Average")
cursor.execute("SELECT sname,max(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
print("Displaying the name of the Least Average")
cursor.execute("SELECT sname,min(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
OUTPUT
Displaying the name of the Highest Average
[('PRIYA', 98.6)]
Displaying the name of the Least Average
[('TARUN', 62.3)]
Example
Note
Remember throughout this chapter student table what we have created is taken as example
to explain the SQL queries .Example 15.3.2 -2 contain the student table with records.
www.tntextbooks.org
307
Data Manipulation through SQL
Example
OUTPUT
Total number of rows deleted : 1
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
(6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
www.tntextbooks.org
In this example we are going to accept data using Python input() command during
runtime and then going to write in the Table called "Person"
Example
309
Data Manipulation through SQL
OUTPUT
Enter 5 students names:
RAM
KEERTHANA
KRISHNA
HARISH
GIRISH
Enter their ages respectively:
28
12
21
18
16
Enter their ids respectively:
1
2
3
4
5
Displaying All the Records From Person Table
('RAM', 28, 1)
('KEERTHANA', 12, 2)
('KRISHNA', 21, 3)
('HARISH', 18, 4)
('GIRISH', 16, 5)
You can even add records to the already existing table like “Student” Using the above
coding with appropriate modification in the Field Name. To do so you should comment the
create table statement
Note
Execute (sql[, parameters]) :- Executes a single SQL statement. The SQL
statement may be parametrized (i. e. placeholders instead of SQL literals). The sqlite3
module supports two kinds of placeholders: question marks? (“qmark style”) and named
placeholders :name (“named style”).
www.tntextbooks.org
Python allows to query more than one table by joining them. In the following example
a new table called “Appointments” which contain the details of students Rollno, Duty, Age is
created. The tables “student” and “Appointments” are joined and displayed the result with the
column headings.
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("""DROP TABLE Appointment;""")
sql_command = """
CREATE TABLE Appointment(rollnointprimarkey,Dutyvarchar(10),age int)"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Appointment (Rollno,Duty ,age )
VALUES ("1", "Prefect", "17");"""
cursor.execute(sql_command)
sql_command = """INSERT INTO Appointment (Rollno, Duty, age)
VALUES ("2", "Secretary", "16");"""
cursor.execute(sql_command)
# never forget this, if you want the changes to be saved:
connection.commit()
cursor.execute("SELECT student.rollno,student.sname,Appointment.
Duty,Appointment.Age FROM student,Appointment where student.
rollno=Appointment.rollno")
#print (cursor.description) to display the field names of the table
co = [i[0] for i in cursor.description]
print(co)
# Field informations can be read from cursor.description.
result = cursor.fetchall()
for r in result:
print(r)
OUTPUT
['Rollno', 'Sname', 'Duty', 'age']
(1, 'Akshay', 'Prefect', 17)
(2, 'Aravind', 'Secretary', 16)
Note
www.tntextbooks.org
cursor. description contain the details of each column headings .It will be stored
as a tuple and the first one that is 0(zero) index refers to the column name. Using this
command you can display the table’s Field names.
311
Data Manipulation through SQL
You can even store the query result in a CSV file. This will be useful to display the query
output in a tabular format. In the following example (EXAMPLE 15.12 -1) Using Python
script the student table is sorted “gender” wise in descending order and then arranged the
records alphabetically. The output of this Query will be written in a CSV file called “SQL.CSV”,
again the content is read from the CSV file and displayed the result.
Example
import sqlite3
import io # to access replace()
import csv
# CREATING CSV FILE
d=open('c:/pyprg/sql.csv','w')
c=csv.writer(d)
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
# a=Connection.cursor()
cursor.execute("SELECT * FROM student ORDER BY GENDER DESC,SNAME")
# WRITING THE COLUMN HEADING
co = [i[0] for i in cursor.description]
c.writerow(co)
data=cursor.fetchall()
for item in data:
c.writerow(item)
d.close()
# Reading the CSV File
# replace() is used to eliminate the newline character at the end of each row
with open('c:/pyprg/sql.csv', "r", newline=None) as fd:
# r = csv.reader(fd)
for line in fd:
line = line.replace("\n", "")
print(line)
cursor.close()
connection.close()
OUTPUT
Rollno,Sname,Grade,gender,Average,birth_date
1, Akshay, B, M, 87.8, 2001-12-12
2, Aravind, A, M, 92.5, 2000-08-17
3, BASKAR, C, M, 75.2, 1998-05-17
7, TARUN, D, M, 62.3, 1999-02-01
www.tntextbooks.org
Example Opening the file (“sqlexcel.csv”) through MS-Excel and view the result
(Program is same similar to EXAMPLE 15.12 -1 script)
import sqlite3
import io #to access replace()
import csv
# database name to be passed as parameter
conn = sqlite3.connect("Academy.db")
print(“Content of the table before sorting and writing in CSV file”)
cursor = conn.execute("SELECT * FROM Student")
for row in cursor:
print (row)
# CREATING CSV FILE
d=open('c:\\pyprg\\sqlexcel.csv','w')
c=csv.writer(d)
cursor = conn.cursor()
cursor.execute("SELECT * FROM student ORDER BY GENDER DESC,SNAME")
#WRITING THE COLUMN HEADING
co = [i[0] for i in cursor.description]
c.writerow(co)
data=cursor.fetchall()
for item in data:
c.writerow(item)
d.close()
print(”sqlexcel.csv File is created open by visiting c:\\pyprg\\sqlexcel.csv”)
conn.close()
www.tntextbooks.org
313
Data Manipulation through SQL
OUTPUT
Content of the table before sorting and writing in CSV file
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
(6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
sqlexcel.csv File is created open by visiting c:\\pyprg\\sqlexcel.csv
OUTPUT THROUGH EXCEL
A B C D E F
1 Rollno Sname Grade gender Average birth_date
2
3 1 Akshay B M 87.8 2001-12-12
4
5 2 Aravind A M 92.5 2000-08-17
6
7 3 BASKAR C M 75.2 1998-05-17
8
9 7 TARUN D M 62.3 1999-02-01
10
11 5 VARUN B M 80.6 2001-03-14
12
13 6 PRIYA A F 98.6 2002-01-01
14
15 4 SAJINI A F 95.6 200-11-01
To show (display) the list of tables created in a database the following program (Example
refer page no 293) can be used.
Example
import sqlite3
con = sqlite3.connect('Academy.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
www.tntextbooks.org
OUTPUT
[('Student',), ('Appointment',), ('Person',)]
The above program (Example 15.3-1) display the names of all tables created in ‘Academy.
db’ database. The master table holds the key information about your database tables and it
is called sqlite_master
So far, you have been using the Structured Query Language in Python scripts. This
chapter has covered many of the basic SQL commands. Almost all sql commands can be
executed by Python SQLite module. You can even try the other commands discussed in the
SQL chapter.
Points to remember:
• A database is an organized collection of data.
• Users of database can be human users, other programs or applications
• SQLite is a simple relational database system, which saves its data in regular data files.
• Cursor is a control structure used to traverse and fetch the records of the database. All
the SQL commands will be executed using cursor object only.
• As data in a table might contain single or double quotes, SQL commands in Python
are denoted as triple quoted string.
• “Select” is the most commonly used statement in SQL
• The SELECT Statement in SQL is used to retrieve or fetch data from a table in a database
• The GROUP BY clause groups records into summary rows
• The ORDER BY Clause can be used along with the SELECT statement to sort the data
of specific fields in an ordered way
• Having clause is used to filter data based on the group functions.
• Where clause cannot be used along with ‘Group by’
• The WHERE clause can be combined with AND, OR, and NOT operators
• The ‘AND’ and ‘OR’ operators are used to filter records based on more than one
condition
• Aggregate functions are used to do operations from the values of the column and a
single value is returned.
• COUNT() function returns the number of rows in a table.
• AVG() function retrieves the average of a selected column of rows in a table.
• SUM() function retrieves the sum of a selected column of rows in a table.
• MAX() function returns the largest value of the selected column.
• MIN() function returns the smallest value of the selected column
• sqlite_master is the master table which holds the key information about your database
tables.
• The path of a file can be either represented as ‘/’ or using ‘\\’ in Python. For example
the path can be specified either as 'c:/pyprg/sql.csv', or c:\\pyprg\\sql.csv’.
www.tntextbooks.org
315
Data Manipulation through SQL
Hands on Experience
1. Create an interactive program to accept the details from user and store it in a csv file using
Python for the following table.
Database name;- DB1
Table name : Customer
2. Consider the following table GAMES. Write a python program to display the records for
question (i) to (iv) and give outputs for SQL queries (v) to (viii)
Table: GAMES
(i) To display the name of all Games with their Gcodes in descending order of their schedule
date.
(ii) To display details of those games which are having Prize Money more than 7000.
(iii) To display the name and gamename of the Players in the ascending order of Gamename.
(iv) To display sum of PrizeMoney for each of the Numberof participation groupings (as
shown in column Number 4)
(v) Display all the records based on GameName
www.tntextbooks.org
Evaluation
Part - I
317
Data Manipulation through SQL
Part - II
Part - III
Part - IV
Rate :- Integer
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40
References
www.tntextbooks.org
CHAPTER 16
Unit V DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART
Learning Objectives
320
XII Std Computer Science
Scatter plot: A scatter plot is a type of plot that shows the data as a collection of
points. The position of a point depends on its two-dimensional value, where each
value is a position on either the horizontal or vertical dimension.
Box plot: The box plot is a standardized way of displaying the distribution of data based
on the five number summary: minimum, first quartile, median, third quartile, and
maximum.
Installing Matplotlib
You can install matplotlib using pip. Pip is a management software for installing python
www.tntextbooks.org
packages.
321
Data Visualization using Pyplot
Note
Detailed installation procedures given in Annexure
After installing Matplotlib, we will begin coding by importing Matplotlib using the
command:
import matplotlib.pyplot as plt
Now you have imported Matplotlib in your workspace. You need to display the plots.
Using Matplotlib from within a Python script, you have to add plt.show() method inside the
file to display your plot.
Example
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
Output
This window is a matplotlib window, which allows you to see your graph. You
can hover the graph and see the coordinates in the bottom right.
4.0
3.5
3.0
2.5
2.0
1.5
1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0
www.tntextbooks.org
Figure 16.1
322
XII Std Computer Science
You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you
provide a single list or array to the plot () command, matplotlib assumes it is a sequence of y
values, and automatically generates the x values for you. Since python ranges start with 0, the
default x vector has the same length as y but starts with 0. Hence the x data are [0, 1, 2, 3].
plot() is a versatile command, and will take an arbitrary number of arguments.
Program
This .plot takes many parameters, but the first two here are 'x' and 'y' coordinates. This
means, you have 4 co-ordinates according to these lists: (1,1), (2,4), (3,9) and (4,16).
16
14
12
10
Figure 16.2
323
Data Visualization using Pyplot
LINE GRAPH
14 Line1
Line2
12
10
Y - Axis
4
1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00
www.tntextbooks.org
X - Axis
Figure 16.3
324
XII Std Computer Science
Configure
Subplots
Home Button Pan Axis Button Button
Figure 16.4
Home Button → The Home Button will help once you have begun navigating your chart. If
you ever want to return back to the original view, you can click on this.
Forward/Back buttons → These buttons can be used like the Forward and Back buttons in
your browser. You can click these to move back to the previous point you were at, or forward
again.
Pan Axis → This cross-looking button allows you to click it, and then click and drag your
graph around.
Zoom → The Zoom button lets you click on it, then click and drag a square that you would like
to zoom into specifically. Zooming in will require a left click and drag. You can alternatively
zoom out with a right click and drag.
Configure Subplots → This button allows you to configure various spacing options with your
figure and plot.
Save Figure → This button will allow you to save your figure in various forms.
Matplotlib allows you to create different kinds of plots ranging from histograms and
scatter plots to bar graphs and bar charts.
Line Chart
A Line Chart or Line Graph is a type of chart which displays information as a series of
www.tntextbooks.org
data points called ‘markers’ connected by straight line segments. A Line Chart is often used
to visualize a trend in data over intervals of time – a time series – thus the line is often drawn
chronologically.
325
Data Visualization using Pyplot
8955000
8950000
8945000
8940000
Figure 16.5
Bar Chart
A BarPlot (or BarChart) is one of the most common type of plot. It shows the
relationship between a numerical variable and a categorical variable.
www.tntextbooks.org
Bar chart represents categorical data with rectangular bars. Each bar has a height
corresponds to the value it represents. The bars can be plotted vertically or horizontally.
It’s useful when we want to compare a given numeric value on different categories. To
make a bar chart with Matplotlib, we can use the plt.bar() function.
326
XII Std Computer Science
Example
import matplotlib.pyplot as plt
# Our data
labels = ["TAMIL", "ENGLISH", "MATHS", "PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
# Generating the y positions. Later, we'll use them to replace them with labels.
y_positions = range (len(labels))
# Creating our bar plot
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()
Output
MARKS
80
60
RANGE
40
20
0
TAMIL ENGLISH MATHS PHYSICS CHEMISTRY CS
Figure 16.6
Xticks → Display the tick marks along the x-axis at the values represented. Then specify
the label for each tick mark.
Range → Create sequence of numbers.
327
Data Visualization using Pyplot
Bar Graph and Histogram are the two ways to display data in the form of a diagram.
Example
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
www.tntextbooks.org
plt.axes().set_aspect ("equal")
plt.show()
328
XII Std Computer Science
Output
English
Tamil
18.43
20.51
Maths 20.74
17.28
23.04 Social
Science
Figure 16.7
Hands on Practice
1. Create a plot. Set the title, the x and y labels for both axes.
4. Plot a bar chart for the number of computer science periods in a week.
www.tntextbooks.org
329
Data Visualization using Pyplot
Evaluation
Part - I
330
XII Std Computer Science
5.0
4.5
4.0
3.5
3.0
2.5
2.0
1.5
1.0
1.0 1.5 2.0 2.5 3.0
331
Data Visualization using Pyplot
a. Epic Info b.
16 1 info
16
14 14
12
12
Y axis
y axis
10
8
10
2 6
4
8
2
2 3 4 5 6 7
6
8 11
3 x axis
5 6 7 9 10
X axis
c.
d.
2.100
4.0
2.075
3.5
2.050
some numbers
2.025 3.0
2.000 2.5
1.975 2.0
1.950
1.5
1.925
1.0
1.900
0.0 0.0 0.5 1.5 2.0 2.5 3.0
2.85 2.90 2.95 3.00 3.05 3.10 3.15
Part - II
29.2%
54.2%
8.3%
8.3%
www.tntextbooks.org
333
Data Visualization using Pyplot
Part - IV
Reference
1. https://towards datascience.com / data - science - with - python - intro -to- data
-visualization-and-matplotlib-5f799b7c6d82.
2. https://heartbeat.fritz.ai/introduction-to-matplotlib-data-visualization-in-python-
d9143287ae39.
3. https://python programming.net / legends - titles - labels - matplotlib - tutorial/?
completed=/matplotlib-intro-tutorial/.
4. https://keydifferences.com/difference-between-histogram-and-bar-graph.html.
www.tntextbooks.org
334
XII Std Computer Science
GLOSSARY
Terminology Meaning
Access control security technique that regulates who or what can view
or use resources in a computing environment
Access modifiers Private , Protected and Public
append() Used to add an element in a list
Argument Argument is the actual value of this variable that gets
passed to function.
argv An array containing the values passed through
command line argument
Attribute Data items that makes up an object
Authorization Giving permission or access
Block Set of Statements
Boolean means Logical
break Exit the control
c = sqlite3.connect('test. db') create a database connection to the SQLite database
‘test.db’. You can also supply the special name :memory:
to create a database in RAM.
c.close() To release the connection of the database
c.commit() To save the changes made in the table
c.execute() Executes all SQL commands .Accepts two kinds of
placeholders: question marks ? (“qmark style”) and
named placeholders :name (“named style”).
Cartesian product Cartesian operation is helpful to merge columns from
two relations
cd cd command refers to change directory
Class Template of creating objects.
Class variable An ordinary variable declared inside a class
cls To clear the screen in command window
Comma(,) Comma is used to separate each data in a csv file
www.tntextbooks.org
335
elif else…if
Embedded Firmly attached
Enter key Enter key or newline is used to create rows in a csv file
336
337
338
339
www.tntextbooks.org
340
ANNEXURE - 1
List of Python Functions
I. Built-in Functions
Function Description
abs() returns absolute value of a number
all() returns true when all elements in iterable is true
any() Checks if any Element of an Iterable is True
ascii() Returns String Containing Printable Representation
bin() converts integer to binary string
bool() Converts a Value to Boolean
bytearray() returns array of given byte size
bytes() returns immutable bytes object
callable() Checks if the Object is Callable
chr() Returns a Character (a string) from an Integer
classmethod() returns class method for given function
compile() Returns a Python code object
complex() Creates a Complex Number
delattr() Deletes Attribute From the Object
dir() Tries to Return Attributes of Object
divmod() Returns a Tuple of Quotient and Remainder
enumerate() Returns an Enumerate Object
eval() Runs Python Code Within Program
exec() Executes Dynamically Created Program
filter() constructs iterator from elements which are true
float() returns floating point number from number, string
format() returns formatted representation of a value
getattr() returns value of named attribute of an object
globals() returns dictionary of current global symbol table
hasattr() returns whether object has named attribute
hash() returns hash value of an object
help() Invokes the built-in Help System
hex() Converts to Integer to Hexadecimal
id() Returns Identify of an Object
isinstance() Checks if a Object is an Instance of Class
issubclass() Checks if a Object is Subclass of a Class
iter() returns iterator for an object
len() Returns Length of an Object
locals() Returns dictionary of a current local symbol table
map() Applies Function and Returns a List
max() returns largest element
memoryview() returns memory view of an argument
min() returns smallest element
www.tntextbooks.org
341
343
V. Set Functions
Function Description
add() adds element to a set
clear() remove all elements from a set
copy() Returns Shallow Copy of a Set
difference() Returns Difference of Two Sets
difference_update() Updates Calling Set With Intersection of Sets
discard() Removes an Element from The Set
frozenset() returns immutable frozenset object
intersection() Returns Intersection of Two or More Sets
intersection_update() Updates Calling Set With Intersection of Sets
isdisjoint() Checks Disjoint Sets
issubset() Checks if a Set is Subset of Another Set
issuperset() Checks if a Set is Superset of Another Set
pop() Removes an Arbitrary Element
remove() Removes Element from the Set
set() returns a Python set
symmetric_difference() Returns Symmetric Difference
symmetric_difference_update() Updates Set With Symmetric Difference
union() Returns Union of Sets
update() Add Elements to The Set.
344
ANNEXURE - II
C:\wamp\bin\mysql\mysql5.7.23\bin\mysql.exe
Enter password
Welcome to the My SQL monitor. Commands end with ; or \g.
Your MYSQL connection id is 2
Server Version: 5.7.23 MYSQL Community Server <GPL>
Copyright <c> 2000, 2018, Oracle and\or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and\or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
Mysql>
www.tntextbooks.org
345
ANNEXURE 3
Installation of MinGW
STEPS TO INSTALL MinGW-w64 - for 32 and 64 bit Windows
Step 2 : Click the Download button which appears in the home page. The file should start
downloading in your standard download folder or it prompts the save as dialog box
www.tntextbooks.org
Step 3 : The file should appear as . Terminate the window browsing the
SourceForge web site. Move this file to a more permanent location, so that you can
install MinGW (and reinstall it later, if necessary).
346
Installing:
1. Double-click the . icon. The following pop-up window will appear.
2. Click Run. The following pop-up window will appear. Click next button in the following
window
www.tntextbooks.org
3. The following pop-up window will appear, which specify the Setup settings
347
Settings
Specify setup settings.
Version 8.1.0
Architecture i686
Threads posix
Exception dwarf
Build revision 0
4. Select the destination folder in the following window to install MinGW-W64. Click next
button
Installation floder
Select a destination folder where i686-8.1.0-posix-dwarf-rf_v6-rev0 will
be installed.
Destination folder
www.tntextbooks.org
348
Installing Files
Copying i686-8.1.0-posix-dwarf-rt_v6-rev0 files to your computer.
Downloading file...
File: i686-8.1.0-release-posix-dwarf-rt_v6-rev0.7z
Installing Files
Copying i686-8.1.0-posix-dwarf-rt_v6-rev0 files to your computer.
8. Locate the folder in your PC. For example here the mingw64 is present in the following
path c:\Program Files\mingw-w64.
www.tntextbooks.org
9. Open the folder and double click the batch file. The program will get executed.
349
10 A shortcut for run will be created in the desktop. Double click and open the “command
window”.
Run terminal
11 Through this command window only we have to execute the Python program because
it contains the other programming language program ie is C++. This command window
dynamically invoke the g++ compiler to compile and execute C++ program using Python
program
www.tntextbooks.org
350
ANNEXURE 4
Installation of pip
First of all you need to identify whether pip is installed in your PC.
If so, upgrade the pip in your system. To do this, you need to launch the
command prompt. Before trying to install or upgrade the pip, the command
will work only if you have appended the path of python directory in the
path variable of the windows.
You can install the latest version of pip from your command prompt using the following
command:
To check the version of pip in your system, type the following command:
www.tntextbooks.org
351
You can see the version of pip installed from the output screen.
To install matplotlib, type the following in your command prompt:
Python –m pip install –U matplotlib
This command will download matplotlib from the source library. If it is already installed the
screen will look like the following:
List Packages
www.tntextbooks.org
To view the list of installed packages on your system, use the List command:
screen will display the list of all the packages installed on your system.
www.tntextbooks.org
353
Mr. Ramakrishnan V G
Reviewers Post Graduate Teacher, Karnataka Sangha Hr Sec School,
Dr. Ranjani Parthasarathi T Nagar, Chennai
Professor, Dept of Info Sci and Tech, College of Engineering, Guindy, Mrs. Vidhya H
Anna University, Chennai Post Graduate Teacher,
DAV Boys Senior Secondary School,
Content Expert Gopalapuram, Chennai.
M. Saravanan,
Art and Design Team B.T.Asst, G.G.H.S.S, Puthupalayam,
Vazhapadi, Salem.
Layout
THY Designers and computers
Chennai
Typist
In-House
Mrs. Meena T
QC - Mathan Raj R SCERT, Chennai.
- Arun Kamaraj Palanisamy
Wrapper Design
Kathir Arumugam This book has been printed on 80 G.S.M.
Elegant Maplitho paper.
Co-ordination
Printed by offset at:
Ramesh Munisamy
www.tntextbooks.org
354
COMPUTER APPLICATIONS
Theory & Practical
Government of TamilNadu
First Edition - 2019
Content Creation
The wise
possess all
ii
www.tntextbooks.org
PREFACE
iii
www.tntextbooks.org
iv
CAREER GUIDANCE
www.tntextbooks.org
Law
LLB All University and their affiliated Lawyer, Legal Officer, Govt
B.A+LLB Colleges and Self financing Colleges Job
B.Com in India and Abroad.
BBM+LLB
BBA+LLB
Commerce Courses
B.com-Regular, All University and their affiliated Private Organization, Government,
B.com-Taxation & Tax Procedure, Colleges and Self financing Colleges Banking sectors and prospects for self
B.com-Travel &Tourism, in India and Abroad. – employment.
B.com-Bank Management,
B.com-Professional,
BBA/BBM-Regular,
BFM- Bachelors in Financial Markets,
BMS-Bachelors in Management
Studies,
BAF- Bachelors in Accounting &
Finance,
Certified Stock Broker & Investment
Analysis,
v
www.tntextbooks.org
Management Courses
Business Management All University and their affiliated Private Organization,
Bank Management Colleges and Self financing Government, Banking sectors and
Event Management Colleges in India and Abroad. prospects for self – employment.
Hospital Management
Human Resource Management
Logistics Management
vi
CONTENTS
www.tntextbooks.org
CHAPTER 02 An Introduction to Adobe Pagemaker ��������������������������������� 17
CHAPTER 03 Introduction to Database Management System ������������������ 57
CHAPTER 04 Introduction to Hypertext Pre-Processor ���������������������������� 85
CHAPTER 05 PHP Function and Array ����������������������������������������������������� 99
CHAPTER 06 PHP Conditional Statements ��������������������������������������������� 106
CHAPTER 07 Looping Structure ������������������������������������������������������������ 113
CHAPTER 08 Forms and Files ��������������������������������������������������������������� 120
CHAPTER 09 Connecting PHP and MYSQL ��������������������������������������������� 130
CHAPTER 10 Introduction to Computer Networks ��������������������������������� 138
CHAPTER 11 Network Examples and Protocols ������������������������������������� 154
CHAPTER 12 DNS (Domain Name System) �������������������������������������������� 170
CHAPTER 13 Network Cabling �������������������������������������������������������������� 185
CHAPTER 14 Open Source Concepts ����������������������������������������������������� 201
CHAPTER 15 E-Commerce �������������������������������������������������������������������� 209
CHAPTER 16 Electronic Payment Systems �������������������������������������������� 233
CHAPTER 17 E-Commerce Security Systems ����������������������������������������� 253
CHAPTER 18 Electronic Data Interchange- EDI �������������������������������������� 266
PRACTICALS ����������������������������������������������������������������������������������������� 277
E-book Assessment DIGI-Links
Lets use the QR code in the text books ! How ?
• Download the QR code scanner from the Google PlayStore/ Apple App Store into your smartphone
• Open the QR code scanner application
• Once the scanner button in the application is clicked, camera opens and then bring it closer to the QR code in the text book.
• Once the camera detects the QR code, a url appears in the screen.Click the url and goto the content page.
vii
www.tntextbooks.org
www.tntextbooks.org
01
CHAPTER
LEARNING OBJECTIVES
Students will be able to learn about the concepts, techniques, and processes used
throughout the multimedia environment
●● Gain an ability to understand multimedia tools a graphics presentation.
●● Import graphics, create objects using various tools, add effects to objects
●● To know various multimedia file formats for sound and video
●● To understand the Multimedia production method and their team activities.
1.3 Components of
Multimedia
Multimedia has five major components
like text, images, sound, video and
animation. They are explained in detail
below:
Hypertext
A hypertext is a system which consists
of nodes, the text and the links between
Figure: 1.2 Components of Multimedia the nodes, which defines the paths the
user need to follow for the text access in
1.3.1 Text non-sequential ways. The author of the
Text is the basic components of multimedia working system created this structure. The
and most common ways of communicating user is permitted to define their own paths
information to other person. Even though in more sophisticated hypertext systems.
multimedia includes images, video, audio The user is provided with the flexibility
and graphics, Text is the basic components and choice to navigate in hypertext. In a
used in multimedia. multimedia product Text is used to convey
the information and must be placed at
appropriate position in order to obtain the
well-formatted sentences and paragraphs.
The readability of the text depends on the
spacing and punctuation. The message
communication is more appropriate with
improved Fonts and styles.
Figure: 1.3 Text
on the flat X and Y axis of the screen. while Musical Instrument Digital
in three dimensional animation it occurs Identifier (MIDI)
along the three axis X, Y and Z. Animation Musical Instrument Digital Identifier
tools are very powerful and effective. The (MIDI) is a standard communication tool
two basic types of animations are Path developed for computers and electronic
animation and Frame animation. instruments. This tool is flexible and easy
for composing the projects in multimedia.
Path Animation
Tools for synthesizing the sound and
Path animation involves moving an object software for sequencing are necessary for
on a screen that has a constant background MIDI.
e.g. a cartoon character may move across
the screen regardless of any change in the Digital Audio
background or the character. Sampled sound is a Digitized sound.
A sample of sound is taken and stored
every nth fraction of a second as digital
information in bits and bytes. The quality
of this recording depends on the sampling
rate. sampling rate is defined as how often
the samples are taken and how many
numbers are used to represent the value
Figure: 1.7 Animation of each sample (bit depth, resolution and
sample size). The finer the quality of the
Frame Animation captured sound and the resolution is
In frame animations, multiple objects are achieved while played back, when more
allowed to travel simultaneously and the often the sample is taken and the more
background or the objects also changes. data is stored about that sample.
1.3.4 Sound
1.3.5 Video
Sound is a meaningful speech in any
Video is defined as the display of recorded
language and is the most serious element
event, scene etc. The powerful way
in multimedia, providing the pleasure of
to convey information in multimedia
music, special effects and so on. Decibels is
applications are embedding of video. The
the measurement of volume, the pressure
video can be categorized in two types as
level of sound.
Analog video and Digital video.
Analog Video
In Analog video, the video data’s are
stored in any non-computer media like
video tape, laserdisc, film etc. It is divided
further in two types as Composite and
Component Analogue Video. Composite
Analog Video has all the video components
Figure: 1.8 Sound
4 Chapter 1 Multimedia and Desktop Publishing
www.tntextbooks.org
like brightness, color, and synchronization image compression, and the format is
combined into one signal. Due to the comfortable for moving large files between
combining of the video components, the computers.
quality of the composite video resulted
BMP (Bitmap)
in color blending, low clarity and high
generational loss. This recording format Initially this format is in use with Windows
was used for customer analog video 3.1. It is quite large and uncompressed and
recording tape formats such as Betamax hence BMP is used for the high-resolution
and VHS. or large images.
portable and well compressed storage of A standard audio file format used by Apple
raster images. PNG acts as replacement for which is like a WAV file for the Mac.
GIF and also replaces multiple common
WMA (Windows Media Audio)
uses of TIFF. PNG works good with online
viewing applications like worldwide web. It is a popular windows media audio
so it is fully streameable with a best display format owned by Microsoft and designed
option. with Digital Right Management (DRM)
abilities for copyright protection.
Budgeting Testing
Multimedia architect Computer graphic artist Audio and video specialist Web master
computer programmer
resolution projectors are common Centers and Archives
for multimedia presentations on The primary function of library is
the road. Cell phones and personal to organize, collect, preserve, and
digital assistants with Bluetooth and disseminate information to users.
Wi-Fi communication technology Several techniques and technologies
makes multimedia communication are in use for handling the information
for business more efficiently. more effectively. Multimedia technology
4. Medical Services is adopted by the libraries in various
Medical services are grown drastically functions like multimedia kiosks, user
with the development of multimedia. orientation programs etc. Following is the
Medical Students practices surgery brief account of multimedia technology
methods via simulation prior to applications in libraries.
actual surgery. Tiny digital cameras 1. Multimedia Kiosk
are inserted in human body and it
Kiosk is a free-standing furnished
displays the inner scene of the body.
equipped multimedia computer that
In this way the medical practitioners
allow users to retrieve information
were able to see the inner part without
via a touch screen. It is commonly
dissecting it.
used in airports and other public
5. Public Places locations to provide directions and
Multimedia is available in many few mandatory information’s. In an
public places like trade shows, library, Kiosk is usually located near
libraries, railway stations, museums, the entrance of the library, used for
malls, airports, banks, hotels and displaying announcements, reading
exhibitions in the form of kiosks. lists, comments and suggestions
It provides information to the from library users and other
customers and helps them. The information’s about operations and
information presented in kiosk are programs of the library.
12 Chapter 1 Multimedia and Desktop Publishing
www.tntextbooks.org
points to remember
●● Multimedia allows the users to combine and change data from various sources like image,
text, graphics, video, audio and video to a single platform.
●● Multimedia has five major components like text, images, sound, video and animation.
●● Static text, the text or the words will remain static as a heading or in a line, or in a paragraph.
●● A hypertext is a system which consists of nodes, the text and the links between the nodes,
which defines the paths the user need to follow for the text access in non-sequential ways.
●● Images acts as an vital component in multimedia. These images are generated by the
computer in two ways, as bitmap or raster images and as vector images.
●● Animation is the process displaying still images so quickly so that they give the impression
of continuous movement. In animation the screen object is a vector image in animation.
●● Sound is a meaningful speech in any language and is the most serious element in multimedia,
providing the pleasure of music, special effects and so on.
●● Musical Instrument Digital Identifier (MIDI) is a standard communication tool developed
for computers and electronic instruments.
●● video can be categorized in two types as Analog video and Digital video.
EVALUATION
02
CHAPTER
LEARNING OBJECTIVES
After the completion of this chapter, the student
●● learns about what Desktop publishing is.
●● creates documents using PageMaker
●● creates Text Blocks
●● changes a Text block size
●● inserts text from other software like MS-Word in the PageMaker document
●● uses frames to hold text in place of using text blocks and so many
pictures and text next to each other, on top of each other, or beside each other—wherever
you want them to go. Figure 2.1 shows various page layout softwares
Tool Bar
Title Bar
Menu Bar
Ruler
Tool Box
Black
Border
Vertical scroll bar
Pasteboard
(The pasteboard PageMaker Page
stores items for
later use.)
Margins
(Margins appear as
dotted or pink lines.)
The main components of the above window are Title bar, Menu bar, Toolbar, Ruler,
Scroll bars and Text area. Let us have a look at these components.
Title bar
It is the topmost part of the window. It shows the name of the software and the name of
the document at the left, and the control buttons (Minimize, Maximize and Close) at the
right.
In Figure 2.5 we can see the name of the software (Adobe PageMaker 7.0) at the left.
It is followed by the default name of the document(Untitled-1) which can be changed
when we save the document with a user-supplied name.
We know that on clicking the Minimize button the document window is minimised
to a small icon and kept in the task bar, Maximise button is used for maximising the
current document window to fit the whole screen area, and the Close button closes the
software itself.
Menu bar
It contains the following menus File, Edit, Layout, Type, Element, Utilities, View,
Window, Help. When you click on a menu item, a pulldown menu appears. There may be
sub-menus under certain options in the pull-down menus. Refer Figure 2.6
Toolbar
If you place the mouse pointer on a button in the Toolbar, a short text will appear as its
description called ‘Tool Tip’. Refer Figure 2.7
Toolbox
The Figure 2.8 shows the PageMaker toolbox.
To move the toolbox, drag the toolbox by its title bar. Select a tool from the default
toolbox by clicking it.
If the toolbox is not available on the screen, you can perform these steps to show the
toolbox. The Keyboard shortcuts and Toolbox usages are shown in Table 2.1 & Table 2.2
20 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org
Constrained line
Used to draw vertical or horizontal lines.
tool
Scrolling is the process of moving up Document
and down or left and right through Editing means making changes to the text.
the document window. There are two When you edit a document, you revise its
scrollbars namely Vertical and Horizontal text. Editing encompasses many tasks,
scroll bars for scrolling the document such as inserting and deleting words and
vertically or horizontally. phrases, correcting errors, and moving
and copying text to different places in the
Rulers document.
There are two ruler bars. One is at the top
and the other is at the left side. 2.6.1 Selecting Text
To show the ruler Text can be selected using the mouse or
1. Click on View. The View menu will the keyboard.
appear.
Selecting Text using the mouse
2. Click on Show Rulers. Rulers appear To select text using a mouse, follow these
along the top and left sides of the steps :
document window.
1. Place the Insertion point to the left
To hide the ruler of the first character to be selected.
1. Click on View. The View menu will 2. Press the left mouse button and drag
appear. the mouse to a position where you
2. Click on Hide Rulers to hide the want to stop selecting.
rulers. 3. Release the mouse button.
4. The selected text gets highlighted.
2.5 Entering Text in the
Document
To Select Press
In PageMaker the text of the document
can be typed inside a text block. So, you A Word Double-click with I-beam
must use the Text tool to create those text A Paragraph Triple-click with I-beam
blocks. After creating a Text block, you
can type the text directly into the text Selecting Text using the Keyboard
block. As the characters are typed, the To select text using a keyboard, follow
flashing vertical bar called the insertion these steps :
point, moves to the right. When the text
1. Place the Insertion point to the left of
being typed reaches the end of the text
the first character you wish to select.
block, PageMaker will automatically wrap
the text to the next line. The Enter key 2. The Shift key is pressed down and
must not be pressed at the end of the each the movement keys are used to
line in text block. The Enter key should be highlight the required text.
pressed only at the end of a paragraph or 3. When the Shift key is released, the
when a blank line is to be inserted. text is selected.
Chapter 2 An Introduction to Adobe Pagemaker 23
www.tntextbooks.org
Figure 2.10
3. A red triangle in the bottom windowshade means there is more text in the text block
than is visible on the page. Drag the windowshade handle down to show more text.
2. Click once on this, and the cursor changes to a loaded text icon.
3. Position this where the second part of the text is to be, and click.
2. Locate the document that contains the text you want to place and select it.
●● Click once on this and the loaded text icon reappears. Now generate a new text block
and click. Repeat this process until there is no more text to place.
Similarly if you want to place the Text blocks that are connected in this way
text in a page, position the loaded text are threaded. The process of connecting
icon at the top of the page and click. Text text among Text blocks is called threading
flows into the page. If there is more text text. Text that flows through one or more
than fits in the page, a red triangle appears threaded blocks is called a story.
in the bottom windowshade handle. Once you have a loaded text icon,
Click once on this and the loaded you can use one of three text-flow options
text icon reappears. Now generate a new to place text in text blocks.
page (or pages) by selecting Layout > To cancel a loaded text icon, click the
Insert Pages in the menu bar. Place the pointer tool in the toolbox; no text is deleted.
loaded text icon at the top of the next page
and click. Repeat this process until there A threaded text block can be
is no more text to place. identified by a plus sign in its top and/or
bottom handles. Refer Figure 2.23-Fig 2.25
Automatic text flow Unthreaded text is where a text block
Before importing the text, first select stands alone, without being connected
Layout > Autoflow in the menu bar. to any other block. These blocks have
Then you should import the text. Now nothing in their top and bottom handles.
the loaded text icon looks different - it
contains a squiggly arrow( ).
Place the loaded text icon at the top
of the page and click. But now the text will
automatically flow on to the succeeding
pages, creating new ones, if necessary.
In PageMaker, text and graphics that you draw or import are called objects.
Once a file is saved under a name, versions are completely separate, and the
to save it again the name need not be work you do on one document has no
entered again. The file can be saved simply effect on the other.
by selecting the File > Save command or To save a document with a new
by clicking the Save button (or) clicking name or in a different location:
Ctrl + S in the keyboard.
1. Choose File > Save As in the menu
2.11.2 Saving a Document bar. (or) Press Shift + Ctrl + S in the
with a new name or in a keyboard.
different location Now Save Publication dialog box
You can save a document with a new will appear. Refer Figure 2.30
name or in a different location using
2. Type a new name or specify a new
Save AS command. Save AS command
location.
creates a new copy of the document. So,
two versions of the document exist. The 3. Click the Save button.
Press Ctrl + O in the Keyboard. combination is joined with a plus sign, the
A Open Publication dialog box as first key must be pressed and held down
shown in the figure 2.31 appears on and the second key is to be pressed.
the screen. Table 1.1 Keyboard Movement Keys
Move Press
One character to the Left Arrow
left
Small Caps
Leading Horizontal Baseline
Bold
Italic Scale Shift
Underline
Figure 2.34 Character Control Palette
Font:
Arial Black
Bold
Underlined
Small
Caps
Italic
Figure 2.35 Modify character attributes using the Character Control Palette
3. Release the mouse button and the 3. Then click OK button. Now the
line will be drawn and selected, with cursor changes to a crosshair.
sizing handles on either end. 4. Click and drag on the screen to draw
Resize the line by clicking and your dotted line. As you drag, the
dragging the handles, if necessary. line appears.
5. Release the mouse button and the
line will be drawn and selected, with
sizing handles on either end.
Resize the line by clicking and
dragging the handles, if necessary.
Figure 2.42 Draw a Rounded Corner Rectangle Figure 2.43 draw a Polygon
Figure 2.49 Drawing a star-3 Figure 2.51 Filling Shapes with Colors and
Patterns
Figure 2.53 Type page number Figure 2.55 Insert page settings
3. Then click on OK. The required page 6. The new pages are inserted in your
is displayed on the screen. publication.
48 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org
3. Click on OK button.
2.20.1 Inserting Page Numbers
in Mater Pages
2.20 Master Pages
To make page numbers appear on
Any text or object that you place on the every page
master page will appear on the entire
1. Click on Master Pages icon.
document pages to which the master is
applied. It shortens the amount of time 2. Then click on Text Tool. Now the
because you don’t have to create the cursor changes to I - beam.
same objects repeatedly on subsequent 3. Then Click on the left Master page
pages. where you want to put the page
number.
Chapter 2 An Introduction to Adobe Pagemaker 49
www.tntextbooks.org
Figure 2.60 Hiding maser page items Figure 2.61 Master page palette
Pop-up Menu
points to remember
●● Desktop publishing (abbreviated DTP) is the creation of page layouts for documents
using DTP software.
●● Some of the popular DTP software are Adobe PageMaker, Adobe InDesign,
QuarkXPress, etc.
●● Adobe PageMaker is a page layout software. It is used to design and produce documents
that can be printed.
●● The area outside of the dark border is referred to as the pasteboard.
●● Editing means making changes to the text. When you edit a document, you
revise its text.
●● A text block contains text you type, paste, or import. You cannot see the borders
of a text block until you select it with the pointer tool.
●● A Text block can be connected to other text block so that the text in one text
block can flow into another text block. Text blocks that are connected in this
way are threaded.
●● The process of connecting text among Text blocks is called threading text.
●● Text that flows through one or more threaded blocks is called a story.
●● Any text or object that you place on the master page will appear on the entire
document pages to which the master is applied.
●● Master Pages commonly contain repeating logos, page numbers, headers, and
footers.
●● A master item cannot be selected on a document page.
EVALUATION
Part I
Choose the correct answer
4. In PageMaker Window, the area
1. DTP stands for ______________ outside of the dark border is referred
(a) Desktop Publishing to as _________.
(b) Desktop Publication (a) page
(c) Doctor To Patient (b) pasteboard
(d) Desktop Printer (c) blackboard
2. ____________ is a DTP software. (d) dashboard
(a) Lotus 1-2-3 5. Shortcut to close a document in
(b) PageMaker PageMaker is ______________
(c) Maya (a) Ctrl + A (b) Ctrl + B
(d) Flash (c) Ctrl + C (d) Ctrl + W
3. Which menu contains the New 6. A __________ tool is used for
option? magnifying the particular portion of
(a) File menu the area.
(b) Edit menu (a) Text tool (b) Line tool
(c) Layout menu (c) Zoom tool (d) Hand tool
(d) Type menu
54 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org
Part - II
Short Answers
1. What is desktop publishing?
2. Give some examples of DTP software.
3. Write the steps to open PageMaker.
4. How do you create a New document in PageMaker?
5. What is a Pasteboard in PageMaker?
6. Write about the Menu bar of PageMaker.
7. Differentiate Ellipse tool from Ellipse frame tool.
8. What is text editing?
9. What is text block?
10. What is threading text blocks?
11. What is threading text?
12. How do you insert a page in PageMaker?
Part - III
Explain in Brief Answer
1. What is PageMaker? Explain its uses.
2. Mention three tools in PageMaker and write their keyboard shortcuts.
3. Write the use of any three tools in PageMaker along with symbols.
4. How do you rejoin split blocks?
5. How do you link frames containing text?
6. What is the use of Master Page?
7. How to you insert page numbers in Master pages?
Part - IV
Explain in detail
1. Explain the tools in PageMaker toolbox.
2. Write the steps to place the text in a frame.
3. How can you convert text in a text block to a frame?
4. Write the steps to draw a star using polygon tool?
03
CHAPTER
Introduction to Database
Management System
LEARNING OBJECTIVES
To understand database concepts, components and its functions.
●● To know about relational model of data
●● To understand Query languages for databases.
●● Enables to write SQL commands and query processing
●● To enhance the programming skills and Techniques using MySQL
Data Duplication – Same data is used given instance. This property helps in the
by multiple resources for processing, successful transaction. Isolation property
thus created multiple copies of same data is needed during concurrent transaction.
wasting the spaces. When multiple users do the transactions
High Maintenance – Access control and by accessing same object at the same time,
verifying data consistency needs high the transaction is known as concurrent
maintenance cost. transaction. To prevent the conflict in
database update, the transactions are isolated
Security – less security provided to the data. from other user and serialized. This is also
So database systems became popular to known as Degree of Consistency. Durability
overcome the above limitations of file is defined as the system’s ability to recover all
system. committed transactions during the failure
of storage or the system.
3.1.3 DBMS Concepts
Concurrency Control and
There exist few standards that are Locking – It is the DBMSs mechanism
applicable to all forms of database used for data sharing. When the same data
management Systems like Relational is shared among multiple users, proper
Database Management System (RDBMS) access control is needed and privilege of
and Object Database Management System changing the applications data item is
(ODBMS). All DBMS adheres to the controlled through Locking.
following two basic concepts.
ACID Properties – The acronym 3.2 DBMS Database Models
stands for Atomicity, Consistency, Isolation The database technology came into
and Durability. Atomicity follows the thumb existence in terms of models with relational
rule “All or Nothing”, while updating the and object-relational behavior. The major
data in database for the user performing the database models are listed below:
update operation. This update operation is
called as transaction and it either commits 3.2.1 Hierarchical Database
(successful updating) or aborts (updating Model
failure). Consistency ensures that the The famous Hierarchical database model
changes in data value to be constant at any was IMS (Information Management
Company
Marketing Personnel
= Container
= Object
Figure: 3.1 Hierarchical database model
System), IBM’s first DBMS. In this model Network schema – schema defines all
each record has information in parent/ about the structure of the database.
child relationship like a tree structure. The Sub schema – controls on views of the
collection of records was called as record database for the user
types, which are equivalent to tables in
relational model. The individual records Language – basic procedural for accessing
are equal to rows. See Figure 3.1 the database.
In the above model we have many The major advantage of this model
advantages like less redundant data, is the ability to handle more relationship
efficient search, data integrity and security. types, easy data access, data integrity
This model also has few limitations like and independence. The limitation of
complex to implement and difficulty in network model is difficulty in design and
handling many to many relationships. maintenance.
one owner. The many to many relationships Member Member group Group
member_id:int id:int
are handled in a better way. This model
id:int
firstname:string group_id:int ...
M Works N
Salesperson Department
in
1 1 N
1
Lives
At
Has Has
Accounts Orders
Address Zip
N N
State
StName
Account Orders
City
StNumber
where as the table can have. The example of of more than one attribute is called a
Employee table is shown below in Table 3.1. composite primary key.
Table 3.1 Table Structure
3.4.6 Foreign Key
ID NAME AGE SALARY
A foreign key is a “copy” of a primary key
1 Alex 26 22,000 that has been exported from one relation
2 Divya 25 20,000 into another to represent the existence of a
3 Tulsi 28 30,000 relationship between them. A foreign key
is a copy of the whole of its parent primary
key i.e if the primary key is composite,
3.4.3 Column
then so is the foreign key. Foreign key
The table consists of several rows and
values do not (usually) have to be unique.
columns. Table can be divided into smaller
Foreign keys can also be null. A composite
parts, in terms of columns. Each column
foreign key cannot have some attribute(s)
is known as attributes. In the Employee
null and others non-null.
table four attributes are available namely
Id, Name, Age and Salary. The attribute is 3.4.7 Super Key
defined in a table to hold values of same
An attribute or group of attributes, which
type. This is known as Attribute Domain.
is sufficient to distinguish every tuple in
In the Employee table, the Name field will
the relation from every other one is known
hold only characters not the numbers in
as Super Key. Each super key is called a
it.The vertical entity in a table is known as
candidate key. A candidate key is selected
Attribute or Column.
from the set of Super Key. While selecting
candidate key, redundant attributes
3.4.4 Row
should not be taken. The candidate key is
A single entry in a table is called as Row
also known as minimal super keys.
or Record or Tuple. Set of related data’s
are represented in a row or tuple. The 3.4.8 Composite Key
horizontal entity in a table is known as
A key with more than one attribute to
Record or row. See Table 3.2
identify rows uniquely in a table is called
Table 3.2 Row Structure Composite key. This is also known as
ID NAME AGE SALARY Compound Key.
1 Alex 26 22,000
3.5 ER Model
3.4.5 Primary Key Generally we use an ER model to know the
The candidate key that is chosen to concept of database design and this model
perform the identification task is called consists of a collection of entities(real
the primary key and any others are world objects)where each of these entities
Alternate keys. Every tuple must have, by will be interconnected with each other
definition, a unique value for its primary with conditions and dependencies(i.e. one
key. A primary key which is a combination entity is dependent on another).
3.5.1 ER Modeling basic concepts key(a unique id) as the roll no because for
The basic concepts of ER model consists every one roll no varies and it will not be
of same.
Name
Person
Employee
3.5.5 Relationship Type entity and the department entity, then Ram
In ER Model, relationship exists works for Comp.sc department, shyam
between two entities. Three types of works for electrical department ..etc are
relationships are available and the Entity- relationship instances of the relationship,
Relationship(ER) diagram is based on the works for.
three types listed below. 3.5.5.2 Degree of a relationship
One-to-One relationship: Consider The number of entity types involved is
two entities A and B. one-to-one known as Degree of relationship. One –
(1:1) relationship is said to exist in a Unary, Two – Binary, Three – Ternary.E.g
relational database design, if 0 or 1 An employee of an organization acts as
instance of entity A is associated with manager of few other employees. It also
0 or 1 instance of entity B, and 0 or 1 connects one entity to itself as a loop. so
instance of entity B is associated with 0 manager-of is unary. Similarly employee
or 1 instance of entity A. works-fordepartment, connects two
One-to-Many relationship: Consider entities and is binary. If customer purchase
two entities A and B. one-to-many item, it involves shop keeper also and is a
(1:N) relationship is said to exist in ternary relationship.
a relational database design, for 1
3.5.5.3 Cardinality
instance of entity A there exists 0 or 1
or many instances of entity B, but for 1 It is defined as the number of items that
instance of entity B there exists 0 or 1 must be included in a relationship.ie)
instance of entity A. number of entities in one set mapped with
the number of entities of another set via
Many-to-Many relationship:Consider
the relationship. Three classifications in
two entities A and B. many-to-many
Cardinality are one-to-one, one-to-many
(M:N) relationship is said to exist
and Many-to-Many. See Figure 3.9
in a relational database design, for 1
instance of entity A there exists 0 or 1 1
or many instances of entity B, and for Person Drives Vehicle
driver
1 instance of entity B there exists 0 or 1
Figure 3.9 Cardinality
or many instance of entity A.
In the above example we have two entities
In reality one-to-one are in less usage,
Person and Vehicle. If we consider the
where as one-to-many and many-to-many
current vehicle, the driver is operating, then
are commonly used. However in relational
we have one-to-one relationship between
databases, many-to-many are converted
Person and Vehicle. See Figure 3.10
into one-to-many relationships.
n
3.5.5.1 Relationship instance Customer Places Order
Each instance of the relationship between
Figure 3.10 CardinalityRelation 1 to n
members of these entity types is called a
relationship instance. E.g if Works-for is In the above example, Customer places
the relationship between the Employee the Order is a one-to-many relationship.
64 Chapter 3 Introduction to Database Management System
www.tntextbooks.org
Fname Lname
Fname Lname
ID Name Name ID
Fname Lname
Relationship 1 Have n
PARENT STUDENT
with student ID Name
ADMIN
Enrolls
Name Phone#
1
Adds
1
ID
Teacher n Hires
n
Address
n 0
Is assigned Class
to
Name
Fname
1 ID
n
Teaches SUBJECT Lname
ID ClassID
Name
MySQL 44.3%
SQLite 21.2%
PostgreSQL 21.2%
MongoDB 16.8%
Oracle 13.2%
Redis 11.2%
Cassandra 2.5%
A new user account is added with values to select_priv, insert_priv and update_priv
the user table using the following INSERT are few privileges set for the new user. If
query in MySQL database. The Syntax the flag is set as ‘Y’ then access is granted
for inserting record is INSERT INTO and if flag set as ‘N’ then access is denied.
table name (Parameter1,Parameter2,
Parameter3..) VALUES (Value1, Value2, Table 3.8 List of privileges available
Value3..); All the query will terminate in MySQL
with semicolon(;). Privileges Action Performed (If
mysql> INSERT INTO user (host, Granted)
name, password, select_priv, insert_ Select_priv User can select rows from
priv, update_priv) database tables.
Query OK, 1 row affected (0.20 sec) – Update_priv User can update rows of
database tables.
This statement implies that the query is
executed successfully with the time in Delete_priv User can delete rows of
seconds. database tables.
Create_priv User can create new tables
mysql>FLUSH PRIVILEGES; in database.
The above command is executed after Alter_priv User can make changes to
every new account creation. This the database structure.
command is similar to rebooting the
server so that newly created account and 3.8.2 Administrative MySQL
the access privilege are updated in the Command
server. Manual server rebooting is avoided The Database Administrator (DBA)
by this command.The inserted record is frequently uses few commands to control
retrieved using SELECT query and the the entire database. These commands
structure is shown below Table 3.7 & 3.8: are known as Administrative MySQL
mysql>SELECT * FROM user WHERE Commands. The following are few such
name = ‘guest’; important commands used frequently
while working with MySQL.
Table 3.7 Example Table
select_ insert_ update_ 1. USE Database – This command is
host name password
priv priv priv used to select the database in MySQL
localhost guest j2gd6vxd1bj3k13g4 Y Y Y for working. If there exists a database
named test, it is used as working
database using the below Syntax.
Since MySQL is more secured, it provides
function to encrypt the password. Thus Syntax:
the password ‘guest123’ is encrypted mysql > use test;
and stored as ‘j2gd6vxd1bj3k13g4’ using Database changed
PASSWORD() function. The parameters mysql>
68 Chapter 3 Introduction to Database Management System
www.tntextbooks.org
Database
5. SHOW INDEX FROM tablename –
test The query shows all the indexes for
mysql the given table.
employee Syntax:
students mysql > show indexes from sports;
parents
6. SHOW TABLE STATUS LIKE
3. SHOW Tables – Lists all the tables tablename\G – This command
available in the current database we provides with detailed report on the
are working in. See Table 3.10 performance of the table.
Syntax:
3.8.3 MySQL Installation
mysql > show tables;
Download and install
XAMPP Server Software
Table 3.10 Table List from Internet. Refer
Tables_in_test Figure 3.14 to 3.23.
school
salary
employee
library
sports
4. SHOW COLUMNS
FROM tablename – Lists all the
attributes, attribute type, Is Null
value permitted, key information,
default value and other information
for the given table. The show
columns for sports table is given
below in Table 3.11.
Figure: 3.14 XAMPP Server executable file
Syntax:
Click the Welcome Page Next Button
mysql > show columns from sports;
Chapter 3 Introduction to Database Management System 69
www.tntextbooks.org
Select the Required component along with MYSQL component and click next button
After installing Click finish button and open the XAMMP Control panel
In the Control Panel start the Apache and MySQL Services one by one
INSERT INTO TABLE_NAME (column1, Table: 3.13 SQL DDL COMMANDS List
column2, column3, ... columnN)
Commands Description
VALUES (value1, value2, value3,
...valueN); CREATE Used to create database or
tables
3.11 SQL
ALTER Modifies the existing
SQL- Structured Query Language is a structure of database or table
standard language used for accessing and
DROP Deletes a database or table.
manipulating databases. It is declared as
standard by American National Standards RENAME used to rename an existing
Institute (ANSI) and International object in the database
Organization for Standardization (ISO) in TRUNCATE Used to delete all table
1986 and 1987 respectively. records
About SQL
Data Manipulation Language (DML)
●● Though SQL is standard language,
different versions are maintained to These SQL commands deals with the
meet out the requirements. Few major manipulation of data present in the
functions performed using SQL are database. Most of SQL commands come
listed below: under DML. INSERT, UPDATE, and
●● Executes queries against a database. DELETE commands belongs to this
●● Retrieves data from database. category. See Table 3.14
●● Inserts and updates records in a
Table: 3.14 SQL DML COMMANDS List
database
●● Delete records from database. Commands Description
●● Creates new databases and new tables Adds new rows into
INSERT
in a database. database table.
modifies existing data with
UPDATE
Types of SQL Commands new data within a table.
Different SQL commands are available to Deletes the records from
DELETE
perform various functions. SQL commands the table.
are classified into five major categories
depending on their functionality. See Data Query Language (DQL)
Table 3.13 SELECT is the only SQL command used
Data Definition Language (DDL)
to fetch or retrieve the data from database
tables that come under DQL. See Table 3.15
The DDL commands are used to define
database schema (Structure). Also to create Table: 3.15 SQL DQL COMMANDS List
and modify the structure of the database
Commands Description
object in the database. CREATE, ALTER,
DROP,RENAME and TRUNCATE Retrieve data from the
SELECT
table.
commands belongs to this category.
76 Chapter 3 Introduction to Database Management System
www.tntextbooks.org
Using Operators
Table:3.20 SQL Delete Record List
While forming the SQL query we use major
firstname lastname age
operators like Arithmetic, Comparison
Krishna S 10 and Logical in the WHERE clause. The
Sugal S 14 purpose of each operator is listed below
Arun J 15 in Table 3.22.
Syntax2: select * from tablename ORDER Select Rollno, SUM(Marks) from Exams
BY columnname DESC; GROUP BY Rollno;
Example: select * from Biodata ORDER
Table:3.26 Select Record List
BY firstname DESC;
Rollno Marks
Table:3.25 Select Record List Table: 3.27 Select JOIN Record List
Rollno Subject Marks
Rollno Name Hobby
201901 Tamil 81
201901 Krishna Gardening
201904 English 75
201902 Sugal Photography
201901 English 96
201903 Charles Reading
201903 Tamil 92
Table: 3.28 Select Join Record List Table: 3.29 Select Order by class
Record List
Name Hobby Total
EmpID Name Age Salary
Krishna Gardening 177
101 Ram 35 15000
Sugal Photography 158
102 Gopal 41 30000
Charles Reading 173
103 Priya 32 13000
Venilla Singing 158 104 Hari 37 20000
Pragathi Painting 179 In the below Query, we use sub query in
an SELECT statement.
In the Query Statement, the marks are added
and listed under the column name Total for SELECT * from Employee
each of the Rollno from both the tables. where EmpID IN (SELECT EmpID from
Employee WHERE Salary < 20000);
Sub queries
First, the inner query is executed.
Here the SQL query is written within a As a result EmpID 101 and 103 are
main Query. This is called as Nested Inner/ retrieved. Now the external or outer
SubQuery.The sub query is executed first query is executed. Internally the query is
and the results of sub query are used as the SELECT * from Employee where EmpID
condition for main query. The sub query IN(101,103) and the output is drawn
must follow the below rules: below in Table 3.30.
1. Subqueries are always written within
the parentheses. Table: 3.30 Select Record List
2. Always place the Subquery on the
EmpID Name Age Salary
right side of the comparison operator.
3. ORDER BY clause is not used in 101 Ram 35 15000
sub query, since Subqueries cannot
manipulate the results internally. 103 Priya 32 13000
Backup It is a program or process of copying table contents into a file for future
reference. It’s a challenging task for DBA’s
Primary Key This key of relational table identifies each record in the table in a unique
way.
Relationship There exists a relationship between two tables when the foreign key of one
table references primary key of other table.
Cardinality It is defined as the number of different values in any given table column
Open Source Open source – refers to the design that is publicly accessible by people for
modification and sharing
SQL It (Structured query Language) is a programming language designed
mainly for managing data in RDBMS
Record Record is referred in a table, which are composed of fields.
Query In SQL, all commands are named as query. The query statement is
executed against the databases.
Join Retrieves data from two or more tables, by referencing columns in the
tables that hold identical values
EVALUATION
Part - I
Choose the correct answer 3. An entity set that does not have
enough attributes to form primary
1. Which language is used to request
key is known as
information from a Database?
a) Strong entity set
a) Relational
b) Weak entity set
b) Structural
c) Identity set
c) Query
d) Owner set
d) Compiler
2. The ---------- diagram gives a logical 4. ---------- Command is used to delete
structure of the database graphically? a database.
a) Entity-Relationship a) Delete database database_name
b) Entity b) Delete database_name
c) Architectural Representation c) drop database database_name
d) Database d) drop database_name
Part - IV
Explain in detail
1. Discuss on various database models available in DBMS.
2. List the basic concepts of ER Model with suitable example.
3. Discuss in detail on various types of attributes in DBMS.
4. Write a note on open source software tools available in MySQL Administration.
5. Explain in detail on Sub Queries with suitable examples.
04
CHAPTER
Introduction to
Hypertext Pre-Processor
LEARNING OBJECTIVES
●● To understand the importance of Web Application
●● To know the Server side Scripting Language
●● To know the features of PHP (Hyper Text Pre-processor)
●● To know the Basics of Web development process
●● To understand Webserver Installation and Configurations
and general purpose scripting language Web development activities. The current
invented by Rasmus Lerdorf in 1994. It is version of PHP, 7.3 is released by the
very simple and lightweight open source official team on 30 November 2017.
server side scripting language. It can easily
embed with HTML and other client side 4.3 Client Server
scripting languages like CSS (Cascading Architecture
Style Sheets) and Java script. It also creates
In the evolution of network architecture,
dynamic and interactive Webpages in the
various critical networks related problems
real time Web development projects.
are getting resolved by client server
It is a competitor and alternative for architecture model. The client server
other server side scripting languages like architecture introduces application sharing
Microsoft ASP (Active Server Page) and mechanism between two different hardware
JSP (Java Server page). Recent statistics of systems over the network (Internet/intranet).
server side scripting language usage depict In 1990’s Internet was emerging in the
that 78.9 % of Website are developed by computer network field. The main objective
PHP scripting language. of Internet implies that an application is
PHP 78.9% shared by more than one hardware either it
ASP.NET 12.0%
Java 3.9% could be a server or client machine.
Static files 2.2%
Ruby 2.2% The server is a high performance
Scala 1.2% hardware machine it could run more than
Python 1.2%
JavaScript 0.6% one application concurrently. The client is a
ColdFusion 0.5% separate hardware machine which is connected
Perl 0.3%
Erlang 0.1% with server in the network (Internet/intranet).
It could send the request and receive the
Figure 4.1 Server side Scripting Language
response from the server hardware. The Server
Comparison
and client are also called as service provider
and service requester respectively.
4.2 Various Server-side
Programming Languages Database Server Database Server
Global Usage Statistics
PHP scripting language can be executed
Network
via an interpreter which is installed in the
Webservers or CGI (Common Gateway
Interface). The most of the Webservers such
as Apache Tomcat, Microsoft IIS (Internet Network
versions to ensure quality and ease of Figure 4.2 Client Server Architecture Model
File server
Most of the server side scripting
languages are working on any one the client
server architecture model. Webserver
Figure 4.3 Single Tier Architecture
is software which is running in server
Two Tier Architecture hardware. It takes the responsibilities for
compilation and execution of server side
This architecture is used for the server,
scripting languages.
accessed by client as two layer interactions.
Such as Client layer in tire one and server
layer in tire Two. Refer Figure 4.4
4.4 Server side scripting
language
2-Tier Architecture
Web scripting languages are classified
into two types, client side and server side
Client Tier scripting language. PHP is completely
different from Client side scripting
language like Java script. The PHP code
entirely executes on Webserver which is
installed in the remote machine and it is
Database Tier
generating HTML code which is sent to
Database Server
the user. The user receives the HTML code
Figure 4.4 Two- Tier Architecture
and sees the Website contents via Internet market. Recent statistics of Web server
browser in their computer or laptop. PHP usage depict that more than 130% Websites
also supports OOPs (Object Oriented are running under the open source Web
Programing) concepts. It is applicable to servers such as Tomcat Apache, Nginx etc.
implement all OOPs features such as class, Refer Figure 4.7.
object and inheritance etc. The action is The following are the steps to install
shown in Figure 4.6. and configure Apache Httpd Webserver
HTTP request and PHP module in windows server
Web broswer PHP machine.
HTTP response
Executive PHP code
Step 1:
Go to Apache foundation Website
and download the Httpd Webserver
Web Server Software.
Figure 4.6 Website Request and Response from
https://httpd.apache.org/download.cgi
Web server to Browser Step2:
After downloading .MSI file from
4.5 Web Server Installation Apache foundation Website, user
& Configuration Files launches the .MSI file and clicks
Web server software that next and next button to finish the
runs on server hardware, installation on server machine. The
governs the server side software takes default port number
scripting compilation 130 or 130130. Once the user
into an intermediate finished, the Web server software is
byte-code that is then installed and configured on server
interpreted by the runtime engine. hardware machine as a service.
Step 3:
Web server software is available
To test the installation of Apache
as open source or licensed version in the
Httpd Webserver, enter the following
Apache 45.2% URL from your Web browser which
Nginx 40.0% is installed in your client machine.
Microsoft-IIS 9.3% https://localhost:130/ or https://
LiteSpeed 3.5% localhost:130130
Google Servers 0.9%
The output page that says “Its works”
Node.js 0.5%
Server
Client browser
1
request
2
Php
Apache 3
Response Apache/IIS
4
MySQL/Microsoft SQL
Server/Oracle
Boolean:
<?php
Boolean is a data type which denotes the class School {
possible two states, TRUE or FALSE function marks() {
$this->sec = “A”;
Example: }
<?php }
$x = true; // create an object
$y = false; $school_obj = new School ();
// show object properties
echo $x;
echo $school_obj ->sec;
echo $y;
?>
?>
NULL:
Array: Null is a special data type which contains
Array is a data type which has multiple a single value: NULL
values in single variable.
<?php
Example: $x = “COMPUTER APPLICATION!”;
<?php $x = null;
$cars = array(“Computer”,”Laptop”,”Mobile”); var_dump($x);
var_dump($cars); ?>
?> OUTPUT:
OUTPUT: NULL
array(3) { [0]=> string(5) “Computer “ [1]=>
string(3) “Laptop “ [2]=> string(6) “Mobile Resources
“} Resource is a specific variable, it has
a reference to an external resource.
These variables hold specific handlers to
Var_dump:
handle files and database connections in
The var_dump() function is used to respective PHP program.
dump information about a variable. This
<?php
function displays structured information
// Open a file for reading
such as type and value of the given $handle = fopen(“note.txt”, “r”);
variable. Arrays and objects are explored var_dump($handle);
recursively with values indented to show echo “<br>”;
structure.
// Connect to MySQL database server with
Object: default setting
PHP object is a data type which contains $link = mysql_connect(“localhost”, “root”,
information about data and function “”);
inside the class. var_dump($link);
?>
Arithmetic operators
The arithmetic operators in PHP perform general arithmetical operations, such as
addition, subtraction, multiplication and division etc. Refer Table 4.1.
Assignment Operators:
Assignment operators are performed with numeric values to store a value to a variable.
The default assignment operator is “=”. This operator sets the left side operant value of
expression to right side variable. Refer Table 4.2.
Comparison Operators:
Comparison operators perform an action to compare two values. These values may contain
integer or string data types (Number or Strings). Refer Table 4.3.
Logical Operators:
Logical Operators are used to combine conditional statements. Refer Table 4.5.
String Operators:
Two operators are used to perform string related operations such as Concatenation and
Concatenation assignment (Appends). Refer Table 4.6.
points to remember
URL Uniform Resource Locator, the address of a specific Web page or file on the
Internet.
HTTP HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol
used by the World Wide Web and this protocol defines how messages are
formatted and transmitted, and what actions Web servers and browsers
should take in response to various commands
Webserver A Web server is a Software that uses HTTP (Hypertext Transfer Protocol) to
serve the files that form Web pages to users
EVALUATION
Part - I a) <php>
Choose the correct answer b) < ? php ?>
1. What does PHP stand for? c) < ? ? >
a) Personal Home Page d) < ?php ? >
Part - IV
Explain in detail
1. Explain client side and server side scripting language.
2. Discuss in detail about Website development activities.
3. Explain the process of Webserver installation.
4. Discuss in detail about PHP data types.
5. Explain operators in PHP with example.
student activity
Find out the following web technology details from famous website using free web
tools : http://similarweb.com or http://pub-db.com
1. Programing details
2. Webserver details
3. Hosting Country details
05
CHAPTER
LEARNING OBJECTIVES
●● To understand the importance of Functions concept in PHP
●● To know the types of functions concept in PHP
●● To know the basics of array concepts
●● To know the types of Arrays concept in PHP
Function Calling:
A function declaration part will be executed by a call to the function. Programmer has to
create Function Calling part inside the respective program.
SYNTAX:
functionName();
Example:
<?php
function insertMsg() {
echo “Student Details Inserted Successfully!”;
}
insertMsg(); // call the function
?>
$Array_Variable=array(“value1”,”value2”,”value2”);
);
echo $$student[0][0].”: Tamil Mark: “.$student [0][1].”. English mark: “.$student [0]
[2].”<br>”;
echo $$student[1][0].”: Tamil Mark: “.$student [1][1].”. English mark: “.$student [1]
[2].”<br>”;
echo $$student[2][0].”: Tamil Mark: “.$student [2][1].”. English mark: “.$student [2]
[2].”<br>”;
?>
points to remember
Functions A function is that they are reusable; if you have a task that needs to be
performed a number of times, a function is an ideal solution.
User defined Besides the built-in PHP functions, we can create our own functions. A
Function function is a block of statements that can be used repeatedly in a program.
System Define A function is already created by system it is a reusable piece or block of
Functions code that performs a specific action. Functions can either return values
when called or can simply perform an operation without returning any
value.
Parameterized PHP Parameterized functions are the functions with parameters or
Function arguments.
Array An array is a special variable, which can hold more than one value at a
time. It’s a collection of heterogeneous data
Associative Array Associative arrays are arrays that use named keys that you assign to them.
Indexed Arrays The index can be assigned automatically in a collection of data set
Multi-Dimensional A multidimensional array is an array containing one or more arrays.
Array
EVALUATION
Part - I
Choose the correct answer
1. Which one of the following is the right way of defining a function in PHP?
a) function { function body }
b) data type functionName(parameters) { function body }
c)functionName(parameters) { function body }
d) function fumctionName(parameters) { function body }
2. A function in PHP which starts with __ (double underscore) is know as..
a) Magic Function b) Inbuilt Function
c) Default Function d) User Defined Function
3. PHP’s numerically indexed array begin with position ___________
a) 1 b) 2 c) 0 d) -1
4. Which of the following are correct ways of creating an array?
i) state[0] = “Tamilnadu”;
ii) $state[] = array(“Tamilnadu”);
iii) $state[0] = “Tamilnadu”;
iv) $state = array(“Tamilnadu”);
a) iii) and iv) b) ii) and iii) c) Only i) d) ii), iii) and iv)
5. What will be the output of the following PHP code?
<?php
$a=array(“A”,”Cat”,”Dog”,”A”,”Dog”);
$b=array(“A”,”A”,”Cat”,”A”,”Tiger”);
$c=array_combine($a,$b);
print_r(array_count_values($c));
?>
a) Array ( [A] => 5 [Cat] => 2 [Dog] => 2 [Tiger] => 1 )
b) Array ( [A] => 2 [Cat] => 2 [Dog] => 1 [Tiger] => 1 )
c) Array ( [A] => 6 [Cat] => 1 [Dog] => 2 [Tiger] => 1 )
d) Array ( [A] => 2 [Cat] => 1 [Dog] => 4 [Tiger] => 1 )
6. For finding nonempty elements in array we use
student activity
●● Create store the student details arrays and display the values.
●● List out real world Built-in string function usages in PHP
06
CHAPTER
LEARNING OBJECTIVES
●● To understand the importance of Conditional Statements
●● To know different type of Conditional Statements in PHP
●● To know the Basic fundamental logic creation using Conditional Statements
If statement in PHP:
If statement executes a statement or a group of statements if a specific condition is satisfied
as per the user expectation.
Syntax:
if (condition)
{
Execute statement(s) if condition is true;
}
106
www.tntextbooks.org
Example:
Conditional statements Very
<?php
often when we write code,
$Pass_Mark=35; you want to perform different actions
$Student_Mark=70; for different decisions in different
business logic.
if ($Student_Mark>= $Pass_Mark){
echo “The Student is Eligible for the Promotion”;
}?>
Syntax:
if (condition)
{
Execute statement(s) if condition is true;
}
else
{
Execute statement(s) if condition is false;
}
Example:
<?php
$Pass_Mark=35;
$Student_Mark=70;
if ($Student_Mark>= $Pass_Mark){
echo “The Student is eligible for the promotion”;
}
else {
echo “The Student is not eligible for the promotion”;
} ?>
Syntax:
if (1stcondition)
{
Execute statement(s) if condition is true;
}
elseif(2ndcondition)
{
Execute statement(s) if 2ndcondition is true;
}
else
{
Execute statement(s) if both conditionsarefalse;
}
Switch Case:
The switch statement is used to perform different actions based on different conditions.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example:
<?php
$favcolor = “red”;
switch ($favcolor) {
case “red”:
echo “Your favorite color is red!”;
break;
case “blue”:
echo “Your favorite color is blue!”;
break;
case “green”:
echo “Your favorite color is green!”;
break;
default:
echo “Your favorite color is neither red, blue, nor green!”;
}
?>
Chapter 6 PHP Conditional Statements 109
www.tntextbooks.org
points to remember
EVALUATION
Part - I
Choose the correct answer
1. What will be the output of the 2. What will be the output of the
following PHP code? following PHP code ?
<?php <?php
$x; $x = 0;
if ($x) if ($x++)
print “hi” ; print “hi”;
else else
print “how are u”; print “how are u”;
?> ?>
a) how are u a) hi
b) hi b) no output
c) error c) error
d) no output d) how are u
3. What will be the output of the 6. What will be the output of the
following PHP code ? following PHP code ?
<?php <?php
$x; $a = “”;
if ($x == 0)
print “hi” ; if ($a)
else print “all”;
print “how are u”;
if
print “hello”
?> else
student activity
07
CHAPTER
Looping Structure
LEARNING OBJECTIVES
●● To understand the importance of Looping Structure
●● To know different types of Looping Structure in PHP
●● To know the Basic fundamental logic creation using Looping Structure
Looping Structure:
Looping Structures are useful for writing iteration logics. It is the most important feature of
many programming languages, including PHP. They are implemented using the following
categories. Refer Figure 7.1 for Loop structure and flow chart
●● for Loop ●● While Loop
●● foreach Loop ●● Do While Loop
For Loop:
For loop is an important functional looping system which is used for iteration logics when
the programmer know in advance how many times the loop should run.
Syntax:
Parameters:
●● init counter: Initialize the loop initial counter value
●● Test counter: Evaluated for every iteration of the loop. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
●● Increment counter: Increases the loop counter value.
113
www.tntextbooks.org
Initial-action i=0
Loop-
continuation- (i < 100)
condition?
True False
True
Statement(s) System, out. print1n
(loop body) (”Welcoe to atnyla”);
False
Example:
<?php
for ($i = 0; $i<= 10; $i++) {
echo “The number is: $i<br>”;
}
?>
Foreach Loop:
foreach loop is exclusively available in PHP. It works only with arrays. The loop iteration
deepens on each KEY Value pair in the Array. For each, loop iteration the value of the
current array element is assigned to $value variable and the array pointer is shifted by one,
until it reaches the end of the array element. Refer Figure 7.2.
Syntax:
Example:
<?php PHP Loop Often when you
$Student_name = array(“Magilan”, “Iniyan”, write code, you want the
“Nilani”, “Sibi”, “Shini”); same block of code to run over and
over again in a row. Instead of adding
foreach ($Student_name as $value) { several almost equal code-lines in a
echo “$value <br>”; script, we can use loops to perform a
} task.
?>
While Loop:
While loop is an important feature which is used for simple iteration logics. It is checking
the condition whether true or false. It executes the loop if specified condition is true.
Refer Figure 7.3
Initialization; 1
while(condition) 2
Syntax:
Example:
<?php
$Student_count = 10;
$student_number=1;
while($student_number<= $Student_count) {
echo “The student number is: $student_number<br>”;
$student_number++;
}
?>
Chapter 7 Looping Structure 115
www.tntextbooks.org
Do While Loop:
Do whileloop always run the statement inside of the loop block at the first time execution.
Then it is checking the condition whether true or false. It executes the loop, if the specified
condition is true. Refer Figure 7.4.
This
Start loop
happens
at least “Do-While”
once loops run the
looping code
do
first ...
something
...and then
check for the
condition
Yes is No
condition Stop loop
true?
Syntax:
do {
code to be executed;
} while (condition is true);
Example:
<?php
$Student_count = 10;
$student_number=1;
do
{
echo “The student number is: $student_number<br>”;
$student_number++;
}
while($student_number<= $Student_count)
?>
points to remember
●● PHP while loops execute a block of code while the specified condition is true.
●● The for loop is used when you know in advance how many times the script
should run.
●● The foreach loop works only on arrays, and is used to loop through each key/
value pair in an array.
●● do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
EVALUATION
student activity
●● Create simple array element and display the values using foreach
●● Explain real world usages in using Looping Structure
08
CHAPTER
LEARNING OBJECTIVES
●● To understand the importance of HTML Form in Web Application
●● To know the File handling technique in PHP
●● To know the Basics of Web based file management system
Name
Supreme
Pizza Topping Vegetarian
Hawaiian
Send my order
120
www.tntextbooks.org
selects more than one value from the HTML form. Radio box is similar to checkbox but one
value can be chosen at a time. File select is the best feature to select one file from the local
machine to server machine at a time. Form tag is used to mention a method (POST or GET)
and control the entire form controls in the HTML document. Refer Figure 8.1 and 8.2
Example:
Test.html:
<html>
<body>
</body>
</html>
Welcome.php:
<html>
<body>
Welcome <?php echo $_POST[“name”]; ?><br>
Your email address is: <?php echo $_POST[“email”]; ?>
</body>
</html>
Output
Name: sethuraman
E-mail: [email protected]
Submit
Output
Welcome sethuraman
Your email address is: [email protected]
●● HTML File contains two Text Box validation available in PHP. They are as
(Name and Email), One Button and follows,
one form tag. The remote server PHP Client-Side Validation: The input
file (welcome.php) is mentioned in data validations are performed on the
form tag under the Action Attribute. client machine’s web browsers using client
●● In “Welcome.Php” file, PHP variables side scripts like Java script or adding
such as $_POST and $_GET collects “required” attribute in HTML input tags.
the data and prepares the response Server Side Validation: After
accordingly. the submission of data, validations are
●● Eventually the user will receive the performed on the server side using the
output response in the client machine’s programming like PHP, ASP or JSP etc.
browser screen. available in the server machine.
A HTML form will take input from
8.1.2 Basic PHP Form Validation
the site visitor and then will post
Validation is a process of
it to a back-end application such
checking the input data
as CGI, ASP Script or PHP script etc. The
submitted by the user
back-end application will perform required
from client machine.
processing on the passed data based on
There are two types of
defined business logic inside the application.
<form action=”welcome.php”>
Please fill in this field.
Username: <input type=”text”
name=”name” required>
Figure 8.3 Client Validation
<input type=”submit”>
</form>
8.2 Files
File handling is an important activity of all web application development process. Files are
processed for different tasks using the following events:
●● PHP Open a File,
●● PHP Read a File,
●● PHP Close a File,
●● PHP Write a File,
●● PHP Appending a File and
●● PHP uploading a File.
Syntax:
$file_Object= fopen(“FileName”, “Read/WriteMode”) or die(“Error Message!”);
Example:
<?php
$myfile = fopen(“Student.txt”, “r”) or die(“Unable to open file!”);
?>
Syntax:
fread($file_Object,filesize(“FileName”));
Chapter 8 Forms and Files 123
www.tntextbooks.org
Example: Syntax:
<?php file_put_contents(file,data,mode,context)
fread($myfile,filesize(“Student.txt”));
Table 8.1 Appending a File
?>
Parameters
PHP Close a File: Parameter Description
The fclose() function is used to close an File Required. Specifies the file to
opened file. The file object comes from write to. If the file does not exist,
fopen function. this function will create one
button next to the input control. The form above sends data to a file called “Student_
photo_upload.php”. Refer Figure 8.4.
In Server machine “php.ini” file, search for the file_uploads directive, and set it to On:
“file_uploads = On”
After submitting the upload button the request reaches to Student_photo_upload.php file.
In the file $_FILES variable collects all uploaded file information such as name of the file,
size of the file and extension of the file etc. All the details are checked thoroughly and the
errors are saved in an array variable. The file finally moves under the image directory if
the array error variable is empty.
Example:
Fileupload.html:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Student_photo_upload.php:
<?php
if(isset($_FILES[‘image’])){
$errors= array();
$file_name = $_FILES[‘image’][‘name’];
$file_size =$_FILES[‘image’][‘size’];
$file_tmp =$_FILES[‘image’][‘tmp_name’];
$file_type=$_FILES[‘image’][‘type’];
$file_ext=strtolower(end(explode(‘.’,$_FILES[‘image’][‘name’])));
$expensions= array(“jpeg”,”jpg”,”png”);
if(in_array($file_ext,$expensions)=== false){
$errors[]=”extension not allowed, please choose a JPEG or PNG file.”;
}
if($file_size> 2097152){
$errors[]=’File size must be excately 2 MB’;
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,”images/”.$file_name);
echo “Success”;
}else{ AJAX (Asynchronous
print_r($errors); JavaScript And XML).
AJAXis not a programming language.
} AJAX just uses a combination of: A
} browser built-in XMLHttpRequest
?> object (to request data from a web
server)JavaScript and HTML DOM
(to display or use the data)
points to remember
HTML Hypertext Markup Language is the standard markup language for creating
web pages and web applications.
FORM Validation Validation of HTML form data is important to protect your form from
hackers and spammers!
Files handling File handling is an important part of any web application. You often need
to open and process a file for different tasks.
File upload A PHP script can be used with a HTML form to allow users to upload files
to the server.
EVALUATION
Part - I a) GET
Choose the correct answer b) POST
1. When you use the $_GET variable to c) REQUEST
collect data, the data is visible to.. d) NEXT
a) none
3. Which directive determines whether
b) only you PHP scripts on the server can accept
c) everyone file uploads?
d) selected few a) file_uploads
2. Which one of the following should b) file_upload
not be used while sending passwords c) file_input
or other sensitive information? d) file_intake
Part - IV
Explain in detail
(5-Marks)1.
1. Explain Form Handling methods.
2. Discuss in detail about HTML form controls.
3. Explain the process File handling.
4. Explain concepts of HTTP Uploading process.
5. Explain in detail of File handling functions .
student activity
●● Create simple student Login Form to validate username and password using java
script (client side validation)
●● Create simple student registration form to inert studnets details like Student
Name, username and password etc. using java script (client side validation)
09
CHAPTER
LEARNING OBJECTIVES
●● To understand the importance of Database Connectivity
●● To know the PHP MySQL functions
●● To know the features of MySQL Connection Process
●● To know the Basics of Web Databases
130
www.tntextbooks.org
The MySQLi extension contains the following important functions which are related to
MySQL database connectivity and management.
●● Mysqli_connect() Function
●● Mysqli_close() Function
●● mysqli_select_db() Function
●● mysqli_affected_rows() Function
●● mysqli_connect_error() Function
●● mysqli_fetch_assoc() Function
Syntax:
This function requires four parameters to connect to database server. Database Server
name, Database username, password and Database Name.
// Create connection
$conn = mysqli_connect($servername, $username, $password,$DB_name);
// Check connection
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
?>
In the above code snippet, three variables are used to connect to the Database server. They
are
●● $servername -> Database Server Server IP address
●● $username -> Database Server User Name
●● $password -> Database Server Password
●● $DB_Name -> Database Name
The mysqli_connect function uses these variables and connect Database server from PHP
scripting. If connection gets fail, output will be printed with MySQL error code. Otherwise
connection is success.
Syntax:
Example:
$con=mysqli_connect(“localhost”,”my_user”,”my_password”,”Student_DB “);
$sql=”SELECT student_name,student_age FROM student”;mysqli_query($con,$sql);
Syntax:
mysqli_close(“Connection Object”);
Example:
<?php
$con=mysqli_connect(“localhost”,”$user”,”$password”,”SCHOOL_DB”);
// ....some PHP code...
mysqli_close($con);
?>
According to recent Survey, approximately 544 million websites are running PHP
stack as of January 2018. Of course, this count is likely even higher today given the
widespread use of PHP in web designing and development.
PHP has also attracted the development of many software frameworks that provide
building blocks and a design structure to promote rapid application development
(RAD). Some of these include PRADO, CakePHP, Symfony, CodeIgniter, Laravel, Yii
Framework, Phalcon and Zend Framework, offering features similar to other web frameworks.
points to remember
EVALUATION
Part - I
Choose the correct answer
1. Which one of the following statements instantiates the mysqli class?
a) mysqli = new mysqli()
b) $mysqli = new mysqli()
c) $mysqli->new.mysqli()
d) mysqli->new.mysqli()
2. which one is correct way, we can retrieve the data in the result set of MySQL using
PHP?
a) mysql_fetch_row.
b) mysql_fetch_array
c) mysql_fetch_object
d) All the above
3. How Can we Create a Database Using PHP and MySQL?
a) mysqli_create_db(“Database Name”)
b) mysqli_create_db(“Data”)
c) create_db(“Database Name”)
d) create_db(“Data”)
4. Which is the correct function to execute the SQL queries in PHP ?
a) mysqli_query(“Connection Object”,”SQL Query”)
b) query(“Connection Object”,”SQL Query”)
c) mysql_query(“Connection Object”,”SQL Query”)
d) mysql_query(“SQL Query”)
5. Which is the correct function Closing Connection in PHP ?
a) mysqli_close(“Connection Object”);
b) close(“Connection Object”);
c) mysql_close(“Connection Object”);
d) mysqli_close(“Database Object”);
6. Which is the correct function to establish Connection in PHP ?
a) mysqli_connect(“Server Name “,”User Name”,”Password”,”DB Name”);
b) connect(“Server Name “,”User Name”,”Password”,”DB Name”);
c) mysql_connect(“Server Name “,”User Name”,”Password”,”DB Name”);
d) mysqli_connect (“Database Object”);
Part - II
Short Answers
1. What are the MySQLi function available PHP?
2. What is MySQLi function?
3. What are the types MySQLi function available PHP?
4. Difference between Connection and Close function?
5. Give few examples of MySQLi Queries.
6. What is Connection string?
7. What is web Database?
8. What is mysqli_fetch_assoc() Function?
9. Define mysqli_connect_error() Function.
10. Define mysqli_affected_rows() Function.
Part - III
Explain in Brief Answer
1. Write the Syntax for MySQLi Queries.
2. Write is the purpose of MySQLi function available.
3. Differentiate mysqli_affected_rows() Function and mysqli_fetch_assoc() Function.
4. Write MySQL Connection Syntax with example.
5. Write a note PHP MySQL database connection.
136 Chapter 9 Connecting PHP and MYSQL
www.tntextbooks.org
Part - IV
Explain in detail
1. Discuss in detail about MySQL functions with example .
2. Explain the Database error handling and management process in PHP?
3. Explain in details types of MySQL connection method in PHP.
4. Explain MySQLi Queries with examples.
student activity
●● Create simple student Login Form to validate username and password using
PHP and MySQL (Server side validation)
●● Create simple student registration form to inert studnets details like Student Name,
username and password etc. using PHP and MySQL (Server side validation).
10
CHAPTER
LEARNING OBJECTIVES
●● To know about history of computer networking & the Internet
●● Discuss about the explosion on the Internet
●● Demerits of Internet
●● To learn about the growth of computer networking
●● Uses of computer networks at home, business, mobile, social media
nodes are identified by its IP addresses i.e.,(network address) and can include hosts such as mobile
phones , tabs , personal computers, huge servers and other networking device. Connecting more
than one device is called as network. In many cases, application at particular communications were
layered others were simply in general communications protocols. The well-known networking for all
is Internet.
4 1965 Telephone switch At first widely used Telephone switch was introduced
by Western Electric which implemented true computer
control.
5 1966 WAN (Wide Area An experimental paper on WAN (Wide Area Network) has
Network ) been published by Thomas Marill and Lawrence G.Roberts
published in the area of time sharing.
6 1969- ARPANET First In 1969, four nodes of ARPANET were connected
1970 (Hierarchical routing between four universities namely the university of
after 1970’s Internet California at Los Angeles, at Santa Barbara, the Stanford
today) Research Institute and the university of Utah using the 50
Kbit/s circuits.
Packet –switched networks was the theoretical work to
model was performed by Leonard Kleinrock , ARPANET
was which underpinned the development of it and his
theoretical work on hierarchical routing in late 1970 s
with his student Farouk Kamoun remains critical to the
operation of the Internet today.
7 1972 X.25 Using X.25 as commercial services were deployed then was
TCP/IP using an infrastructure for expanding TCP/IP networks.
8 1973 Hosts In1973, a French network named CYCLADES was the first
for making hosts which is responsible for reliable delivery
of data, later it became centralized service of network in
itself.
9 1973- Ethernet A memo at Xerox PARC was written by Robert Metcalfe
1979 describing Ethernet in 1973, in an Aloha based networking
system which was developed in 1960s by Norman Abramson
and colleagues at the University of Hawaii. At July 1976 the
paper published “Ethernet: Distributed Packet Switching for
Local Computer Networks” by Robert Metcalfe and David
Boggs, then collaborated on many patents received in 1977
and 1978. Robert Metcalfe pursued making on open standard
at 1979.
10 1976 ARCNET ARCNET was created by John Murphy of Data point
corporation in which token-passing network was used first
to share the storage device in 1976.
11 1995 NEW FIBRE OPTIC The speed capacity of transmission for Ethernet was
CABLES slightly elevated from 10 Mbit/s to 100Mbit/sat 1995.After
19913, Ethernet supported transmission speed capacity
towards gigabit. Frequently, highest speeds up to 100 Gbit/s
were appended (still 2016). Ethernet has ability to grow
easily (such as quick compatible to support new fiber optic
cable speed)
1945 1995
avoid standing in the queue at office to pay to serve millions of user and a multiple
bills with very low transaction fees. purpose in all parts of this universe.
Merchandising via Internet makes In few years, the Internet built
merchant an easier to get a specific type itself as a highly powerful platform that
of products, company, brand can be done changed their way we do business and the
easier via Internet. way we communicate. Internet promotes
Powerful search engine can take us as the universal source of information of
to imaginary concept to our hand with billions of people, at work, at home, at
all as a text, audio, video, with briefly and school. Internet gave high communication
by without moving to library, or taking medium, has given an international,
advice from expert. Current affairs can “Globalised” at all dimension of the world.
be updated immediately without any Internet is growing all the time. By
delay. For example on olden days Internet two things, have marked its evolution now a
Explorer, Yahoo, bing were powerful days the mobile technology and social web.
search engine. Later, Google stepped These two innovations have been changed
in with user friendly gmail, youtube, the people life style to use Internet. We may
googledrive, google maps, etc. and are find many communities in social web. Face
useful applications. Students, researchers book was created in 2004 but gowned into
can get their relevant study and research worldwide network all over more than 2,230
materials easily via Internet. million active users. Mobile technology
on hand made possible to great reach of
Disadvantages of Internet
Internet and increase the Internet user all
●● Simply wasting the precious time
over the world.
on Internet by surfing, searching
unwanted things. The Internet allows all to be
democratic in mass media. Anyone can
●● Lot of unnecessary information is also
have a webpage in Internet with very
there, why because any one can post
low investment. Similarly any business
anything on their webpage, blogs.
can reach a very large market directly,
●● Hackers and viruses can easily theft our economically and fast, no matter of
more valuable information available location or size of their business. Almost
in the Internet. There a lot of security anyone that who can read and write can
issues are there in E-banking. have a access and a presence in World Wide
Web with very low investment. People
10.2.1 The Internet Explosion
everywhere can express and publish their
Internet is simply defined as the World ideas and opinions via blogging.
Wide Web connection of individual
networks which operated by academic, 10.2.2 Growth of Computer
industry, government, and private parties. Networking
The Internet served to interconnect with On account of networks operate all us
laboratories engaged at government the scenes in business and home, we
research, and from 1994 it is expanded usually wont thing wrong about it, still
142 Chapter 10 Introduction to Computer Networks
www.tntextbooks.org
10.3 Uses of the Computer many computers can access one printer if
Networks it is in networks.
The computer networks plays major role Software (or) Data sharing
on providing information to large , small Using computer network, similarly
organization as well as individual common application or other software will be
man. Nowadays almost all the companies, stored at central computer or server.
bank and stores are implemented the We can share one software from one
computerized transactions. Transaction to another. It provides high reliability
are going in varies locations, It may be in source of the data. For example, all files
same campus, building, city, or at different can not be taken backup or duplicate on
places (or) cities. For all these purpose the more than one computer. So if one is not
computer network use us. Let us see about unavailable due to hardware failure or any
in this passage. other reason, the copies can be used.
The common uses of computer
network are Money saving
●● Communication Using the computer networking, it’s
important financial aspect for organization
●● Resource sharing
because it saves money. It reduces the
●● Data (or) software sharing paper work, man power and save the time.
●● Money saving
10.3.1 Networks in Business
Communication In twenty first centuries communications
Using computer networks, we can interact is necessary for successful business
with the different people with each other operations and technology for the
at all over the world. It provides a powerful business interaction. Here computer
communication among widely separated networks were faster, the Internet became
employees, team, section. They can easily full strength and wireless communications
communicate at very low cost via mobile, has been transformed the way of business
social media, telephone, e-mail, chatting, performed. By the usage of latest
video telephone, video conferencing, technologies, such as cloud computing,
SMS, MMS, groupware etc… are being used to allow globally without
scarifying security or limiting user access.
Resource sharing Here on via Internet conversations happen
Resource sharing means one device faster, Quick Decision making saves a lot
accessed by many systems. It allows of time, we all know that “time is money”
all kind of programs, equipment’s and in business. On the way of e-banking
available data to anyone via network to we already have seen that we can pay or
irrespective of the physical location of the receive money from or to the customer
resource of them. Simply resource sharing may be easily done via gateways or by
is sharing such as printers, scanner, PDA, online payments were much easier on
fax machine, and modems. For example, this method. Here any type of business
144 Chapter 10 Introduction to Computer Networks
www.tntextbooks.org
INTERNET
DSL
Cable
Cellular
Internet
Internet service
provider
Satellite
Dial-up
Small office
telephone
Figure 10.6 Mobile Networks
used to communicate with one another with or home, but via this mobile network he can
fixed transceivers and moving via more than stay in touch by his mobile. By searching
one cell during transmission. For example some important points, checking mail can
mobiles, tablets, pagers, laptops, engaged be done, watching the progress can be
with mobile broadband just like modems easier on this way. Computer knowledge
etc. Refer Figure 10.6 not necessary to easily access the Internet
via mobile network, here.
Features of Mobile Networks
10.3.4 Social Application
●● Less consumption of power is used
by mobile devices comparing with a Very fast and easiest way to cover all the
single transmitter or satellite often cell people, who they are connected in social
towers were nearer. network media. For example WhatsApp,
Face book, twitter, blogs, pintrest,
●● Huge capacity than a large transmitter,
LinkedIn, classmates and so on. Through
at single frequency can be used for
the above social media we share our
different or many links as long as they
taughts in different formats and different
are in different in cells.
size of files. The corporate also uses
●● Covering large area than a single intranets. Refer Figure 10.7 given below.
transmitter, we can add more towers
indefinitely and cannot be limited by
any horizon limits.
all the service provider giving Internet requires user to register names and
cannot make a reach to all (computer). accounts for avoid duplicate and
After the reach of mobile it makes all to secrecy .so many public networks offer
access the Internet via mobile or cellular free registration, but some charge fees
phone reaches the network easier to access. for their premium services. Private
Where ever we go, we can access. For networks (such as BANK ACCOUNT
example one business man wants to travel HOLDERS groups) restrict registration
his office by transport for an hour, on that to people who meet certain eligibility
time he cannot have connectivity to office criteria.
points to remember
●● A set of computers connected together for the purpose of sharing resources is called
as computer network. Internet is the most common resource shared on today.
●● Computer networking is a technique of digital telecommunications network one that
permits nodes to share its resources from one to another. This computer networking
exchanges the data as a main element. These link were transferred over cable media like
optic cables or wire or wireless media such as Bluetooth and WIFI
●● U.S Military Radar system used SAGE (Semi – Automatic Ground Environment)
at late 1950
148 Chapter 10 Introduction to Computer Networks
www.tntextbooks.org
EVALUATION
9. ---------- able to predict, manage, 15. Which one were harmful to computer
and protect the computer network at a) Bloggers
Internet b) Browser
a) Artificial intelligence c) Hackers
b) Broadband provider d) twitter
c) Cloud computing
d) Transceivers 16. Which innovation made the people
to use Internet?
10. -------------use less power a) Social web
comparing with single transmitter
or satellite often cell towers nearer b) Mobile technology
a) Mobile devices c) Mobile App
b) Transistors d) Both a & b.
c) WIFI
Part - II
d) Communication
Short Answers
11. People now a days getting relaxed 1. Define Computer Network.
via 2. Define Internet.
a) Business
3. What are the common uses of
b) Corporate company computer network?
c) News papers
4. List out some features of mobile
d) Social media network.
12. Which one of the following is not
5. Difference between wired and
the social media
wireless networks.
a) Gmail
b) Facebook Part - III
c) twitter
Explain in Brief Answer
d) Linkedin 1. Define ARPANET.
2. What is the usage of cloud storage
13. Facebook was created at and cloud computing?
------------year
3. What is meant by artificial
a) 2002 b) 2004
Intelligence?
c) 2013 d) 2010
4. List out some usefulness of social
14. In mobile network, land areas for networks.
network coverage was distributed as 5. How computer networks saves the
a) Firmware b) cells money saving?
c) Range d) Service
Part - IV
Explain in detail
1. Define computer networking and Internet. Explain different developments on
computer network and Internet.
2. Explain the growth of the computer networking.
3. Mention some uses of network at business, home, mobile, social application.
student activities
11
CHAPTER
LEARNING OBJECTIVES
●● To know network examples like Intranet, Intranet, Extranet
●● Different types of mobile networks
●● Know about wlans :802.11
●● To Know about RFID
●● Discus briefly about osi, tcp,ip and other network protocols
Individual
Internet users
Firewall
Extranet
Figure 11.3 Extranet
Comparison
Table 11.1 Comparison between Internet, Intranet and Extranet
Type Definition Example
Internet a global network, public TCP/IP network used Sending email to a friend
by over a billion people all over the world
Intranet a TCP/IP network with access restricted to Accessing your record in the
members of an organization employee personnel file
Extranet TCP/IP network with restricted access to Checking availability of inventory
members from an outside supplier
Extranet
server Intranet
Internet server
Application
server
Extranet Intranet
or data networks. Cells will often be smaller ●● Second to Third Generation Bridge
in size in large towns, as the number of users (2.5)2000 – GPRS launch
in the area is more. Communication over ●● Third Generation( 3G) 2003- UK 3G
mobile network is be made up of voice, data, launch
images and text messages. See Figure 11.5 ●● Fourth Generation (4 G) 2007
Marcocells ●● Fifth Generation (5G) 2019+
stops seamless roaming across assorted transmission and Code Division Multiple
access networks and routing domains. Access to delivery data rates of up to
This means each operator must cover the 2Mbit/s supports multimedia services
entire area or have agreements in place to (MMS: voice, video and data). European
permit roaming. standard is UMTS (Universal Mobile
Telecommunication Systems). Mobile
Second to Third Generations Bridge phones systems continue to use digital
(2.5G) 2000 – GPRS launch transmission with SIM authentication for
GPRS was introduced here, it seen as billing systems and for data incorruption.
an excess period of mobile networking Data transmission used a WCDMA.
development, between 2G and 3G. WCDMA stands for (Wideband Code
GPRS stands for(General Packet Radio Division Multiple Access). One technique
Service).GPRS is a data service which to obtain data rates between 384kbit/s
enables mobile devices to send and and 2048kbit/s. Few 3G suppliers use
receive messages, picture messages and ATM (Asynchronous Transfer Mode) for
e-mails. It allows most popular operating their ‘over the air’ network with in MPLS
speeds of up to 115kbit/s, latterly (Multiprotocol Label Switching) or IP for
maximum of 384kbit/s by usingEDGE. theirs backbone network.
EDGE stands for EDGE (Enhanced Mobility still supported at layer
Data rates for Global Evolution). GSM 2, and hence like 2G it still prohibits
data transmission rates typically reached seamless roaming beyond heterogeneous
9.6kbit/s. access networks and routing domains.
Third Generation(3G)2003 – First The transmission were band frequencies
UK 3G launch are between 1900 and 2200 MHz. All
UMTS license holders at the UK holds
This generation of mobile systems merges
a 20 year license with the condition that
different mobile technology standards,
80% population coverage is achieved by
and uses higher frequency bands for
31 December 2007. The present third
generation licensed operators in the UK
can be seen below as at August 2004.
Li-Fi is a wireless technology
which uses light-emitting diodes Fourth Generation(4G) 2007
(LEDs) for data transmission
whereas Wi-Fi uses radio frequencies for 4G is at the research stage. 4G was based on
data transmission. Li-Fi is the short form an adhoc networking model where there was
of Light Fidelity. no need for a fixed infrastructure operation.
The term Li-Fi was first used by Adhoc networking requires global mobility
Harald Haas, Professor in Edinburgh features (e.g. Mobile IP) and connectivity
University. The computer scientists to a global IPv6 network to support an IP
achieved speeds of 224 gbps in the lab address for each mobile device. Logically
and research is going on. The biggest roaming in assorted IP networks (for
revolution in the Internet world is going example: 802.11 WLAN, GPRS and UMTS)
to happen
were be possible with higher data rates, from
Chapter 11 Network Examples and Protocols 159
www.tntextbooks.org
2Mbit/s to 10–100Mbit/s, offering reduced is that the technical code for the protocol.
delays and newly services. Mobile devices See Figure 11.6
will not expect on a fixed infrastructure,
they will require enhanced intelligence to
self configure in adhoc networks and having
a routing capabilities to route over a packet-
switched network.
Reader
Tag
Antenna
OSI Layers:
Tag or 1. Physical Layer: This is the 1st layer,
transponder it defines the electrical and physical
specifications for devices.
Computer
2. Data Link Layer: It is the 2nd layer and
Figure 11.11 An Active RFID system it guarantees that the data transmitted
are free of errors. This layer has simple
11.2 Refenrence Model protocols like “802.3 for Ethernet” and
“802.11 for Wi-Fi”.
11.2.1 OSI Model
3. Network Layer: It is the 3rd layer
Open System Interconnection (OSI) determining the path of the data
model was found in the year 1934, general packets. At this layer, routing of data
framework that enables packets is found using IP Addressing.
network protocols
4. Transport Layer: It is the 4th layer that
along with software and
guarantees the transportation/sending
systems to be developed
of data is successful. It includes the
based on general set of
error checking operation.
guidelines. It describes
the standards for the inter-computer 5. Session Layer: It is the 5th layer,
communication. See Figure 11.12 identifies the established system
session between different network
entities. It controls dialogues between Protocol (IP). The Internet Protocol typically
computers .For instance, while specifies the logistics of the packets that
accessing a system remotely, session are sent out over networks; it specifies the
is created between your computer and packets which have to go, where to go and
the remote system. how to get there. The Transmission Control
6. Presentation Layer: It is the 6th layer Protocol is accountable for guaranteeing
that does the translation of data to the trustworthy transmission of data. It sees
the next layer (Prepare the data to the that the packets for errors and submits the
Application Layer). Encryption and requests for re-transmissions incase any of
decryption protocols occur in this layer them are missing’
such as, Secure Socket Layer (SSL).
Frequent TCP/IP Protocols
7. Application Layer: It is the 7th layer,
which acts as the user interface ●● HTTP – It is used between a web client
platform comprising of software and a web server and it guarantees
within the system. non-secure data transmissions.
●● HTTPS – It is used between a web
11.2.2. TCP/IP
client and a web server ensures secure
Transmission Control Protocol/Internet data transmissions.
Protocol, TCP/IP is a set of protocols
●● FTP – It is used between computers
which governs communications among all
for sending and receiving file.
computers on the Internet. TCP/IP protocol
tells how information should be packaged, Domain Names and TCP/IP Addresses
sent, and received, as well as how to get to The address for any website is not as easy
its destination. See Figure 11.3 as to remember, domain name are used
TCP WORKING: TCP/IP is a instead. For example, 216.58.216.164
combination of two protocols: Transmission is one of the IP address for Google and
Control Protocol (TCP) and Internet google.com is the domain name.
32 bits
0 4 8 16 19 31
Version Length Type of service Total length
Identification Flags Fragment offset
IPv4 Heder
points to remember
Internet Several networks, small and big all over the world, are connected together to
form a Global network called the Internet.
Intranet It is a website used by organizations to provide a place where employees can
access company related information.
Extranet It is a private network using Internet technology to share part of business
information with supplier’s partners and customers.
APRANet Advanced Research Projects Agency Network
TCP/IP Transmission Control Protocol / Internet Protocol
Wi-Fi Wireless Fidelity.
RFID Radio Frequency Identification.
OSI Open System Interconnection
HTTP Hypertext Transfer Protocol
HTTPS Hypertext Transfer Protocol Secure
FTP File Transfer Protocol
SMTP Simple Mail Transfer Protocol
UDP User Datagram Protocol
SMTP Simple Mail Transfer Protocol
DNS Domain Name System
EVALUATION
11. ------------- refer to other host computers by using names rather than numbers.
a) DNS b) TCP c) FTP d) SMTP
12. TCP/IP is a combination of two protocols:
i. Transmission Control Protocol (TCP) ii. Internet Protocol (IP)
iii. Selection Protocol (SP) iv. Captial Protocol (CP)
a) i, ii b) i, iii c) iii, iv d) ii, iii
Part - II
Short Answers
1. Define Intranet
2. What is the uses of mobile networks?
3. List out the benefits of WiFi
4. How many types of RFID system available and what are they?
5. Expand HTTP, HTTPS, FTP.
Part - III
Explain in Brief Answer
1. Compare Internet, Intranet and Extranet
2. List out the components of a RFID enabled system.
3. Write short notes on HTTP, HTTPS, FTP.
4. What are the layers available in TCP/IP Reference Model?
5. Expand ARP, ICMP, SMTP and DNS.
Part - IV
Explain in detail
1. Explain about Internet, Intranet and Extranet.
2. Discuss about OSI model with its layers.
3. Difference between TCP/IP and OSI Reference Model.
4. Explain about the development, merits and demerits in Mobile networks.
student activities
12
CHAPTER
LEARNING OBJECTIVES
●● To understand the need of Domain Name System for proper functioning of
Internet
●● To know the importance of IP addresses
●● To know the parts of URL and its types
●● To know the components of Domain name system and its functions
●● To know how the DNS is working
170
www.tntextbooks.org
www.tnschools.gov.in
35.173.69.207
DNS server
While typing a web address, e.g., host system in the whole network. Due
www.tnschools.gov.in, DNS translates to increase in the number of system in a
it into a machine friendly IP address network there is a need of more addresses
(for example 35.173.69.207 is the IP for which lead to two addressing methods i.e.,
www.tnschools.in) and directs your IPv4 and IPv6.
Internet connection to the correct website.
12.3.1 IPv4 Address
American computer scientist IPv4 address is a 32-bit unique address
Paul V. Mockapetris together given to a computer system. No two systems
with Jon Postel, invented the can have same IP address. If the network has
Internet Domain Name System (DNS)
p connections then ‘ p’ addresses should be
Jon Postel was an administrator of the
Internet Assigned Numbers Authority there. An address space is the total number
(IANA) until his death and he was of addresses that can be made by that
known as “God of the Internet”. protocol. It is determined by the number
of bits that the protocol use. If the protocol
uses ‘n’ bits then the address space of that
protocol would be ‘2n’ addresses can be
formed. So, the number of addresses that
can be formed in IPv4 is 232. There are two
ways to represent the IP address
Jon Postel Paul V. Mockapetris ●● Binary notation
●● Dotted-decimal notation
12.3 IP Address In binary notation the address is expressed
Internet Protocol (IP) address is simply as 32-bit binary values.
the logical address in the network layer. For E.g. 00111001 10001001
Like how the door number/flat number 00111000 00000111
is used to differentiate
individual house from In dotted-decimal notation the address
others in the same is written in decimal format separated by
apartment IP address dots(.). Refer Figure 12.2
is also used to find the For e.g. 128.143.137.144
Chapter 12 DNS (Domain Name System) 171
www.tntextbooks.org
128.143.137.144
Figure 12.2 IPv4 Address
http://cms.tn.gov.in/sites/default/files/press_release/pr070119a.jpg
Root (Level 0)
Label
edu
edu. Domain name
Label
Label
Figure 12.6 explain the domain ●● Domain names have the minimum
name and label clearly. challenger.atc. length of 2, and the maximum length
fhda.edu. is the domain name which of 63 characters. The entire name may
is obtained by reading the labels from be at most 253 characters long.
bottom to top, separating each label by ●● Domain names are not case-sensitive.
dot (.) Refer Figure 12.7 (It may be upper, lower or mixing of
both case letters)
Domain name
Generic Top-Level Domain names:
It is the sequence of labels. In domain
name the sequence of labels are separated Top level domain is the last part of a domain
by dot (.). The domain name is always read name. Generic top level domains are used
from the lower level to higher level i.e., for generic purpose and maintained by
from the leaf node to root node. Since the IANA. Refer Table 12.1
root node always represent NULL string,
all the domain name ending with dot. Table 12.1 Generic Domain Names
Domain Name Meaning
Basic rules of Domain names
com Commercial Organisation
●● Domain can consists of Alphabets a
through z, and the digits 0 through 9. edu Educational Institutions
●● Hyphens are allowed, but hyphens gov Government (US)
can not be used as first character of a
mil Military groups
domain name.
●● Spaces are not allowed org Non profit Organization
●● Special symbols (such as !, $, &, _ and net Networking organization
so on) are not permitted.
info Information service
providers
Top level
.com .org .net .in domains
Second level
.ac .mil .co .gov .nic
.tnscert .tnpesu domains
.dge
.eservices
Country top-level domain names as responding to requests from all over the
Country domain uses 2-character country world. It also becomes unreliable because
abbreviation according to country. For e.g., in case of any failure the data becomes
google.in – for INDIA, google.us for US. inaccessible.
Refer Table 12.2 The solution to this problem is to
distribute the information among many
Table 12.2 Country domain names
computers. The best way to do that is to
Domain Name Meaning divide the entire space into many domains
in India and sub domains. DNS also allows domains
us United States to be further divided into sub domains.
fr France By this, the solution to the problem is
obtained and hierarchy of servers is also
uk United Kingdom
maintained. Name servers store the data
ca Canada and provide it to clients when queried by
au Australia them. Name Servers are programs that
lk Srilanka run on a physical system and store all the
bd Bangladesh zone data.
cn China
Inverse domain performs the
pk Pakistan
opposite task of normal DNS
jp Japan query. It converts the IP address
sg Singapore to domain name.
2
Top level
5 name
Top level
server name
1 3 server
Local DNS
name server Local DNS
4
name server
Host
Authoritative
DNS server Authoritative
DNS server
Figure 12.8 working structure of Name server
Root
The resolver is a program which
is responsible for initiating the
.com Zone translation of a domain name
into an IP address. Since a resolver is
mhhe Domain
stored in the host, There is no need
Zone and
domain of any protocol to form a connection
between the resolver and the user
program.
DN Browser
QUERY
Where is Type
Resolver www.tnscert.org
www.tnscert.org
Local Server
www.tnscert.org
don’t know don’t know is at 198.71.57.84
ask ask
them them
Root Server Org Server tnscert.org Server
Web Server
Web server is a program running on dedicated machine which handle the queries of
www enduser. Server is used to host the websites and to deliver the contents of websites using
HTTP. While typing the URL in browser, the browser send the URL to DNS. After getting an
IP address from DNS, It sends the request to the web server with IP address . Now the content
of websites appear on browser.
server i.e., TLD (Top Level Domain) which reviews the request and direct the query to name
servers associated with that specific domain. Until the query is solved it is passed to next level
domains. At last the mapping and the record are returned to the resolver who checks whether
the returned value is a record or an error. Then the resolver returns the record back to the
computer browser which is then viewed by the user. Refer Figure 12.10
points to remember
●● Domain Name System (DNS) maintains all the directory of domain names and
help us to access the websites using the domain names. It translates the domain
name into IP address.
●● IPv4 address is a 32 bit unique address given to a computer or a device. There are
two ways to represent the IP address: Binary notation, Dotted-decimal notation.
●● URL is made up of four parts- protocols, hostname, folder name and file
name. Absolute URL contains all the four necessary and fundamental parts
of URL.
●● Relative URL contains only folder name and the file name or just the file
name.
●● There are 3 important components in the Domain Name System. They are
Namespace, Name server and Zone.
●● Domain name space is a tree like structure with root element on the top. It
can have a maximum of 128 levels starting from root element taking the level
0 to level 127.
●● Domain name is the sequence of labels separated by dot (.). The domain
name is always read from the leaf node to root node. The root node always
represent NULL string. So All the domain name ends with dot.
●● In the domain name space (DNS) tree structure domain is a sub structure
tree. The domain can be further divided into sub domains.
●● Name Servers are programs that run on a physical system and store all the
zone data. It provides to clients when queried by them.
●● Zone is the contiguous part up to which the server has access. The domain
assigned for the server does not divide into further sub domains then zone is
same as domain.
DNS Domain Name System an Internet service that translates domain name into IP
address.
IP address used to uniquely identify a computer over the network.
URL Uniform Resource Locator, the address of a specific web page or file on the
Internet.
Domain Name A naming system on which domain names are in a hierarchical and logical tree
space structure.
Domain Name a symbolic name associated with an IP address
Name server Contains the DNS database which consists of domain names and their
corresponding IP addresses.
ICANN Internet Corporation for Assigned Name and Numbers, Non-profit organization
which regulates an Internet.
IANA Internet Assigned Numbers Authority (IANA) is an affiliated authority of
ICANN.
Zone A group of contiguous domains and sub domains in the Domain Name Space.
The resolver a program which is responsible for initiating the translation of a domain name
into an IP address
TLD Top Level Domain, domains below the root domain
IPv4 /IPv6 Internet Protocol version 4/6
EVALUATION
Part - I
Choose the correct answer
1. Which of the following is used to maintain all the directory of domain names?
a) Domain name system b) Domain name space
c) Name space d) IP address
2. Which of the following notation is used to denote IPv4 addresses?
a) Binary b) Dotted-decimal
c) Hexadecimal d) a and b
15. Match the following 10. What are the categories available in
a. domain - 1. progress domain name space?
that initiates 11. Write any four generic Top Level
translation Domain.
b. zone - 2. contains database
Part - III
of domain names
Explain in Brief Answer
c. name server - 3. single node
1. Write a note on DNS.
d. resolver - 4. contiguous nodes
a. 1432 2. Differentiate IPv4 and IPv6.
b.3421 3. Differentiate Domain name and
c. 3214 URL
d. 3412 4. What are the differences between
Absolute URL and Relative URL?
Part - II
5. Write a note on domain name.
Short Answers
1. List any four domain names. 6. Differentiate web address and URL
2. What is an IP address? Part - IV
3. What are the types of IP address? Explain in detail
4. What is an URL? 1. Explain briefly the components of
5. List out four URLs you know. DNS.
6. What are the types of URL? 2. Classify and Explain the IP address.
7. What is a domain? 3. Explain about the name server?
8. What is a zone? 4. What is domain name space?
9. What is a resolver? Explain.
5. Explain how the DNS is working.
student activities
5. Buy your own domain name or create free sub-domain and connect free hosting
servers.
For example:
www.goDaddy.com, www.webs.com
13
CHAPTER
Network Cabling
LEARNING OBJECTIVES
●● To know the necessity of cabling in computer networking.
●● To know the different types of cables used in networking.
●● To know the components involved in making of Ethernet cable.
●● To know the various types of Registered Jacks and its functions
●● To know the wiring and colour coding techniques used in Ethernet cabling.
●● To practice in making an Ethernet cable with desired length.
185
www.tntextbooks.org
In the figure 13.1 huge and huge cables 2. Twisted Pair Cables: It is type of
are used during network cabling, it really cable with two or more insulated
makes everyone confuse which wire wires twisted together. It started with
should connect. So the process is going to the speed of 10 mbps (10BASE-T
reduce the number of cables and making cable is used). Then the cable is
alternatives in networking. improved and the speed was higher
and went to 100 mbps and the cable
13.2 Types of Network was renamed as 100BASE-TX. Then
Cables finally the cable improved more made
to 10 gbps and named as 10GBASE-T.
There are many types of cables available in
This twisted cable has 8 wires which
the networking. Here we discuss about six
are twisted to ignore electromagnetic
different cables.
interference. Also the eight wires
1. Coaxial Cables: This cable was
cannot be placed in a single unit there
invented at late 1880’s, which is used
could be a difficult in spacious, so it
to connect the television sets to
is twisted to make as one wire. There
home antennas. This cable is used to
are two types of twisted pair cables,
transfer the information in 10 mbps.
Unshielded Twisted Pair (UTP) and
The cable is divided into thinnet and
Shielded Twisted pair (STP). The UTP
thicknet cables. These cables have
is used nowadays as modern cables
a copper wire inside and insulation
for Internet and they are lower in cost
is covered on the top of the copper
and installation and maintenance is
wire to provide protection to the
easy compared to the coaxial cables.
cable. These cables are very difficult
STP is similar to UTP, but it is covered
to install and maintain, because they
by an additional jackets to protect the
are too big to carry and replace. The
wires from External interference. See
coaxial cable got its name by the word
Figure 13.3
“coax”. Nowadays coaxial cables are
also used for dish TV where the setup
box and the television is connected
using the coaxial cable only. Some
of the cable names are Media Bridge
50-feet Coaxial cable, Amazon basics
CL2-Rated Coaxial cables, etc. See Figure13.3 Twisted pair cables
Figure 13.2
3. Fiber Optics: This cable is different
from the other two cables. The other
two cables had an insulating material
at the outside and the conducting
material like copper inside. But in
this cable it is of strands of glass
Figure13.2 Coaxial cables for connecting
and pulse of light is used to send
television sets the information. They are mainly
186 Chapter 13 Network Cabling
www.tntextbooks.org
used in Wide Area Network (WAN). through the USB called dongles. The
The WAN is a network that extends dongle is a small peripheral device
to very large distance to connect which has a compatible of mobile
the computers. One example of broadband with a sim slot in it
WAN is Internet. These cables are and connects the Internet and acts
placed in deep underground to as a modem to the computer. See
avoid any damage to the cables. The Figure 13.5
optic cable uses light to transmit
the information from one place he latest version of USB is USB
T
to another. There are two types of 3.0 which has the data transfer rate
fiber optic cables available, One is 4.85 Gbps. But USB 2.0 has just
single-mode (100BaseBx) another 480 Mbps.
one is Multimode (100BaseSX). Micro USB is a miniaturized version
Single-mode cables are used for of the USB used for connecting mobile
devices such as smart phones, GPS
long distance transmission and at
devices and digital cameras.
a high cost whereas the multimode
cables are used for short distance
transmission at a very low cost. The
optic cables are easy to maintain and
install. See Figure 13.4
Figure 13.5 The USB Cables and USB dongle connected to a laptop.
Ethernet cards. These cards enable the solid colours, and the others are striped.
computers to have a connection with The eight colors are white green, green,
other devices by using Ethernet cables. white orange, blue, white blue, orange,
The switches and routers may be used white brown and brown. The following
to increase the number of systems to be figure 13.8 shows the patch cable.
interconnected.
The Ethernet cable is the basic
component of the Local Area Network
(LAN); here the only one popular
Ethernet wire is used, RJ45 Ethernet
cable. Here we shall be discussing the
different components used inside this
Ethernet cable. The components of the
Ethernet cable are RJ45 connector, patch
cable (UTP cable), plastic covering. The
RJ45 connector is made up of plastic
cubes connected at the both the ends.
With this connector we will connect Figure 13.8 Patch cable (Twisted pair)
one end at the computer and other end Ethernet cables are
at the LAN port. The patch cables has normally manufactured in several
eight small wires inside. The plastic industrial standards such as Cat
covering is used to provide protection to 3, Cat 5, Cat 6, Cat 6e and cat 7.
the wires when it is bending or twisted “Cat” simply stands for “Category,” and the
during connecting to the system or to following number indicates the version.
the LAN port. Latest version denotes faster and higher
Ethernet cabling is the process frequencies, measured in Mhz. Increasing
of connecting the computers with other the size of the cable also lead to slower
devices using Ethernet cables. The three transmission speed.
main components are used in the Ethernet The cables together with male
cabling components are connectors (RJ45) on each end are
commonly referred as Ethernet cables. It
1. Patch Cable (Twisted pair)
is also called as RJ45 cables, since Ethernet
2. RJ45 Connector cable uses RJ45 connectors
3. Ethernet Ports A crossover Ethernet cable is
4. Crimping Tool specially designed for making a connection
between two computers. Generally, the
13.3.1 Patch Cable (Twisted Ethernet cables are designed to make a
Pair) connection between a computer and a
These Cables are generally made up of 8 router or switch.
wires in different colors. Four of them are
a slightly wider. The Ethernet cables are codes
sometime called as RJ45 cables. In RJ45 Pin T-568A Pin T-568B
the “RJ” stands for the Registered Jack 1 white / green 1 white / orange
and the “45” simply refers to the number stripe (Tx+) stripe (Tx+)
of interface standard in the cable. See
2 green (Tx-) 2 orange (Tx-)
Figure 13.9
3 white / orange 3 White / green
stripe (Rx+) stripe (Rx+)
4 blue 4 blue
5 white / blue 5 white / blue
stripe stripce
6 orange (Rx-) 6 green (Rx-)
7 white / brown 7 white / brown
stripe stripe
Figure 13.9 RJ45 Connector
8 brown 8 brown
Each RJ45 connector has eight pins
Although four pairs of wires are
and connected to each end of the Ethernet
available in the cable, Ethernet uses only
cable. since it has 8-position, 8-contact
two pairs: Orange and Green. The other
(8P8C) modular plug, It is also known as
two colors (blue and brown) can be used
8P8C connector. These plugs (connector)
ISDN or phone connections.
are then inserted into Ethernet port of the
network card. As we have already discussed
about the pin details in the Ethernet
Wiring schemes and colour codes of connector. The position of the pin details
the connector
briefly. Now let’s see the pin details of
The RJ45 connector has eight small jack the Ethernet ports, the pin 1 shows the
inside to connect eight small wires of the transmission positive the pin 2 shows the
patch cable. The eight cables are in eight transmission negative the pin 3 shows
different colors. Let’s discuss that eight the receiver positive. The pin 4 shows the
colors and where does that eight colors reserved position it is nothing but tells the
connect to the RJ45 connector. connection for some other use. The pin
Wiring schemes specifies how the 5, 7, 8 are also used as reserved position.
wires to be connected with RJ45 connector. The pin 6 shows the receiver negative. The
There are two wiring schemes available two main signals of the pins: the one is the
T568A T568B
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
12
34
56
78
Pin 4: Pin 5:
Reserved Reserved
Pin 3: Pin 6:
Receive + Receive –
Pin 2: Pin 7:
Transmit – Reserved
Pin 1: Pin 8:
Transmit + Reserved Pin 1 Pin 8
5. In this position of pin no. 5 describes connector with Ethernet cable. It is also
that it is not connected or bidirectional called as RJ45 jack. It is found on personal
and the color is white blue. computers, laptops, routers, switches, hubs
6. In this position of pin no. 6 describes and modems. We can see an Ethernet port
the receive data or bidirectional on the back side of a computer or a laptop.
with the RX (Negative) which has a It connects Ethernet cable with Ethernet
negative terminal and the color used card mounted on motherboard.
in this position is orange. In these days, most of the computers
7. In this position of pin no. 7 describes and laptops have a built-in Ethernet port
that it is not connected or bidirectional for connecting the device to a wired
and the color is white brown. network. Some of them not having an
8. In this position of pin no. 8 Ethernet port use an Ethernet dongles
describes that it is not connected or to form a network with other devices.
bidirectional and the color is brown. Devices or computers which use wifi only
for networking eliminates both the cable
13.3.3 Ethernet card and Port and its port. See Figure 13.13
Ethernet card is a Network Interface
Card (NIC) that allows computers to Ethernet port (RJ45 Jack)
Figure 13.14 Crimping Tool for RJ-11 (6 pin) and Figure 13.15 Crimping process using crimping
RJ-45 (13 pin) tool
history of ethernet
Bob Metcalfe invented Ethernet in 1973 while at Xerox PARC (Palo Alto Research Center
in California, USA) and the company patented it in 1975. It was used for interconnecting
advanced computer workstations, making it possible to send data to one another and to
high-speed laser printers. Metcalfe and others then finalized an open Ethernet standard in
1980, and by 1985 it had become an IEEE standard. An industry was born, and Ethernet was
ready for its meteoric rise.
There have been a number of networking standards published in the 802 branch of the
IEEE, including the 802.3 Ethernet and 802.5 Token Ring standards. The IEEE standard was
first published in 1985 with the title IEEE 802.3 Carrier Sense Multiple Access with Collision
Detection (CSMA/CD) Access Method and Physical Layer Specifications . The IEEE standard
does not use “Ethernet” in the title, even though Xerox relinquished their trademark on the
Ethernet name. That’s because open standards committees are quite sensitive about using
commercial names that might imply endorsement of a particular company. As a result, the
IEEE calls this technology 802.3 CSMA/CD or just 802.3. However, most people still use the
Ethernet name when referring to the network system described in the 802.3 standard.
Source : www.wikipedia.org
have 8 pins. This RJ-61 will use the 13.5.1 Straight-Through Wiring
twisted pair cable with a modular 8 In general, the Ethernet cables used
connection. See Figure 13.17 for Ethernet connections are “straight-
through cables”. These cable wires are
in the same sequence at both ends of
the cable, which means that pin 1 of the
plug on one end is connected to pin 1
of the plug on the other end (for both
standard – T568A & T568B). the straight
through wiring cables are mostly used for
connecting PC / NIC card to a hub. This
Figure 13.17 RJ-14 Ethernet Connector is a simple physical connection used in
3. RJ-21: The RJ-21 connector has 50 printers, computers and other network
pins with 25 pins at one end and 25 interfaces. See Figure 13.19
pins at the other end. It is also called
as champ connector or Amphenol 1 1
2 2
connector. The Amphenol is a
3 3
connector manufacturer. The 4 4
RJ-21 interface is typically used 5 5
for data communication trucking 6 6
at another end and vice versa. Specifically, flat (and light blue color) to distinguish it
connect the solid Green (G) with the solid from other types of network cabling.
Orange, and connect the green/white with 1 1
the orange/white. See Figure 13.20 2 2
3 3
PC Cross over PC
4 4
Tx+1 1 Tx+
5 5
Tx–2 2 Tx–
6 6
Rx+3 3 Rx+
7 7
4 4 8 8
5 5
Rx–6 6 Rx– Figure 13.21 Roll over Wiring
7 7 These all the three arrangements are used
8 8 to perform an interface change. But, all
Figure 13.20 Cross over wiring
the three arrangements transmits the data
at the same speed only. See Figure 13.21
13.5.3 Roll-over Wiring
Rollover cable is a type of null-modem
How to determine the type
cable that is often used to connect a device
of Ethernet cables?
console port to make programming changes
to the device. The roll over wiring have Straight-through: The coloured wires
opposite pin arrangements, all the cables are in the same sequence at both ends
are rolled over to different arrangements. of the cable.
In the rollover cable, The coloured wires are Cross-over: The first coloured wire
reversed on other end i.e. The pins on one at one end of the cable is the third
end are connected with other end in reverse coloured wire at the other end of the
order (i.e. pin 1 to 8, 2 to 7, 3 to 6, 4 to 5, 5 to cable.
4, 6 to 3, 7 to 2, 8 to 1). Roll-over: The coloured wires are in
Rollover cable is also known as the opposite sequence at either end of
Yost cable or Console cable. It is typically the cable.
points to remember
●● By using World Wide Web, now ●● Twisted cable has 13 wires which are
people can access the network from twisted to ignore electromagnetic
different parts of the world. interference
●● The Network cables are used to ●● Two types of twisted pair cables are
transfer the data and information to Unshielded Twisted Pair (UTP) and
another computer. Shielded Twisted pair (STP).
●● Coaxial cables are used for connecting ●● The optic cable uses light to transmit
the television with setup box. the information from one place to
Null modem A communication method directly connects two computers without modem
cables or any equipment.
LAN Local Area Network in which the devices used in home or office
interconnected for sharing the resources.
TX / RX Transmit / Receive signals used in connectors
Dongles The dongle is a small peripheral device with a sim slot in it and connects the
Internet and acts as an Ethernet port to the computer.
EVALUATION
student activities
14
CHAPTER
LEARNING OBJECTIVES
To know the
●● Need of Open Source Software. ●● OpenNMS and Group which created
●● NS2 and its Use OpenNMS
●● OpenSource Hardware
Copyright
Vendor Vendor Vendor
Owner
Contributor Contributor
OSS
Project
OSS
Project
software and tools tool – NS2
●● There are many opensourcesoftwares.
In computer network, network
so, we can select and use any software
simulation is a method whereby a
that suits our needs.
software program models the activities
●● The complete options of the software of a network by calculating the
can be used without any cost and communication between the different
restrictions. network objects such as(routers, nodes,
●● We can share our ideas with the team, switches, access points, links etc.).
write the required code and share it A network simulator is a software
with many. program that replicates the functioning
●● As we can identify the programming of a computer network. In simulators,
techniques of group members, we the computer network is typically
can learn many ideas and make our demonstrated with devices, traffic etc.
program writing skills more efficient. and the performance are evaluated.
●● The coding in opensourcesoftwaresare Normally, users can then adapt the
being groomed by many enthusiastical simulator to accomplish their precise
members of the group. So if we report analysis needs. The network parameters
problems that we have in the program define the state of the network (node
they are quickly mended by the group’s placement, existing links) and the events
effort. (data transmissions, link failures, etc.).
A significant output of simulation is the
●● As we can make changes to the
trace files. Trace files can document every
opensourcesoftwares, we can add the
incident that happened in the simulation
most required features in the software
and are used for examination.
●● Many open source software are very
user friendly. NS2 is the abbreviation of
NETWORK SIMULATOR version 2. It
Like benefits Opensource Software was considered explicitly for exploration
also have Some Problems Like Difficult in network communication and event-
to work for beginners, Exchange of files driven open-source simulator in
to other softwares, Some time Lack of computer.
Responsibility, service and problems with
OTCL and c++ used to create
hardware compatible.
and run NS2. NS2 works on Windows
and Linux platforms, that supports
Example of open source
wired or wireless network and also use
Application software
the command line interface as a user
NS2 , OPEN NMS, Ubuntu , MySQL,
interface, API a pure event base software
PDF Creator, Open Office, 7zip
tool with super simulation design, it has
GNUCASH, GIMP, BLENDER,
more models which help the user to get
AUDACITY, VLC, MOZILA FIREFOX,
desired output easily.
MAGENTO, ANDROID, PHP
points to remember
●● Open Source denotes to some program whose source code is made available for
usage or reform as users or other developers see appropriate
●● In simulators, the computer network is typically demonstrated with devices,
traffic etc. and the performance are evaluated.
●● A significant output of simulation is the trace files. Trace files can document
every incident that happened in the simulation and are used for examination.
●● NS2 has C++ and Object-oriented Tool Command Language (OTcl) of languages
2.
●● It link together for C++ and the OTcl using TclCL.
●● Open NMS (Network Management System) is a free and open-source initiative
grade network monitoring and network management platform.
●● Network monitoring software notifications help the user/administrator for
fixed errors.
SOURCE CODE Set of Instructions that decide, how the software should work
EVALUATION
Part - II
Short Answers
1. Explain the History of open source software
2. What is meant by network simulator?
3. What is trace file?
4. Write short notes on NS2.
5. Explain NRCFOSS.
6. Write short note on Open NMS?
Part - III
Explain in Brief Answer
1. What are the uses of Open source Network Software?
2. Explain Free software.
3. List out the Popular open source software.
4. Write note on open source hardware.
5. What are the main functional areas of Open NMS?
6. Explain Types of Organisations related to Open Source.
Part - IV
Explain in detail
1. Differentiate Proprietary and open source software.
2. List out the Benefits of Open Source Software
3. Explain various Open Source License.
student activities
1 Mention Open source software and free software names that not explain in this
chapter.
2. Mention Software that are accounts related.
3. Mention Open Source Developing and maintaining companies
15
CHAPTER
E-Commerce
LEARNING OBJECTIVES
●● To learn the concept of E-Commerce.
●● To know the brief history of E-Commerce.
●● To analyze different types of E-Commerce business models and revenue models.
●● To distinguish between E-Commerce and Traditional commerce.
●● To understand the advantages and disadvantages of E-Commerce.
Common Business
Infrastructure
& publishings
●● Goods - e.g. mobile phones, digital to grow when National Science Foundation
cameras, clothes, accessories, antivirus. opened the Internet to the public in 1991.
●● Information - e.g. subscription to Since then businesses have started to take
some newspapers, scientific journals, up residence at websites.
television channels. With the progress of the Internet
●● Services - e.g. matrimonial services, technology and vastly developed global
placement services. Internet community, large number of
●● Tangible form – e.g. a digital camera Dotcoms, FinTech and Internet Startups
purchased by a consumer from an have appeared and a strong foundation of
online shopping website which might electronic commerce continues to build.
be delivered at the requested address. The Internet had provided new
●● Electronic form – e.g. a music album or commercial potential not only for
a software downloaded from a site which large organizations, but also provided
might be delivered in electronic form. a sustainable entry point for Small and
Medium-sized Enterprises (SMEs) of
E-Commerce. Today, E-Commerce is
15.2 The Evolution of
no longer an exclusive domain of large
Electronic Commerce
organizations or private networks.
E-Commerce is not a completely new type
Even though E-Commerce has
of commerce. The dawn of E-Commerce
been existing since few decades, it has
started few decades ago and, continues to
recently sustained significant growth. It is
grow exponentially. It first emerged on
because the Internet has transformed from
private networks in 1970s. Electronic Data
an auxiliary communication medium of
Interchanges and teleshopping together
academics and large organizations to an
paved the way for the E-Commerce.
entrenched communication medium that
The history of modern E-Commerce extends nearly all parts of mainstream
is closely twisted together with the history society. Integrated with commercialization
of the Internet. E-Commerce became really of the Internet, personal computers and
possible when the Internet was opened to electronic payment systems together
commercial use. Online shopping started made E-Commerce flourish.
Growth of Electronic Commerce: 2004 – 2009
Commerce The second wave is the rebirth of
E-Commerce after the dotcom burst. The
Economists describe four distinct waves
second wave is considered as the global
(or phases) that occurred in the Industrial
wave, with sellers doing business in many
Revolution. In each wave, different
countries and in many languages. Language
business strategies were successful.
translation and currency conversion were
Electronic commerce and the information
focused in the second wave websites. The
revolution brought about by the Internet
second wave companies used their own
likely go through such series of waves.
internal funds and gradually expanded their
Refer Figure 15.5
E-Commerce opportunities. As a result
E-Commerce grows more steadily, though
●● The First Wave of Electronic
more slowly. The rapid development of
Commerce: 1995 -2003
network technologies and interactive
The Dotcom companies of first wave are web (web 2.0, a period of social media)
mostly American companies. Thereby offered the consumers more choices of
their websites were only in English. buying. The increased web users nourished
The Dotcom bubble had attracted huge E-Commerce companies (mostly B2C
investments to first wave companies. companies) during the second wave.
As the Internet was mere read-only
web (web 1.0) and network technology ●● The Third Wave of Electronic
was in its beginning stage, the bandwidth Commerce: 2010 – Present
and network security was very low. Only The third wave is brought on by the mobile
EDI and unstructured E-mail remained as technologies. It connects users via mobile
a mode of information exchange between devices for real-time and on-demand
businesses. But the first wave companies transactions. mobile technologies. It
enjoyed the first-move advantage and connects users via mobile devices for real-
customers had left with no options. time and on-demand transactions. Not
only the information is filtered by time, but
1
WEB 3.0
100 million
Number of users
WEB 2.0
WEB 1.0
Read-Write-Execute
Web, Smart Search,
Virtual Shopping,
Read-Write Web, Social Commerce, Auctons, Semantic Web,
10 million
7000
6000
Dot-com
market peak
Indes matches
Dot-com peak Figure 15.6 E-Commerce business models
5000
0
1990-01-01
1990-03-01
1991-05-01
1992-01-01
1992-03-01
1993-05-01
1994-01-01
1994-03-01
1995-05-01
1996-01-01
1996-03-01
1997-05-01
1998-01-01
1998-03-01
1999-05-01
2000-01-01
2000-03-01
2001-05-01
2002-01-01
2002-03-01
2003-05-01
2004-01-01
2004-03-01
2005-05-01
2006-01-01
2006-03-01
2007-05-01
2008-01-01
2008-03-01
2009-05-01
2010-01-01
2010-03-01
2011-05-01
2012-01-01
2012-03-01
2013-05-01
2014-01-01
2014-03-01
2015-05-01
2016-01-01
2016-03-01
2017-05-01
2018-01-01
may buy tyres from another company for their cycles. When compared to other models,
the value per transaction in B2B transaction is high, because of bulk purchases. The
company also might get the advantage of discounts on bulk purchases. See Figure 15.7
G2B is a part of e-governance. The Government provides information about business rules,
requirement and permission needed for starting a new business, and other specifications
in its portal. The objective of G2B is to reduce burdens on business, provide one-stop
access to information thereby boost the economy. e.g. ebiz.gov.in See Figure 15.14
2. Auction site is a kind of website, that auctions items on the Internet and levies some
commission from the sales. e.g. https://www.ebay.com/
4. Bulk-buying sites collect a number of users together all of who want to buy similar
items; the site negotiates a discount with the supplier and takes a commission.
e.g. https://www.alibaba.com/
5. Digital publishing sites effectively host the e-books or magazines on the web. They make
profits in a number of ways such as advertising, selling etc., https://wordpress.org/
6. Licensing sites allow other websites to make use of their software. For example, the
search engines which allow a visitor of the site to search within the website more easily.
7. Name-your-price sites are just like normal retail sites. In contrast, the buyer negotiates
with the retailer for a particular product or service. https://in.hotels.com/
8. Online Shopping mall site allows multi E-Commerce traders to assemble together
on a single website. Often these sellers would be related to each other, for example
they may all sell luxury goods. This site would take a percentage of their profit.
E-Commerce
E-Commerce isn’t just commerce anymore. Even though they share the
primary principle of buying and selling goods and services, there is a
difference between traditional commerce and E-Commerce.
Disadvantages of anywhere at their convenience. They don’t
E-Commerce need a long wait to talk to a salesman.
They can read the details regarding
The pros and cons of E-Commerce affect
model numbers, prices, features etc. of
three major stakeholders: consumers
the product from the website and buy
business organisations, and society.
at their own convenience. Payments can
The following are the advantages also be made through online.
and disadvantages of E-Commerce for a
consumer. Disadvantages
●● E-Commerce is often used to buy
Advantages
goods that are not available locally but
●● E-Commerce system is operated on all from businesses all over the world.
days and all the day. It is able to conduct Physical goods need to be transported,
business 24 x 7. Neither consumer nor which takes time and costs money. In
suppliers need physical store to be traditional commerce, when we walk out
opened to do business electronically. of a shop with an item, it’s ours; we have
People can interact with businesses at it; we know what it is, where it is and
the time of their convenience. how it looks. But in E-Commerce we
●● Speed is a major advantage in should wait between placing the order
E-Commerce. Advanced Electronic and having the product in hand. Some
communications systems allow E-Commerce companies handle this by
messages to reach across the world engaging their customer updating status
instantaneously. There is no need to wait of their shipments.
days for a catalogue to arrive by post. ●● Unlike returning goods to a traditional
Communication delay is not a part of shop returning goods through online is
the Internet or E-Commerce world. believed to be an area of difficulty. The
●● The Internet is too easy to ‘shop around’ doubts about the period of returning,
for products and services that may be will the returned goods reach source
more cheaper and effective than left to in time, refunds, exchange and postage
buy only in a Brick and Mortar shop. make one tiresome.
It provides an opportunity to buy at ●● Privacy issues are serious in E-Commerce.
reduced costs. It is possible to, explore the In E-Commerce generating consumer
Internet, identify original manufacturers, information is inevitable. Not all the
thereby bypass wholesalers and achieve companies use the personal information
a cheaper price. they obtained to improve services to
●● The whole world becomes a shop for consumers. Many companies misuse
today’s customers. They can have wide the information and make money out of
choice by comparing and evaluating it. It is true that privacy concerns are a
the same product at different websites critical reason why people get cold feet
before making a purchase decision. about online shopping.
Augmented reality
AR is a 3-dimensional experience of and motivate shoppers to buy as they get
witnessing the virtual items by augmenting more enhanced buying experience.
the real objects with the virtual ones. Interior design and home decor sites
The AR technology allows customer see were some of the early adopters of this
themselves and visualize how they would technology, seeing the benefits of consumers
look like in a particular outfit. Customers interacting with products virtually. They
don’t have to wear it literally instead. allow consumers to virtually place furniture
Augmented reality (AR) and virtual reality in their home and envision what the end
(VR) keep changing customer experiences result will look like via their mobile phones.
CDs and softwares. It is not suitable for ●● Customer loyalty: Business cannot
dealing with the new or unexpected. survive long without loyal customers. The
Traditional commerce always takes customers would like to buy from a website
advantage when it is perishables and where they are able to get the best deal.
touch and feel products. They cannot be loyal to a particular seller.
●● Competition and Corporate In traditional commerce, shopkeeper
vulnerability: Access to Global Market would interact with the consumer “face-
is an beneficial on one hand but it to-face” and gain their loyalty too. In
also come with a competition. Open E-Commerce, the interaction between the
Internet has paved way to all business business and the consumer is “screen-to-
firms to operate in the global market. face”. The customers would feel that they
Many businesses have been already do not have received sufficient personal
facing international competition from attention. Since there is no personal touch
web-enabled business opponents. in E-Business, companies could not win
The competitors may access product over their loyalty easily.
details, catalogs, and other information ●● Shortage of skilled employees: Though
about a business through its website most of the process in E-Commerce
and makes it vulnerable. They might is automated, some sectors like
then indulge in web harvesting. Web packaging and delivery, needs manual
harvesting is the illegal activity of interventions. There could be problems
extracting business intelligence from related to shipping delays which would
competitor’s web pages. need technically qualified staff with
●● Security: Security remains to be a an aptitude to resolve. E-Commerce
problem for E-Commerce. Customers has difficulty in recruiting, training
might be reluctant to give their and retaining talented people. There is
credit card number to the website. a great shortage of skilled employees.
As lot of cyber frauds takes place in Traditional organizational structures
E-Commerce transactions, people and poor work cultures in some places
generally afraid to provide their inhibit the growth of E-Commerce.
personal information. Legal issues ●● Size and value of transactions: The
arise when the customer’s data falls delivery cost of a pen surpasses the
in the hands of strangers. Fraudulent cost of pen itself. E-Commerce is most
activities in traditional commerce is often conducted using credit card for
comparatively less as there is personal payments, and as a result very small
interaction between the buyer and the and very large transactions tend not to
seller. be conducted online.
The following are the initial steps involved in the process to start an online business
and start selling items instantly:
points to remember
Affiliate Business who promotes the products of another business for a commission.
Brick and mortar The term that refers to a business that has a physical store; opposite of
online store.
Mobile commerce Businesses that are conducted through the Internet using mobile phones
or other wireless hand-held devices.
EVALUATION
Objective Questions Commerce: 2010 – Present
1. A company can be called E-Business if d) Dotcom burst: 2000 – 2002
a) it has many branches across the 6. Assertion (A): The websites of first
world. wave dotcom companies were only in
English
b) it conduct business electronically
over the Internet. Reason (R): The dotcom companies
of first wave are mostly American
c) it sells commodities to a foreign
companies.
country.
a) Both (A) and (R) are correct and
d) it has many employees.
(R) is the correct explanation of (A)
2. Which of the following is not a tangible
b) Both (A) and (R) are correct, but (R)
good?
is not the correct explanation of (A)
a) Mobile
c) (A) is true and (R) is false
b) Mobile Apps
d) (A) is false and (R) is true
c) Medicine
7. Off-shoring means
d) Flower bouquet
a) Work outsourced to a branch of its
3. SME stands for
own company
a) Small and medium sized enterprises b) Work outsourced to new employees
b) Simple and medium enterprises c) Work outsourced to a third party
c) Sound messaging enterprises locally
d) Short messaging enterprises d) Work outsourced to a third party
4. The dotcom phenomenon deals with outside its own country
________ 8. G2G systems are classified into
a) Textile industries a) Internal facing and external facing
b) Mobile phone companies b) Internet facing and Extranet facing
c) Internet based companies c) Internal flag and external flag
d) All the above d) Internet flag and Extranet flag
5. Which of the following is not correctly 9. ____ host the e-books on their
matched websites.
a) The First Wave of Electronic a) Bulk-buying sites
Commerce: 1985 -1990 b) Community sites
b) The Second Wave of Electronic c) Digital publishing sites
Commerce: 2004 – 2009
d) Licensing sites
Chapter 15 E-COMMERCE 231
www.tntextbooks.org
Part - II
Short Answers
1. Define E-Commerce.
2. Distinguish between E-Business and E-Commerce
3. Differentiate tangible goods and electronic goods with example of your own.
4. What is dotcom bubble and dotcom burst?
5. Write a short note on out-sourcing.
Part - III
Explain in Brief Answer
1. Describe how E-Commerce is related to socio-technological changes.
2. Write a short note on the third wave of E-Commerce.
3. Explain B2B module in E-Commerce.
4. Write a note on name-your-price websites.
5. Write a note on physical product dispute of E-Commerce.
Part - IV
Explain in detail
1. Write about the development and growth of Electronic Commerce.
2. List all the E-Commerce business models and explain any four briefly.
3. Explain any five E-Commerce revenue models.
4. How would you differentiate a traditional commerce and E-Commerce?
5. What are the advantages and disadvantages of E-Commerce to a consumer?
student activities
16
CHAPTER
LEARNING OBJECTIVES
●● To understand what is Electronic payment systems
●● To know the various types of E-payment methods
●● To learn the basics of
❍ Card Based Payment Systems
❍
❍ Electronic Account Transfer
❍
❍ Electronic Cash Payment Systems
❍
❍ Mobile Payment and Internet Payment Systems
❍
16.1 Introduction to As the volume and variety of
Electronic Payment transactions expands the volume of money
systems expand. Using cash for each of large
transactions is neither feasible nor practically
Everyday people buy or sell goods and
possible. Security and transportation
services for money. Money becomes the
problems arise in cases where large amounts
major medium of exchange. Later some
of cash transactions are involved.
payment systems were developed out of a
need to facilitate the growth of commerce Banks would support in such cases
and economic development. by offering other payment methods. The
cashless society has been discussed for long
The media used for transferring
time. The demise of cash and cheques could
the value of money is very diversified,
not be sudden. Though old habits hardly die,
ranging from the use of simple payment
people do not hesitate adapting new things.
instruments (e.g. cash) to the use of
complex systems (e.g. cryptocurrency).
Physical money (cash), is the traditional Definition
and most widely used payment instrument An Electronic payment system is a
that consumers use, in their daily lives to financial arrangement that consists an
buy goods and services. intermediator to facilitate transfer of
money-substitute between a payer and
233 233
www.tntextbooks.org
payment systems
Step 2: Customer pays the micro payments
to the online service provider
16.3 Card Based Payments
and gets the requested goods or
Systems
services form them.
Step 3: Service provider deposits micro Payment cards are plastic cards that
payments received from the enable cashless payments. They are simple
customer to the payment processor embossed plastic card that authenticates
and gets the money. the card holder on behalf of card issuing
company, which allows the user to make
The micro electronic payments systems
use of various financial services. More
work on the basis of simple cryptographic
than 90% of online payments are card
algorithms. Based on the algorithm used,
based payments, at the same time other
it is classified into the following categories.
e-payment methods are also gaining
●● Hash chain based micro electronic importance now-a-days.
payment systems.
Based on the transaction settlement
●● Hash collisions and hash sequences
method there are three widely used card
based micro electronic payment systems.
based payment systems. They are
●● Shared secrete keys based micro
1. Credit card based payment systems
electronic payment systems.
(pay later)
●● Probability based micro electronic
2. Debit card based payment systems
payment systems.
(pay now)
16.2.2 Macro electronic payment 3. Stored value card based payment
systems systems (pay before)
Macro electronic payment systems
support payments of higher value. The 16.3.1 Credit Card
security requirements are more rigorous Credit card is an electronic payment system
in macro payment systems because of huge normally used for retail transactions.
money transactions. Banks will impose a A credit card enables the bearer to buy
minimum transaction overhead on macro goods or services from a vendor, based
payment systems. These transactional over on the cardholder’s promise to the card
heads for the usage of computationally issuer to payback the value later with an
expensive cryptographic operations agreed interest. Every credit card account
5. Issuer: Bearer’s bank, that issue the 1. Publisher: Emblem of the issuing
credit card, set limit of purchases, bank (along with the sub category or
decides the approval of transactions, scheme if any)
issue invoices for payment, charges 2. Credit card number: The modern
the holders in case of default and credit card number has 16-digit
offer card-linked products such unique identification number.
as insurance, additional cards and ●● The first digit of the credit
rewards plan. See Figure 16.2 card number is Major Industry
Anatomy of a credit card Identifier (MII). It identifies the
All Payment cards (including debit issuer category. e.g. 1 – Airlines,
card) are usually plastic cards of size 4 – Banks
85.60 mm width × 53.98 mm height, ●● The next 5 digits uniquely identifies
rounded corners with a radius of the issuing organization.
2.88 mm to 3.48 mm and thickness of ●● The first 6 digits together called
0.76 mm. These standards dimensions are as Issuer Identifier number (IIN)
maintained universally in accordance with or Bank Identification number
ISO/IEC 7810#ID-1. See Figure 16.3 (BIN)
8
1 Bank Name
11
5
10
4 9
2 6
3 LOGO 7
●● The next 9 digits are the account 10. Signature: It is cardholder’s signature
number. at the back of the card, used as an
●● The last digit is a check digit attempt to identify cardholder’s
(based to the Luhn algorithm). identity. It also holds the last 4 digits
3. Name of the cardholder: It is of card number.
visibly embossed on the front side 11. CVC/CVV: Card Verification code/
value is a 3 digit code usually printed
(additionally stored on the magnetic
to the left of signature pane validates
stripe) some cards like gift cards do
the card. CVC2 is used in contact
not hold any name.
less transactions.
4. EMV chip: It is integrated chip in Apart from the these mentioned
addition to magnetic stripe to store each credit card may also holds issuer’s
cardholder’s information. EMV disclaimer, address and phone number.
stands for Europay, MasterCard, Visa.
These three names correspond to the 16.3.2 Debit Card
names of the companies which are
Debit Card is an electronic payment card
responsible to develop this technology.
where the transaction amount is deducted
It is categorized into Chip-and-
directly from the card holder’s bank account
Signature and Chip-and-PIN.
upon authorization. Generally, debit
5. RFID symbol: It is four curved lines cards function as ATM cards and act as a
radiating rightwards similar to a substitute for cash The way of using debit
tilted Wi-Fi symbol. It indicates that cards and credit cards is generally the same
it is a contactless smartcard. but unlike credit cards, payments using a
6. Expiration month and year: It is debit card are immediately transferred from
visible on the front side (also stored the cardholder’s designated bank account,
on the magnetic stripe or chip). The instead of them paying the money back at a
card is valid until the last day of the later with added interest. In modern era the
month printed on it. use of debit cards has become so widespread.
7. Card brand logo: It is the name of
The debit card and credit card are
the credit card network company.
identical in their physical properties. It
Visa and MasterCard are leading
is difficult to differentiate two by their
credit card network companies.
appearance unless they have the term
Rupay is Indian domestic open loop
credit or debit imprinted.
card launched in 2012.
8. Magnetic stripe: It is an iron based Currently there are three ways of
magnetic material containing processing debit card transactions:
encrypted data about the card holder 1. EFTPOS (also known as online debit
and account number. or PIN debit)
9. Hologram: Hologram is a security 2. Offline debit (also known as
feature that prevents duplication. It signature debit)
is a 3-dimentional image formed by 3. Electronic Purse Card System
interference of light beams.
processing. Smart cards can be classified Transfer
into Contact smart cards and Contactless
Apart from card based payment systems
smart cards. See Figure 16.5
there are many alternative electronic
1. Contact smart cards payment systems. With the advent of
Contact smart cards have a contact computers, network technologies and
area of approximately 1 square electronic communications a large
centimeter, comprising several gold- number of alternative electronic payment
plated contact pads. These pads systems have emerged. These include
provide electrical connectivity only ECS (Electronic Clearing Services), EFT
when inserted into a reader, which (Electronic funds transfers), Real Time
is also used as a communications Gross Settlement system (RTGS) etc.
medium between the smart card These Electronic Payment systems are
and a host. e.g. a point of sale used in lieu of tendering cash in domestic
terminal(POS). and international transactions.
Advantages of this system are bulk a single account is credited. This type
payments, guaranteed payments and of transactions are Pull transactions.
no need to remember payment dates. It Example: The insurance premium of
can be used by institutions for making bulk number of customers is debited
payments such as disbursing of salary, from customer’s bank account on their
pension or dividend interest among
shareholders. Similarly, individual bank
EFT is known by a number of
customers also can make small value
names across countries. In India,
repetitive payments such as paying EMI
it is called as N-EFT (National
of a loan, electricity bills, telephone Electronic Fund Transfer), in the
bills, insurance premium, as well as SIP United States, they may be referred to
investments. See Figure 16.7 as “electronic cheques” or “e-cheques”.
National Electronic Funds Transfer
ECS can be used for both credit
(NEFT) is an electronic funds transfer
and debit purposes i.e. for making bulk system initiated by the Reserve Bank
payments or bulk collection of amounts. of India (RBI) in November 2005. It is
●● ECS credit: ECS credit is used for making established and maintained by Institute
bulk payment of amounts. In this mode, for Development and Research in
Banking Technology (IDRBT). NEFT
a single account is debited and multiple
enables a bank customer to transfer funds
accounts are credited. This type of between any two NEFT-enabled bank
transactions are Push transactions. accounts on a one-to-one basis. It is done
Example: if a company has to pay salary via electronic messages. Unlike RTGS,
to its 100 employees it can use ECS credit fund transfers through the NEFT do not
system than crediting every employees’ occur in real-time basis.
account separately.
●● ECS debit: ECS debit is an inverse
of ECS credit. It is used for bulk
collection of amounts. In this mode,
multiple accounts are debited and then
prior consent and paid to insurance fulfills his obligations to the buyer or
company. whether he would deliver the goods
or perform a service of a quality
16.4.2 Electronic Funds Transfer consistent with the order.
Electronic Funds Transfer (EFT) is the ●● Irrevocable - a correctly processed
“electronic transfer” of money over an transaction cannot be reversed and
online network. The amount sent from its money cannot get refunded (the
the sender’s bank branch is credited to the so-called settlement finality).
receiver’s bank branch on the same day
in batches. Unlike traditional processes, 16.5 Electronic Cash
EFT saves the effort of sending a demand Payment Systems
draft through post and the inherent delay
Electronic cash is (E-Cash) is a currency
in reaching the money to the receiver.
that flows in the form of data. It converts
Banks may charge commission for using
the cash value into a series of encrypted
this service. EFT is a widely used method
sequence numbers, and uses these serial
for moving funds from one account to
numbers to represent the market value of
another in B2B business models.
various currencies in reality.
16.4.3 Real Time Gross 16.5.1 Cryptocurrency
Settlement: People have always valued unique and
Real Time Gross Settlement system irreplaceable things. A unique thing always
(RTGS) is a payment system particularly has a demand and acclaims a price. A
used for the settlement of transactions cryptocurrency is a unique virtual (digital)
between financial institutions, especially asset designed to work as a medium of
banks. As name indicates, RTGS exchange using cryptographic algorithm.
transactions are processed at the real- This algorithm secures the transactions
time. RTGS payments are also called by recording it in blockchain and controls
as push payments that are initiated the creation of additional units of the
(“triggered”) by the payer. RTGS payments currency. Cryptocurrency is also called as
are generally large-value payments, i.e. cryptocoins, e-cash, alternative currencies
high-volume transactions. or virtual currencies and are classified as a
subset of digital currencies.
he development and maintenance
T
Cryptocurrency can be defined as
of NEFT or RTGS systems
distributed accounting system based on
worldwide is driven primarily by
the central bank of a country. (RBI cryptography, storing information about
in India) the state of ownership in conventional units.
The state of ownership of a cryptocurrency
Real-time gross settlement transactions is related to individual system blocks
are: called “portfolios”. Only the holder of the
corresponding private key would have
●● Unconditional - the beneficiary will
control over a given portfolio and it is
receive funds regardless of whether he
impossible to issue the same unit twice.
242 Chapter 16 Electronic Payment Systems
www.tntextbooks.org
Buyer Seller
Block Crypto-Hashing Distributed databases
(transaction)
●● WAP technology.
Some of the latest mobile banking
applications even have a cash ●● Using smartphone applications.
withdrawal menu. The menu will
create a specific code that can be used 16.6.2 Internet banking
instead of an ATM card to operate an Internet banking is a collective term
ATM. However, this can only be done at a for E-banking, online banking, virtual
special ATM (ATM with no card service). banking (operates only on the Internet
with no physical branches), direct banks,
The WAP protocol installed on a web banking and remote banking.
mobile phone qualifies the device through
Internet banking allows customers
an appropriate application for mobile
of a financial institution to conduct various
session establishment with the bank’s
financial transactions on a secure website
website. In this way, the user has the option
operated by the banking institutions.
of permanent control over the account and
This is a very fast and convenient way of
remote management of his own finances.
performing any banking transactions. It
Mobile Banking operations can be enables customers of a bank to conduct
implemented in the following ways: a wide range of financial transactions
●● contacting the call center. through its website. In fact, it is like
●● automatic IVR telephone service. a branch exclusively operating of an
individual customer. The online banking
●● using a mobile phone via SMS.
system will typically connect to the core
banking system operated by customers Step 1: Login to net banking account using
themselves (Self-service banking). unique user name and password
provided by the bank earlier.
Advantages:
Step 2: Add the beneficiary as a payee
The advantages of Internet banking
●●
to enable transfer of fund. The
are that the payments are made at the
following details like Account
convenience of the account holder and
Number, Name, IFSC about the
are secured by user name and password.
beneficiary are to be filled in the
i.e. with Internet access it can be used
‘Add New Payee’ section.
from anywhere in the world and at any
Step 3: Once the beneficiary is added,
time.
choose RTGS / NEFT / IMPS as
●● Any standard browser (e.g. Google
mode of Fund Transfer.
Chrome) is adequate. Internet banking
Step 4: Select the account to transfer money
does not need installing any additional
from, select the payee, enter the
software.
amount to be transfered and add
●● ApartOutfrom regular
of 7.7 billion worldtransactions,
population remarks (optional).
Internet banking portal
roughly 3.2 billion have provides
the
Internet access. There by more Step 5: Click on submit.
complete control over all banking
than 50%
demands suchof as
world population
available are
balance, Step 6: Enter the OTP received to
accessed to Internet
transaction banking. recent
statements, mobile number linked to the
transactions, bill payment, blocking a corresponding account to
card in case of theft or loss, information complete the transaction.
about other bank products like Modern Electronic funds transfers are
payment cards, deposits, loans etc. secured by a personal identification number
(PIN), one-time password (OTP) etc. An
automated clearing house (ACH) processes
The following are the steps to transfer
the payment then. See Figure 16.12
fund using net banking.
Advantages
Bharat Interface for Money
●● Immediate money transfers through
(BHIM)
mobile device round the clock 24 x 7.
●● Can use single mobile application for Individual banks and financial
accessing multiple bank accounts. institutions build and maintain their
own mobile application for UPI
●● Single Click Authentication for
transaction. Bharat Interface for
transferring of fund.
Money (BHIM) is an exclusive mobile
●● It is not required to enter the details
app for UPI developed by National
such as Card no, Account number,
Payments Corporation of India (NPCI)
IFSC etc. for every transaction.
and launched on 30 December 2016.
●● Electronic payments will become It is intended to facilitate e-payments
much easier without requiring a digital directly through banks and drive
wallet or credit or debit card. towards cashless transactions.
16.8 Cash on delivery
Cash on delivery (COD) also called as
collection on delivery, describes a mode
of payment in which the payment is made
only on receipt of goods rather in advance.
Originally, the term applies only to cash
payment, but since other forms of payment
have become more common, the word
“cash” has sometimes been replaced by the
word “collect” to transactions with checks,
credit cards or debit cards.
COD is often used as an additional
payment option in E-Commerce. It offers
the recipient the advantage of paying only
when commodity is handed over that is
likely similar to traditional system. If the
goods are not paid, they are returned to
the retailer.
points to remember
●● Payments are the financial instruments used globally to transfer value in the form of money or
its substitutes and are constantly changing due to new technology and Government regulations.
●● Payment system can also be divided into two types, namely the cash payment system and the
non-cash payment system based on the instruments used. In the cash payment system, the
instruments used are in the form of currency (paper money and coins) while in the non-cash
payment system the instruments used are card-based payment, Cheques or electronic money.
●● A Credit card plays a major role in electronic payment system worldwide.
●● ECS is treated as a electronic cheques by the bank. The advantages and disadvantages of the
physical cheque is also extended to ECS. In electronic clearing services, bank process the
instructions from the customer to debit his account and pay another automatically without
much human interference.
●● (POS) Point of Sale Terminal- It enables customers to make payment for purchase of goods
and services by means of credit and debit cards. To facilitate customer convenience some
banks also cash withdrawal using debit cards at POS terminals.
BIN Bank Identification Number. The first six-digits of credit card number to
uniquely identify financial institutions.
Brick and mortar The term that refers to a business that has a physical store; opposite of online
store.
(CVC2/CVV2) Card Verification Code and Card Verification Value : A three digit code
printed on the cardholder signature panel allows e-payments when the card
is not physically accessible.
Credit card Company responsible for communicating the transaction between the
network / acquirer and the credit card issuer. E.g. MasterCard, Visa, Rupay
processor
Double spend A type of fraud where same cryptocurrency is spent in more than one
transactions.
E-wallets Electronic purses allow users to make electronic transactions quickly and
securely
Gift cards A magnetic stripe or chip card that holds the value of money to offer as a gift
by a E-business
Internet banking Is the activity of buying or selling of commodities through online services or
over the Internet
PIN Personal Identification Number. A static number that is assigned to
consumers to secure card based payments.
Point of sale Merchant’s electronic device that enables the e-payments. It reads the card
(POS) information from EMV or magnetic strip
EVALUATION
number
2. Compare and contrast the credit
A2) 9th to 15th Digit B2) MII Code card and debit card.
A3) First 6 Digits B3) BIN Code 3. Explain briefly Anatomy of a credit
A4) Last Digit B4) Check digit card.
4. Briefly explain the stored value card
A1 A2 A3 A4 and its types.
a) B4 B3 B2 B1 5. Write a note on mining in
b) B2 B1 B3 B4 cryptocurrency.
c) B2 B3 B4 B1
Part - IV
d) B2 B4 B3 B1
Explain in detail
1. What is credit card? Explain the
Part - II
key players of a credit card payment
Short Answers
system and bring out the merits of it.
1. Define electronic payment system
2. Briefly explain Electronic Account
2. Distinguish micro electronic payment transfer and its types.
and macro electronic payment 3. Write a note on
3. List the types of micro electronic a. Internet banking
payments based on its algorithm b. Mobile banking
4. What is cryptocurrency? Explain the
4. Explain the concept of e-wallet
same.
5. What is a fork in cryptocurrency? 5. Explain in detail : Unified payments
interface
student activities
17
CHAPTER
LEARNING OBJECTIVES
●● To know basics of E-Commerce Security Systems
●● To understand various types of E-Commerce threats
●● To learn about dimensions of E-Commerce security
●● To know about security technologies in E-Commerce transaction
253
www.tntextbooks.org
17.3 Dimensions of
E-Commerce security
As the security issue is the most worrying
issue for E-Business, ensuring the security
in E-Commerce The Data Encryption Standard (DES) is a
transaction Symmetric key data encryption method.
It was introduced in America in the year
Since a large amount of confidential
1976, by Federal Information Processing
information are involved in E-Commerce
Standard (FIPS).
activities it must be transmitted
through the safe and secured network. DES is the typical block
Sophisticated security technologies algorithm that takes a string of bits of
are required to ensure the security of cleartext (plaintext) with a fixed length
E-Commerce transactions. At present, and, through a series of complicated
the security technologies in E-Commerce operations, transforms it into another
transactions are roughly classified into encrypted text of the same length.
DES also uses a key to customize the
●● Encryption technology
transformation, so that, in theory, the
●● Authentication technology algorithm can only be deciphered by
●● Authentication protocols people who know the exact key that
has been used for encryption. The DES
17.4.1 Encryption technology key is apparently 64 bits, but in fact the
Encryption technology is an effective algorithm uses only 56. The other eight
information security protection. It is bits are only used to verify the parity
defined as converting a Plaintext into and then it is discarded.
meaningless Ciphertext using encryption
Today, it is considered that DES
algorithm thus ensuring the confidentiality
is not safe for many applications, mainly
of the data. The encryption or decryption
because of its relatively smaller key size
process use a key to encrypt or decrypt
(56-bit). But the key length can be easily
the data. At present, two encryption
increased by multiple use of the DES,
technologies are widely used. They are
described as Triple-DES, also known as
symmetric key encryption system and an
TDES, 3DES or DESede.
asymmetric key encryption system.
SSN: SSN:
783-43-1616 Bc9Yzwoga
Encryption + XBzdWogZG
9sb3lgc2I0IG
FtZXQNCg...
SSN: SSN:
Bc9Yzwoga 783-43-1616
Decryption
XBzdWogZG
9sb3lgc2I0IG
+
FtZXQNCg...
Asymmetric or Public key encryption consists of a private key and a public key. A
Asymmetric encryption also called as public-key encryption method is a method
RSA (Rivest-Shamir-Adleman) algorithm. for converting a plaintext with a public key
It uses public-key authentication and into a ciphertext from which the plaintext
digital signatures. Until 1970s, there were can be retrieved with a private key.
only symmetric cryptosystems in which
transmitter and receiver must have the 17.4.2 Authentication
same key. This raises the problem of key Technology
exchange and key management. Unlike a The main role of security certification is
symmetric encryption, the communicating to ensure Authentication, Integrity and
parties need not know other’s private- Non-repudiation. This can be achieved
key in asymmetric encryption. Each through digital signatures and digital
user generates their own key pair, which certificates.
Plain text and cipher text are of same size The size of cipher text is always greater than
plain text.
Algorithms like DES, AES, RC4 uses Algorithms like RSA, ECC, DSA use
symmetric key encryption asymmetric key encryption
The number of key used grows The number of key used grows linearly with
exponentially with the number of users the number of users
I n 1976, Whitfield Diffie and Martin e. Hellman, devised an algorithm called public key
encryption. The algorithm can be understood using color game. This how could “A” and
“B” get a secret key without letting “C” finding it out. The trick is based on 2 facts
●● It is easy to mix 2 colors together to get 3rd color
●● Given a mixed color it’s hard to reverse it A C B
Agreed colour
in order to find the exact original colors
Secret colour
+ +
Secret colour
1. First A and B agree publicly on a starting
color (yellow)
2. Now A select a random colour (red)
mix it with yellow and send new color
(yellow+red=orange) to B.
Secret colour
+ +
Secret colour
3. Similarly B selects a random colour
(blue) mix it with yellow and send new
colour (yellow+blue=green) to A.
4. Hacker “C” may have two new colours
(orange) and (green) but not the A’s (red) or B’s (blue) private colours.
5. After interchanging colors, A adds his own private (red) to B’s mixture (green) and
arrive at a third secret colour(black).
6. Also B adds his own private (blue) to A’s mixture (orange) and arrive at a same third
secret color (black).
7. C is unable to have the exact color (black), since C needs one of the private color to do so.
Digital signatures are used to verify the Digital certificates are used to verify the
trustworthiness of the data being sent trustworthiness of the sender.
Digital signature is to ensure that a data remain Digital certificate binds a digital signature to an
secure from the point it was issuedand it was not entity
modified by a third party.
It provides authentication, non-repudiation and It provides authentication and security.
integrity
A digital signature is created using a Digital A digital certificate works on the principles of public
Signature Standard (DSS). It uses a SHA-1 or key cryptography standards (PKCS). It creates
SHA-2 algorithm for encrypting and decrypting the certificate in the X.509 or PGP format.
message.
The document is encrypted at the sending end and A digital certificate consist of certificate's owner
decrypted at the receiving end using asymmetric name and public key, expiration date, a Certificate
keys. Authority 's name , a Certificate Authority's digital
signature
information originated from the signer via the Internet. SET was developed in
and has not been altered by a cracker in 1996 by VISA and MasterCard, with the
the middle. Digital signatures can provide participation of GTE, IBM, Microsoft and
the added assurances of evidence to the Netscape.
origin, identity and status, as well as The implementation of SET is
acknowledging the consent of the sender. based on the use of digital signatures and
Digital signatures use a standard, the encryption of transmitted data with
worldwide accepted format, called Public asymmetric and symmetric encryption
Key Infrastructure (PKI), to provide the algorithms. SET also use dual signatures
highest levels of security and universal to ensure the privacy.
acceptance. In many countries, digital The SET purchase involves three
signatures have the same legal significance as major participants: the customer, the
the traditional forms of signed documents. seller and the payment gateway. Here the
Digital signatures are widely used for customer shares the order information
avoiding forging or tampering of important with the seller but not with the payment
documents such as financial documents or gateway. Also the customer shares the
credit card data. payment information only with the
payment gateway but not with the seller.
A security token is a hardware So, with the SET, the credit card number
component that are used to may not be known to the seller and will
identify and authenticate users. not be stored in seller’s files also could not
be recovered by a hacker.
The SET protocol guarantees the
security of online shopping using credit
cards on the open network. It has the
advantages of ensuring the integrity of
transaction data and the non-repudiation
of transactions. Therefore, it has become
the internationally recognized standard
for credit card online transaction.
17.4.3 Authentication protocols SET system incorporates the
At present, there are two kinds of security following key features:
authentication protocols widely used in ●● Using public key encryption and
E-Commerce, namely Secure Electronic private key encryption ensure data
Transaction (SET) and Secure Sockets confidentiality.
Layer (SSL).
●● Use information digest technology to
Secure Electronic Transaction ensure the integrity of information.
Secure Electronic Transaction (SET) ●● Dual signature technology to ensure
is a security protocol for electronic the identity of both parties in the
payments with credit cards, in particular transaction.
260 Chapter 17 E-Commerce Security Systems
www.tntextbooks.org
The operating principle of SSL using public key encryption could be easily understood
with the following scenario “kumar orders a mobile phone from an online store (abc.
com).”
1. Kumar connects to abc.com website through a secure connection, from his
computer browser.
2. The abc.com website sends Kumar an digital certificate and a public key (P).
This digital certificate issued by a certification authority (CA) proves the
identity of abc.com.
3. Kumar’s browser checks the certificate. It (browser) then agrees with the remote
server on a symmetric cryptographic system to use. Then it randomly choose
a key for this algorithm (session key K).
4. Kumar’s browser sends P (K) to abc.com. Using its secret key S, the abc.com
server calculates S (P (K)) = K. Thus, Kumar’s browser and abc.com server are
in possession of the same key.
5. Kumar enters his credit card number and other data. They constitute the
“information”. The browser sends these “information” to abc.com, encrypted
using the key K. It also sends a summary of this “information”, using a
mathematical function called hash function.
6. With the K key, the abc.com server can dencrypt the “information”. It also
calculates the summary of information, and compares with the summary sent
by Kumar’s browser. If they coincide, it is assumed that the data has been
correctly transmitted.
points to remember
●● Phishing: Phishing is acquiring critical data like login credentials through telephone,
sms, e-mail or any social media by the crackers disguising as authentic.
●● Authentication: Information of the entity sending the document is often included
in the document, but the information may be inaccurate. A digital signature can be
used to authenticate the source of a document.
●● Integrity: In many scenarios, the sender and receiver of the document will require
confidence that the document has not been tampered with during the transfer. If the
document was digitally signed, any modification of the document will invalidate
the signature.
●● Non-repudiation: Repudiation refers to any act of relinquishing responsibility
for a message. Non-repudiation ensures that the signer who digitally signed the
document cannot deny having signed it. The digitally signed documents strengthen
its recipient integrity claims. Therefore, the recipient can strongly insist on the
signature of the sender so as not to be easily denied at a later time.
●● The difference between a digital signature and digital certificate is that a digital
certificate binds a digital signature to an entity; whereas a digital signature ensures
that a data remain secure from the point it was sent. In other words: digital
certificates are used to verify the trustworthiness of the sender, while digital
signatures are used to verify the trustworthiness of the data being sent.
●● The certificate authority maintains a database of public keys called repository so
that it can verify the user with digital signatures. Expired certificates are usually
deleted from the database by the certificate authority.
●● Brute-force attacks is the simplest attack method for breaking any encryption; that
is, trying all the possible keys one by one.
3-D Secure An additional security layer for online credit and debit card transactions.
Ciphertext It is the encrypted data usually the output of an encryption algorithm
Cracker A person who breaks computer network’s security maliciously to gain
access to critical data.
Cryptanalysis Analyzing a suspecting document for hidden data or chiphertext
Cyber Squatting Is the illegal practice of registering an Internet domain name that might
be wanted by another person in an intention to sell it later for a profit
Decipher A standard algorithm for decrypting data
Domain name The website address of an online store, e.g.www.amazon.com
Encryption A method of scrambling data using an algorithm to protect / hide from
unauthorized access.
Friendly Fraud Is an intentional falsely claim of a costumer that they really didn’t
buy(after receiving the goods)
Hacking Unauthorized intrusion into a computer or a network. That is to say
breaking security to gain access to a website illegally and intercept
confidential information
Message digest (MD) Is a representation of data in a form of single string of digits using one-
way hashing formula.
One-Time Password A dynamic password that is valid for one login session or transaction
(OTP) provides a potential security for a e-payment transaction.
PIN (Personal A static number that is assigned to consumers to secure card based
Identification payments.
Number)
Plaintext/ cleartext It is the unencrypted information also called as input chip
Traffic An indicator that marks the number of visitors for a particular site.
EVALUATION
2. Which of the following is not (SET)
a security element involved in b) Credit Card Verification
E-Commerce? c) Symmetric Key Encryption
a) Authenticity d) Public Key Encryption
b) Confidentiality
7. Secure Electronic Transaction (SET)
c) Fishing was developed in
d) Privacy a) 1999
3. Asymmetric encryption is also b) 1996
called as c) 1969
a) Secure Electronic Transaction
d) 1997
b) Certification Authority
8. The websites secured by Secure
c) RSA algorithm Socket Layer protocols can be
d) Payment Information identified using
4. The security authentication a) html://
technology does not include b) http://
i) Digital Signatures c) htmls://
ii) Digital Time Stamps d) https://
iii) Digital Technology 9. 3-D Secure, a protocol was developed
iv) Digital Certificates by
a) i, ii & iv b) ii & iii a) Visa
b) Master
c) i, ii & iii d) all the above
c) Rupay
d) PayTM
Part - III
Explain in Brief Answer
1. Write a note on certification authorities (CA)
2. List some E-Commerce Security Threats?
3. Differentiate asymmetric and symmetric algorithms.
4. Write a note on PGP.
5. Explain 3D secure payment protocols
Part - IV
Explain in detail
1. Write about dimensions of E-Commerce Security.
2. Explain encryption technology.
3. Differenticate digital signatures and digital certificates.
4. Define Secure Electronic Transaction (SET) and its features.
5. Briefly explain SSL.
student activity
18
CHAPTER
LEARNING OBJECTIVES
●● To acquire basic knowledge on EDI ●● To learn the advantages of EDI
●● To know the brief history of EDI ●● To know about the layers of EDI
●● To understand the various types of ●● To study about UN/EDIFACT
EDI
history of ED
I
With the popularity of computers, many companies and organizations use computers to store
and process data. However, different organizations use different application systems, and
the format of the data generated is not the same. When organizations need to communicate
for their business needs they have to rekey. This was time consuming and a major obstacle
in the business operations. In order to solve this problem, some enterprises have agreed a
specific standard format, which can be regarded as the origin of the EDI application concept.
Direct EDI/Point-to-Point
The first EDI messages was sent in
1965 from the Holland-American It is also called as Point-to-Point EDI. It
steamship line to Trans-Atlantic establishes a direct connection between
shipping company using telex messages. various business stakeholders and
The computer had sent a full page of partners individually. This type of EDI
information in roughly 2 minutes. These suits to larger businesses with a lot of day
messages were then written on the magnetic
to day business transactions.
tapes that could be loaded onto another
computer. EDI via VAN
EDI via VAN (Value Added Network) is
18.2 EDI Types where EDI documents are transferred
with the support of third party network
The types of EDI were constructed based
service providers. Many businesses prefer
on how EDI communication connections
this network model to protect them from
and the conversion were organized. Thus
the updating ongoing complexities of
based on the medium used for transmitting
network technologies. See Figure 18.2
EDI documents the following are the
major EDI types. A value-added network is a
company, that is based on its own
●● Direct EDI
network, offering EDI services to
●● EDI via VAN other businesses. A value-added network
●● EDI via FTP/VPN, SFTP, FTPS acts as an intermediary between trading
partners. The principle operations of value-
●● Web EDI added networks are the allocation of access
●● Mobile EDI rights and providing high data security.
EDI message standards are the United The versions of EDIFACT are also called
Nations EDIFACT and the ANSI X12. as directories. These EDIFACT directories
will be revised twice a year; on 1st April of segments, which in turn consist of
and 1st October to include new or update composites. The final iteration is a data
existing EDIFACT messages. EDIFACT element. See Figure 18.5 and 18.6
directories have names like D.18B
Segment Tables
(D stands for Directory, 18 is the
year and A/B indicates the month of Segment table lists the message tags. It
release) contains the tags, tag names, requirements
designator and repetitation field. The
EDIFACT subsets requirement designator may be mandatory
Due to the complexity, branch-specific (M) or conditional (C). The (M) denotes
subsets of EDIFACT have developed. that the segment must appear atleast
These subsets of EDIFACT include only once. The (C) denotes that the segment
the functions relevant to specific user may be used if needed. e.g. C10 indicates
groups. repetitions of a segment or group between
0 and 10.
Example:
CEFIC - Chemical industry
EDIFURN - furniture industry
EDIGAS - gas business
EDIFACT Structure
EDIFACT is a hierarchical structure
where the top level is referred to as an
interchange, and lower levels contain
multiple messages. The messages consist
Highest Level
Composite
Group of related simple elements
Elements
Simple data
Piece of single data
Elements
Lowest Level
EDI Interchange
Interchange is also called as envelope. An excerpt from an EDIFACT message
The top level of EDIFACT structure is might be:
Interchange. An interchange may contain
DTM + 11: 200 606 200 730: 203’
multiple messages. It starts with UNB and
ends with UNZ This whole line is called a segment. The
meaning of each code is as follows:
EDIFACT message
●● DTM is the segment identifier and
The basic standardization concept of
it indicates that the following data is
EDIFACT is that there are uniform message date / time information.
types called United Nations Standard
Message (UNSM). In so-called subsets, ●● 11 is a data element. In this example,
a qualifier describes what kind of
the message types can be specified deeper
event is meant. The code 11 means:
in their characteristics depending on the time of dispatch / delivery of goods.
sector. The message types, all of which always
have exactly one nickname consisting of six ●● 200606200730 is another element.
Here it represents the date in the
uppercase English alphabets. The message
format CCYYMMDDHHMM.
begins with UNH and ends with UNT
●● 203 is also an element. 203 is an
●● Service messages identifier for the date format.
To confirm / reject a message, CONTRL
and APERAK messages are sent. In this example, 203 means that the date
❍ CONTRL- Syntax Check and is in the format CCYYMMDDHHMM
(as of D.18B, CC – century, YY – Year,
❍
Confirmation of Arrival of Message
MM- Month, DD – Date, HH – Hour,
❍ APERAK - Technical error
MM – Minute)
❍
messages and acknowledgment
●● Data exchange
EDI Separators
❍ CREMUL - multiple credit advice
❍
❍ DELFOR- Delivery forecast EDIFACT has the following punctuation
marks that are used as standard separators.
❍
❍ IFTMBC - Booking confirmation
❍
EDIFACT Segment Character Uses
It is the subset of message. A segment is a
Apostrophe ’ segment terminator
three-character alphanumeric code. These
segments are listed in segment tables. Plus sign + segment tag and data
Segments may contain one, or several element separator
related user data elements.
Colon : component data
EDIFACT Elements element separator
The elements are the piece of actual data.
Question mark ? release character
These data elements may be either simple
or composite. Period . decimal point
Example:
UNA:+.? ‘
UNB+IATB:1+6XPPC:ZZ+LHPPC:ZZ+940101:0950+1’
UNH+1+PAORES:93:1:IA’
MSG+1:45’
IFT+3+XYZCOMPANY AVAILABILITY’
ERC+A7V:1:AMD’
IFT+3+NO MORE FLIGHTS’
ODI’
TVL+240493:1000::1220+FRA+JFK+DL+400+C’
PDI++C:3+Y::3+F::1’
APD+74C:0:::6++++++6X’
TVL+240493:1740::2030+JFK+MIA+DL+081+C’
PDI++C:4’
APD+EM2:0:1630::6+++++++DA’
UNT+13+1’
UNZ+1+1’
points to r m mb r
e
e
e
●● According to the National Institute of ●● In 1985, UN created the EDIFACT
Standards and Technology, EDI is “the to assist with the global reach of
computer-to-computer interchange technology in E-Commerce.
of strictly formatted messages that ●● Direct EDI is also called as Point-to-
represent documents other than Point EDI
monetary instruments.” ●● Every EDI message consist of six
●● EDI is “Paperless Trade” and EFT uppercase English Alphabets
(Electronic Transfer) is “Paperless
Payment”
●● Ed Guilbert, is called as the father of
EDI
EVALUATION
stu nt activity
de
●● Prepare a chart explaining various types of EDI standards. (e.g. web EDI)
01
exercise
PageMaker-Page Formatting
AIM
To create a new document using thedefault given options.
1. Open Pagemaker 7.0 and create a new document layout which includes the following
setup options:
●● Page size – A4.
●● Number of Pages – 4.
●● Margins 1.25 inches- top, and .75 inches - all other sides.
3. Set the heading ‘HAPPINESS’ in 18 points, Arial font, bold and alignment centre.
277
www.tntextbooks.org
Procedure
1. Start the PageMaker using the following commands.
Start -> All Programs -> Adobe -> PageMaker 7.0 -> Adobe PageMaker 7.0. The
Adobe PageMaker window will be opened as shown in Figure.
278 Practicals
www.tntextbooks.org
2. Choose File > New in the menu bar. (or) Press Ctrl + N in the keyboard.
This opens the Document Setup dialog box.
●● Click the Page Size drop down list box and select A4 size.
●● In the Number of pages text box, type 4.
●● Set the values in the Margins sections as follows :
Inside – – 0.75 inches
Outside – 0.75 inches
Top – 1.25 inches
Bottom – 0.75 inches
Practicals 279
www.tntextbooks.org
3. Click on OK. Now a new document called Untitled – 1 will appear on the screen as
shown in Figure.
4. Click on the Text tool and create a text block. Then type the following text in the text
block.
HAPPINESS
Happiness is often confused with fun, good living, and riches. Sometimes fun is
equated with happiness. Fun is what we experience while doing an activity, whereas
happiness is a residual and long-lasting feeling. The path to happiness is long and
full of challenges. Happiness requires life-long pursuit.
280 Practicals
www.tntextbooks.org
5. Select the word ‘HAPPINESS’ with Text tool. Using Character Control Palette,
change the font to Arial, font size to 18, and Leading 22. Then click on Bold button.
Then press Shift + Ctrl + C for centre alignment.
Practicals 281
www.tntextbooks.org
6. Select the paragraph with Text tool. Using Character Control Palette, change the
font to Arial, font size to 12, and Leading 20. Then press Shift + Ctrl + J for Justify.
282 Practicals
www.tntextbooks.org
Output
HAPPINESS
Happiness is often confused with fun, good living, and riches. Sometimes fun is
equated with happiness. Fun is what we experience while doing an activity, whereas
happiness is a residual and long-lasting feeling. The path to happiness is long and
full of challenges. Happiness requires life-long pursuit.
Conclusion
The expected output is achieved.
Practicals 283
www.tntextbooks.org
02
exercise
AIM
To create a Student Notice Board.
Procedure
1. Start the PageMaker using the following commands.
Start -> All Programs -> Adobe -> PageMaker 7.0 -> Adobe PageMaker 7.0. The
Adobe PageMaker window will be opened.
2. Choose File > New in the menu bar (or) Press Ctrl + N in the keyboard.
This opens the Document Setup dialog box.
3. Click on OK button.
Now a new document called Untitled – 1 will appear on the screen.
4. Create a box with dimension 100 mm x 100 mm using the Rectangle tool. Fill it with
cyan colour and change the percentage value of tint to 25%. The resulting box is as
shown in Figure.
284 Practicals
www.tntextbooks.org
5. Similarly create another box with dimension 100 mm x 15 mm. Fill it with black
colour and place it on the top portion of the cyan filled box as shown in figure.
Practicals 285
www.tntextbooks.org
6. With the text tool click and drag the mouse from the left corner to the right corner
of the black filled box and type the following words “Student Notice Board”.
The colour of the text and the colour of the box will be same black colour. As soon
as you finish typing press Ctrl + A in the keyboard which will select the entire text.
Using Character Control palette change the font size to 20 points and click on the
Bold button. Then click on the Reverse button which will change the colour of the
text to white and press Shift + Ctrl + C for centre alignment. The result is as shown
in Figure.
Output
Conclusion
The expected output is achieved.
286 Practicals
www.tntextbooks.org
03
exercise
AIM
To create a Visiting Card using PageMaker software.
Procedure
1. Start the PageMaker using the following commands.
Start -> All Programs -> Adobe ->Pagemaker 7.0 -> Adobe PageMaker 7.0. The
Adobe PageMaker window will be opened as shown in Figure 1.1.
Practicals 287
287
www.tntextbooks.org
2. Choose File > New in the menu bar (or) Press Ctrl + N in the keyboard.
This opens the Document Setup dialog box.
288 Practicals
www.tntextbooks.org
3. Click on OK.
Now a new document called Untitled – 1 will appear on the screen as shown in
Figure.
Practicals 289
www.tntextbooks.org
5. Select the Rectangle Tool from the Tool box and draw a rectangle.
6. Using Control Palette, the width and height value of the rectangle has to be set to 95
mm and 55 mm respectively.
290 Practicals
www.tntextbooks.org
7. Select the Text Tool in the Tool box. Then drag from the left corner of the rectangle
box to the right corner to specify the boundary of the text that is to be typed.
8. Type the Name of the person and select it using Text tool. Choose suitable Font and
Font Size from the Control Palette. Then move it a little bit towards right side.
Practicals 291
www.tntextbooks.org
9. Repeat the step 7. Then type the Company name and select it using Text tool. Choose
suitable Font and Font Size from the Control Palette. Then move it a little bit towards
right side.
Select the First character using the Text tool and increase the font size.
292 Practicals
www.tntextbooks.org
10. Repeat the step 7. Then type the Company Address and select it using Text tool.
Choose suitable Font and Font Size from the Control Palette. Then move it towards
right side.
Output
Conclusion
The expected output is achieved.
Practicals 293
www.tntextbooks.org
04
exercise
AIM
To create a Label using PageMaker software.
Procedure
1. Start the PageMaker using the following commands.
Start -> All Programs -> Adobe ->Pagemaker 7.0 -> Adobe PageMaker 7.0.
2. Choose File > New in the menu bar (or) Press Ctrl + N in the keyboard.
This opens the Document Setup dialog box.
3. Click on OK.
Now a new document called Untitled – 1 will appear on the screen.
4. Now you can change Measuring Units from Inches to Millimeters.
Choose File > Preferences > general (or ) Press Ctrl + K. Now Preferences dialogue
box appears.
Change the unit of Measurements and Vertical ruler to Millimeters.
294 Practicals
www.tntextbooks.org
5. Select the Rectangle Tool from the Tool box and draw a rectangle.
6. Using Control Palette, the width and height value of the rectangle has to be set to
100 mm and 40 mm respectively.
8. Choose the required shape from the rounded corners dialog box. Now the rectangle
appears with the rounded corners.
9. Select the Text Tool in the Tool box and create a text block within the rectangle.
10. Type Name : and press a Tab key and then press Enter key.
Type STD : and press a Tab key and then press Enter key.
Type Section : and press a Tab key and then press Enter key.
Type School : and press a Tab key and then press Enter key.
13. Set a right tab at the value 90 mm and choose the dotted line style from the leader
option and then press Apply button.
Practicals 295
www.tntextbooks.org
Output
Conclusion
The expected output is achieved.
296 Practicals
www.tntextbooks.org
05
exercise
MySQL - Usage of
Commands in Data Base
AIM
To execute following DDL [Data definition Language] and DML [Data manipulating
Language] MySQL queries
1. CREATE - to create a database and its objects like (table, index, views, store procedure,
function, and triggers)
2. ALTER - alters the structure of the existing database.
3. DROP - delete objects from the database.
4. SELECT - retrieve data from a database.
5. INSERT - insert data into a table.
6. UPDATE - updates existing data within a table.
7. DELETE - Delete all records from a database table.
Procedure
1. Open MySQL command prompt from XAMPP Control panel.
2. To login in to your Database using User name and password.
3. Execute and get the output of given DDL MySQL queries.
SYNTAX:
Based on the below syntax queries are built and executed.
* CREATE DATABASE testDB;
* CREATE TABLE table_name (column1datatype,column2datatype,column3datatype, .... );
* ALTER TABLE `table_name` ADD COLUMN `column_name` `data_type`;
* DROP DATABASE databasename;
* SELECT * FROM TABLE NAME
* INSERT INTO table_name( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN );
* UPDATE table_name SET field1 = new-value1, field2 = new-value2 [WHERE Clause]
* DROP TABLE table_name ;
Practicals 297
297
www.tntextbooks.org
PROGRAM:
CREATE DATABASE SchoolDB;
studentID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
298 Practicals
www.tntextbooks.org
OUTPUT
Database created
Table created:
studentID LastName FirstName Address City
Table Altered
Database dropped
StudentID LastName FirstName Address City
101 C Priya 1, new street Trichy
202 S Ramu 5, North garden Madurai
St
One row inserted.
StudentID LastName FirstName Address City
101 C Priya 1, new street Trichy
202 S Ramu 5, North garden Madurai
St
002 Ram Kumar ROJA NAGAR CHENNAI
003 R Krishna Park Street Coimbatore
StudentID LastName FirstName Address City
101 C Priya 1, new street Trichy
202 S Ramu 5, North garden Madurai
St
002 Ram Kumar ROJA NAGAR CHENNAI
003 SRI Krishna Park Street Coimbatore
Table dropped.
Table not found.
Practicals 299
www.tntextbooks.org
06
exercise
PHP–Basic Programing
AIM
To create and execute a basic PHP programing
Procedure
1. Start Xampp server (Apache)
2. Goto virtual path folder (C:\xampp\htdocs)
3. Create test.php file and type the program
4. Execute the program on your Web browser using by this URL link (http://localhost/
test.php)
PROGRAM
<html>
<body>
<?php
echo “Welcome to Our School”;
$color = “blue”;
echo “My car is “ . $color . «<br>”;
echo “My dress is “ . $COLOR . «<br>”;
echo “My box is “ . $coLOR . «<br>”;
// test whether a number is greater than 30, 20 or 10 using ternary operator
functiontrinary_Test($n){
300 Practicals
www.tntextbooks.org
$r = $n > 30
? “greater than 30”
: ($n > 20
? “greater than 20”
: ($n >10
? “greater than 10”
: “Input a number atleast greater than 10!”));
echo $n.” : “.$r.”\n”;
}
trinary_Test(32);
trinary_Test(21);
trinary_Test(12);
trinary_Test(4);
?>
</body>
</html>
OUTPUT
My car is blue
My dress is
My box is
32 : greater than 30
21 : greater than 20
12 : greater than 10
4 : Input a number atleast greater than 10!
Practicals 301
www.tntextbooks.org
07
exercise
AIM
To create and execute a PHP Variables Example program
Procedure
1. Start Xampp server (Apache)
2. Goto virtual path folder (C:\xampp\htdocs)
3. Create Variable.php file and type the program
4. Execute the program on your Web browser using by this URL link (http://localhost/
Variable.php)
PROGRAM
<html>
<body>
<?php
$a = 25; // Numerical variable
$b = “Hello”; // String variable
$c = 5.7; // Float variable
echo ‚Number is : “.$a.‚<br/>”;
echo ‚String is : “.$b.‚<br/>”;
echo “Float value : “.$c;
$txt = “INDIA”;
echo “I love $txt!”;
$x = 2;
$y = 2;
302 Practicals
www.tntextbooks.org
echo $x + $y;
function demo() {
echo «<p>Variable x inside function is: $x</p>»;
}
demo();
echo “<p>Variable x outside function is: $x</p>”;
function myTest() {
static $a = 0;
echo $a;
$a++;
}
myTest();
echo “<br>”;
myTest();
echo “<br>”;
myTest();
?>
</body>
<html>
OUTPUT
Number is : 25
String is : Hello
Float value : 5.7
I LOVE INDIA
4
0
1
2
Variable x inside function is:
Variable x outside function is: 2
Practicals 303
www.tntextbooks.org
08
exercise
AIM
To create and execute ECHO and PRINT statements in PHP program.
Procedure
1. Start Xampp server (Apache)
2. Goto virtual path folder (C:\xampp\htdocs)
3. Create echo-print.php file and type the program
4. Execute the program on your Web browser using by this URL link
(http://localhost/ echo-print.php)
PROGRAM
<html>
<body>
<?php
//Use Echo
echo “Welcome to Tamilnadu<br>”;
// Use ‘print’ to print on console
print “Welcome to our School!<br>***********”;
$txt1 = “Learn PHP”;
$txt2 = “Daily”;
$x = 5;
$y = 4;
304 Practicals
www.tntextbooks.org
OUTPUT
Welcome to Tamilnadu
Welcome to our School!
***********
Learn PHP
Study PHP Daily
9
HELLO
Hi Welcome
10
Practicals 305
www.tntextbooks.org
09
exercise
String Functions
AIM
To create and execute String Functions in PHP
Procedure
1. Start Xampp server (Apache)
2. Goto virtual path folder (C:\xampp\htdocs)
3. Create funtion.php file and type the program
4. Execute the program on your Web browser using by this URL link
(http://localhost/ funtion.php)
<html>
<body>
<?php
// Displays the length of the string
echostrlen(“Hello world!”);
//Counting number of words in a String
echo str_word_count(“Good Morning All”);
// Reversing a string
echo strrev(“welcome”);
306 Practicals
www.tntextbooks.org
OUTPUT
12
3
emoclew
6
Hello Everyone
Good Morning!!!
PHP Tutorial
Practicals 307
www.tntextbooks.org
10
exercise
AIM
Write a PHP program to convert word to digit.
Procedure
1. Start Xampp server (Apache)
2. Goto virtual path folder (C:\xampp\htdocs)
3. Create convert.php file and type the program
4. Execute the program on your Web browser using by this URL link
(http://localhost/convert.php)
<html>
<body>
<?php
functionword_digit($word) {
$warr = explode(‘;’,$word);
$result = ‘’;
foreach($warr as $value){
switch(trim($value)){
case ‘zero’:
$result .= ‘0’;
break;
case ‘one’:
$result .= ‘1’;
break;
case ‘two’:
308 Practicals
www.tntextbooks.org
$result .= ‘2’;
break;
case ‘three’:
$result .= ‘3’;
break;
case ‘four’:
$result .= ‘4’;
break;
case ‘five’:
$result .= ‘5’;
break;
case ‘six’:
$result .= ‘6’;
break;
case ‘seven’:
$result .= ‘7’;
break;
case ‘eight’:
$result .= ‘8’;
break;
case ‘nine’:
$result .= ‘9’;
break;
}
}
return $result;
}
echoword_digit(“zero;three;five;six;eight;one”).”\n”;
echoword_digit(“seven;zero;one”).”\n”;
?>
</body>
</html>
OUTPUT
035681
701
Practicals 309
REFERENCES
www.tntextbooks.org
310 Practicals
INTERNET RESOURCES
www.tntextbooks.org
Internet resources
1. https://whois.icann.org/en
2. https://www.iana.org/
3. https://en.wikipedia.org/wiki/Networking_cables
4. https://www.lifewire.com/
5. https://www.tutorialspoint.com/computer_fundamentals/computer_networking.
htm
6. http://www.groundcontrol.com/galileo/ch5-ethernet.htm
7. https://www.tutorialsweb.com
8. https://opensource.com
9. https://www.oshwa.org/
10. https://www.unece.org/cefact/edifact/welcome.html
Practicals 311
Higherwww.tntextbooks.org
Secondary Class XII
Computer Applications - Theory & Practicals
List of Authors and Reviewers
Mrs. A. Arthi
Domain Experts Associate Professor, Dept. of Information Technology
Mrs. P. Bagyalakshmi, R. M. K Engineering Collage, Kavaraipettai, Thiruvallur.
Prof & Head, Dept of computer Applications,
Mrs. Sandhya Alagarsamy,
Queen Mary’s College,
Assistant Professor,
Chennai.
Dept. of Information Technology,
Jeppiaar SRR Engineering College, Chennai.
Mr. Amuthan,
Professor & Associate Dean (Automomy & Accreditation),
Mr. R. Sethuraman,
Dept. of Computer Science & Engineering, Assistant Professor,
Pondicherry Engineering College, Dept. of CS & Engineering Sathyabama,
Pillaichavady, Pudhucherry. Institute of Science & Technology, Chennai.
V. Padmavathi, B.T,
Coordination GHS, Vetriyur, Ariyalur.
Ramesh Munisamy
This book has been printed on 80 G.S.M.
Elegant Maplitho paper.