0% found this document useful (0 votes)
42 views680 pages

STD 12th Computer Books

This document is a textbook published by the Government of Tamil Nadu for the Higher Secondary Second Year Computer Science curriculum. It covers topics such as Python programming, database concepts, and algorithmic strategies, and is designed for students with prior knowledge of C++. The book includes practical activities, a glossary of terms, and links to additional digital resources via QR codes.

Uploaded by

rakshith sooriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views680 pages

STD 12th Computer Books

This document is a textbook published by the Government of Tamil Nadu for the Higher Secondary Second Year Computer Science curriculum. It covers topics such as Python programming, database concepts, and algorithmic strategies, and is designed for students with prior knowledge of C++. The book includes practical activities, a glossary of terms, and links to additional digital resources via QR codes.

Uploaded by

rakshith sooriya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 680

www.tntextbooks.

org

GOVERNMENT OF TAMILNADU

HIGHER SECONDARY
SECOND YEAR

COMPUTER SCIENCE

A publication under Free Textbook Programme of Government of Tamil Nadu

Department of School Education


www.tntextbooks.org

Untouchability is Inhuman and a Crime

Index.indd 1 20-02-2019 15:06:40


www.tntextbooks.org

Government of Tamil Nadu


First Edition - 2019
(Published under New Syllabus)

NOT FOR SALE

Content Creation

The wise
possess all

State Council of Educational


Research and Training
© SCERT 2019

Printing & Publishing


www.tntextbooks.org

Tamil NaduTextbook and Educational


Services Corporation
www.textbooksonline.tn.nic.in

II

Index.indd 2 20-02-2019 15:06:40


www.tntextbooks.org

The tremendous effect of the computer and computing technology is in


shaping the modern society for the betterment of mankind. Human
civilization achieved the highest peak with the development
of computer known as “Internet Era”.

PREFACE Python being a high level language is good


for beginners to learn due to its easy syntax
and powerful memory management. For any
internet applications, it is good to learn as python being the
better choice.
The user of this textbook being acquainted with the knowledge of C++ in
std XI will have no difficulty in studying python language. No substantial
knowledge nor experience, is required as the examples illustrated in the
book are easy to follow.

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

and then bring it closer to the QR code in the textbook.


o Once the camera detects the QR code, a URL appears in the screen.
Click the URL and go to the content page.

III

Index.indd 3 20-02-2019 15:06:40


Index.indd 4
Computer Knowledge Hub PG in Computer Science

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

DST – INSPIRE Fellowships (for Ph.D)


Professional Degree & Entrance Exams DST – INSPIRE Scholarships
(for UG and PG)
Hotel & Catering Institute http://www.ihmchennai.org/ihmchennai/ JEE-Joint Entrance Examination https://jeemain.nic.in/ In addition various fellowships for
AIEEE- All India Engineering Entrance Exam JEST- Joint Entrance Screening Test https://www.jest.org.in SC/ST/PWD,
B.E/B.Tech/ B.Arch (JEE, AIEEE in IITs and NITs) Law 5-Year Integrated Course http://tndalu.ac.in Indira Gandhi Fellowship for
Fashion Technology & Design http://nift.ac.in National Defence Academy https://www.nda.nic.in Single girl child (for UG and PG)
GATE-Graduate Aptitude Test in Engineering NET- National Eligibility Test (CSIR and UGC) http://cbsenet.nic.in Moulana Azad Fellowship
www gate.iitm.ac.in TamilNadu Dr. Ambedkar Law University http://tndalu.ac.in for minorities (for Ph.D)
Indian Navy – 10+2 BTech Entry Scheme Technical Entry Scheme – Army/Navy/Airforce UGC National Fellowship (for Ph.D)
Institute of Chartered Accountants of India https://icai.org TIFR GS - Tata Institute of Fundamental
CAREER GUIDANCE AFTER 12TH

International Olympiad: for getting stipend for


Institute of Company Secretary https://www.icsi.edu Research Graduate School http://univ.tifr.res.in Higher Education in Science and Mathematics
Institute of Cost Accountants of India http://icmai.in Visual Arts Degree OBC etc are available.
Institute of Banking Personal Selection IBPS https://ibps.in http://www.tndipr.gov.in/television-traininginstitute.aspx
Visit website of University Grants Commission

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

with Applications to Educational Games


Research Institutions in various areas of science

Bhaba Atomic Research centre Institute of Mathematical Sciences (IMSc)


(BARC) Mumbai www.barc.gov.in Chennai www.imsc.res.in
CAREER GUIDANCE

BITS Pilani, https://www.bits-pilani.ac.in Jawaharlal Nehru University (JNU) www.jnu.ac.in


Topics for Research after PG in Computer Studies
T
Central Universities www.ugc.ac.in Mumbai University, Mumbai www.mu.ac.in
Chennai Mathematical Institute National Institute of Science Education and
Architectures, Compiler Optimization, and Embedded Systems. (CMI) Chennai www.cmi.ac.in Research (NISER), www.niser.ac.in
Bioinformatics and Computational Biology | Cloud Computing Delhi University, Delhi www.du.ac.in National Institute of Technology
Hyderabad central university, (NITs) www.nitt.edu
Data Mining, Databases, and Geographical Information Systems.
Hyderabad www.uohyd.ac.in SavithiribaiPhule Pune university,
Graphics and Visualization | High Performance Computing. Pune www.unipune.ac.in
IISER Educational Institutions
Human Computer Interaction | Internet of Things www.iiseradmission.in State Universities https://www.ugc.ac.in
Natural Language Processing | Networks, Distributed Systems, and Security. Indian Institute of Technology in Tata Institute of Fundamental Research
various places (IIT’s) www.iitm.ac.in (TIFR) Mumbai www.tifr.res.in

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

UNIT- II 6 Control Structures 67


Core Python 7 Python functions 89
8 Strings and String manipulations 114
UNIT-III 9 Lists, Tuples, Sets and Dictionary 132
Modularity
and OOPS 10 Python Classes and objects 170

UNIT-IV 11 Database Concepts 189


Database
12 Structured Query Language (SQL) 205
concepts and
MySql 13 Python and CSV files 232

UNIT-V 14 Importing C++ programs in Python. 267


Integrating 15 Data manipulation through SQL 291
Python with Data visualization using pyplot: line chart, pie
MySql and C++ 16 320
chart and bar chart
Glossary 335
Annexure-1 List of Python functions 341
Annexure-2 Installation of MySQL and Creating a Database 345
Annexure-3 Installation of MinGW 346
Annexure-4 Installation of pip 351
www.tntextbooks.org

E - book Assessment DIGI links


VI

Index.indd 6 20-02-2019 15:06:41


www.tntextbooks.org

CHAPTER 1
Unit I
FUNCTION

1.2 Function with respect to


Learning Objectives Programming language

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

repeatedly. In Programming languages these definition:


subroutines are called as Functions.

Chapter 1.indd 1 20-02-2019 15:17:15


www.tntextbooks.org

mandatory. Generally we can leave out


(requires: b>=0 ) these annotations, because it's simpler to
(returns: a to the power of b) let the compiler infer them. There are times
let rec pow a b:= we may want to explicitly write down types.
if b=0 then 1 This is useful on times when you get a type
else a * pow a (b-1) error from the compiler that doesn't make
sense. Explicitly annotating the types can
help with debugging such an error message.
In the above function definition
variable ‘b’ is the parameter and the value
The syntax to define functions is close
which is passed to the variable ‘b’ is the
to the mathematical usage: the definition is
argument. The precondition (requires) and
introduced by the keyword let, followed by
postcondition (returns) of the function
the name of the function and its arguments;
is given. Note we have not mentioned any
then the formula that computes the image
types: (data types). Some language compiler
of the argument is written after an = sign. If
solves this type (data type) inference
you want to define a recursive function: use
problem algorithmically, but some require
“let rec” instead of “let”.
the type to be mentioned.
Syntax: The syntax for function definitions:
In the above function definition if
expression can return 1 in the then branch,
by the typing rule the entire if expression let rec fna1 a2 ... an := k
has type int. Since the if expression has
type ‘int’, the function's return type also be Here the ‘fn’ is a variable indicating
‘int’. ‘b’ is compared to 0 with the equality an identifier being used as a function
operator, so ‘b’ is also a type of ‘int’. Since ‘a’ name. The names ‘a1’ to ‘an’ are variables
is multiplied with another expression using indicating the identifiers used as parameters.
the * operator, ‘a’ must be an int. The keyword ‘rec’ is required if ‘fn’ is to be
a recursive function; otherwise it may be
2. Parameter with Type
omitted.
Now let us write the same function
definition with types for some reason:
Note
(requires: b> 0 ) A function definition which call
itself is called recursive function.
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
For example: let us see an example to check
if b=0 then 1
whether the entered number is even or odd.
else a * pow b (a-1)
www.tntextbooks.org

When we write the type annotations


for ‘a’ and ‘b’ the parentheses are

XII Std Computer Science 2

Chapter 1.indd 2 20-02-2019 15:17:15


www.tntextbooks.org

interface. In our example, anything that


(requires: x>= 0)
let rec even x := "ACTS LIKE" a light, should have function
x=0 || odd (x-1) definitions like turn_on () and a turn_off
return ‘even’ (). The purpose of interfaces is to allow the
(requires: x>= 0) computer to enforce the properties of the
let odd x := class of TYPE T (whatever the interface is)
x<>0 && even (x-1) must have functions called X, Y, Z, etc.
return ‘odd’
A class declaration combines the
The syntax for function types: external interface (its local state) with an
implementation of that interface (the code
x→y that carries out the behaviour). An object is
x1 → x2 → y an instance created from the class.
x1 → ... → xn → y
The interface defines an object’s visibility to
the outside world.
The ‘x’ and ‘y’ are variables indicating
types. The type x → y is the type of a function The difference between interface and
that gets an input of type ‘x’ and returns an implementation is
output of type ‘y’. Whereas x1 → x2 → y is
a type of a function that takes two inputs, Interface Implementation
the first input is of type ‘x1’ and the second
input of type ‘x2’, and returns an output of Interface just Implementation
type ‘y’. Likewise x1 → … → xn → y has defines what carries out the
type ‘x’ as input of n arguments and ‘y’ type an object can instructions defined
do, but won’t in the interface
as output.
actually do it

Note In object oriented programs classes are


All functions are static the interface and how the object is processed
definitions. There is no dynamic and executed is the implementation.
function definitions.
1.3.1 Characteristics of interface
• The class template specifies the interfaces
1.3 Interface Vs Implementation
to enable an object to be created and
An interface is a set of action that an operated properly.
object can do. For example when you press
a light switch, the light goes on, you may • An object's attributes and behaviour is
not have cared how it splashed the light. In controlled by sending functions to the
www.tntextbooks.org

Object Oriented Programming language, object.


an Interface is a description of all functions
that a class must have in order to be a new For example, let's take the example of
increasing a car’s speed.

3 Function

Chapter 1.indd 3 20-02-2019 15:17:15


www.tntextbooks.org

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

required No Pure functions are functions which


Pull Fuel
speed will give exact result when the same
arguments are passed. For example the
Yes
mathematical function sin (0) always results
Return 0. This means that every time you call the
function with the same arguments, you will
always get the same result. A function can
The person who drives the car be a pure function provided it should not
doesn't care about the internal working. To have any external variable which will alter
increase the speed of the car he just presses the behaviour of that variable.
the accelerator to get the desired behaviour.
Here the accelerator is the interface between Let us see an example
the driver (the calling / invoking object) and
the engine (the called object). let square x

In this case, the function call would return: x * x


be Speed (70): This is the interface.

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

-- Do something which doesn't affect s



++i

XII Std Computer Science 4

Chapter 1.indd 4 20-02-2019 15:17:15


www.tntextbooks.org

If it is compiled, strlen (s) is called Here the function Random is impure


each time and strlen needs to iterate over as it is not sure what will be the result when
the whole of ‘s’. If the compiler is smart we call the function.
enough to work out that strlen is a pure
1.4.2 Side-effects (Impure functions)
function and that ‘s’ is not updated in the
loop, then it can remove the redundant As you are aware function has side
extra calls to strlen and make the loop to effects when it has observable interaction
execute only one time. From these what we with the outside world. There are situations
can understand, strlen is a pure function our functions can become impure though
because the function takes one variable as a our goal is to make our functions pure.
parameter, and accesses it to find its length. Just to clarify remember that side effect is
This function reads external memory but not a necessary bad thing.Sometimes they
does not change it, and the value returned are useful (especially outside functional
derives from the external memory accessed. programming paradigm).
Modify variable outside a function
Note One of the most popular groups of
Evaluation of pure side effects is modifying the variable outside

functions does not cause any side of function.
effects to its output
For example

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

else the main differences between pure and


return: 10 impure functions are

5 Function

Chapter 1.indd 5 20-02-2019 15:17:15


www.tntextbooks.org

1.4.3 Chameleons of Chromeland


Pure Function Impure Function
problem using function
The return value of The return value Recall the In the Chameleons of
the pure functions of the impure Chromeland problem what you have studied
solely depends functions does in class XI. suppose two types of chameleons
on its arguments not solely depend
are equal in number. Construct an algorithm
passed. Hence, if on its arguments
you call the pure passed. Hence, that arranges meetings between these two
functions with if you call the types so that they change their color to the
the same set of impure functions third type. In the end, all should display the
arguments, you with the same same color.
will always get set of arguments,
­
the same return you might get Let us represent the number of
values. the different chameleons of each type by variables a, b
return values and c, and their initial values by A, B and C,
They do not have For example, respectively. Let a = b be the input property.
any side effects. random(), Date().
The input – output relation is a =
They do not They may modify
b = 0 and c = A + B + C. Let us name the
modify the the arguments
arguments which which are passed algorithm monochromatize. The algorithm
are passed to them to them can be specified as

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

XII Std Computer Science 6

Chapter 1.indd 6 20-02-2019 15:17:15


www.tntextbooks.org

In each meeting, a and b each


a, b, c
decreases by 1, and c increases by 2. The
a = b, a = A, b = B, c = C
solution can be expressed as an iterative
algorithm.
True
a>0 a, b, c := a - 1, b - 1, c+2
monochromatize (a, b, c)
-- inputs : a = A, b=B, c=C, a=b False
a = b = 0, c = A + B + C
-- outputs : a = b = 0, c = A+B+C
a, b, c
while a>0
a, b, c := a-1, b-1, c+2
Now let us write this algorithm using

function
The algorithm is depicted in the flowchart
as below let rec monochromatize a b c :=
if a > 0 then
a, b, c := a-1, b-1, c+2
else
a:=0, b:=0, c:= a + b + c

return c

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

Chapter 1.indd 7 20-02-2019 15:17:15


www.tntextbooks.org

Hands on Practice

1. Write algorithmic function definition to find the minimum among 3 numbers.


2. Write algorithmic recursive function definition to find the sum of n natural numbers.

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

(A) Impure functions (B) Partial Functions


(C) Dynamic Functions (D) Pure functions

XII Std Computer Science 8

Chapter 1.indd 8 20-02-2019 15:17:15


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

Answer the following questions (2 Marks)


1. What is a subroutine?
2. Define Function with respect to Programming language.
3. Write the inference you get from X:=(78).
4. Differentiate interface and implementation.
5. Which of the following is a normal function definition and which is recursive function
definition
i) let rec sum x y:

return x + y

ii) let disp :

print ‘welcome’

iii) let rec sum num:

if (num!=0) then return num + sum (num-1)

else

return num

Part - III

Answer the following questions (3 Marks)


1. Mention the characteristics of Interface.
2. Why strlen is called pure function?
3. What is the side effect of impure function. Give example.
4. Differentiate pure and impure function.
5. Wha happens if you modify a variable outside the function? Give an example.
www.tntextbooks.org

9 Function

Chapter 1.indd 9 20-02-2019 15:17:15


www.tntextbooks.org

Part - IV

Answer the following questions (5Marks)


1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a

i) Name of the function


ii) Identify the statement which tells it is a recursive function
iii) Name of the argument variable
iv) Statement which invoke the function recursively
v) Statement which terminates the recursion
3. Explain with example Pure and impure functions.
4. Explain with an example interface and implementation.

REFERENCES

1. Data Structures and Algorithms in Python By Michael T.Goodrich, RobertoTamassia and


Michael H. Goldwasser.
2. Data Structure and Algorithmic Thinking in Python By Narasimha Karumanchi
3. https://www.python.org

www.tntextbooks.org

XII Std Computer Science 10

Chapter 1.indd 10 20-02-2019 15:17:16


www.tntextbooks.org

CHAPTER 2
Unit I
DATA ABSTRACTION

2.2 Abstract Data Types


Learning Objectives
Abstract Data type (ADT) is a type (or
After the completion of this chapter, the class) for objects whose behavior is defined
student will be able to Understand by a set of value and a set of operations.
• what is Abstract Data structures. The definition of ADT only mentions
• Abstract data type. what operations are to be performed but not
how these operations will be implemented. It
• Difference between concrete and abstract
does not specify how data will be organized
implementation.
in memory and what algorithms will be
• Pairs. used for implementing the operations.
• Data Abstration in Structure. It is called “abstract” because it gives an
implementation independent view. The
2.1 Data Abstraction-
process of providing only the essentials and
Introduction
hiding the details is known as abstraction.
Data abstraction is a powerful You can see that these definitions
concept in computer science that allows do not specify how these ADTs will be
programmers to treat code as objects — for represented and how the operations will be
example, car objects, pencil objects, people carried out. There can be different ways to
objects, etc. Programmers need not to worry implement an ADT, for example, the List
about how code is implemented — they have ADT can be implemented using singly linked
to just know what it does. list or doubly linked list. Similarly, stack
This is especially important when ADT and Queue ADT can be implemented
several people are doing a project. Here using lists.
project refers to the programming .With Data abstraction replicate how we
data abstraction, your group members won’t think about the world. For example, when
have to read through every line of your code you want to drive a car, you don’t need to
to understand. They can just assume that it know how the engine was built or what
does work. kind of material the tires are made of. You
Abstraction provides modularity just have to know how to turn the wheel
and press the gas pedal. To facilitate data
www.tntextbooks.org

(modularity means splitting a program in


to many modules). Classes (structures) are abstraction, you will need to create two
the representation for “Abstract Data Types”, types of functions: constructors and
(ADT) selectors.

11

Chapter 2.indd 11 20-02-2019 15:18:04


www.tntextbooks.org

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

getlat(city1) and lg1 becomes the value of


• getlon(city)
getlont(city1).
are the selectors because these functions
extract the information of the city object
XII Std Computer Science 12

Chapter 2.indd 12 20-02-2019 15:18:04


www.tntextbooks.org

city value passed as parameter city value passed as parameter city value passed as parameter

getname ( ) getlat ( ) getlon ( )

Now let us consider one more example to representation is defined as an independent


identify the constructor and selector for a part of the program.
slope.Read - - as comments.
Note
- - constructor In concrete data representation, a
makepoint(x, y): definition for each function is known
return x, y
- - selector
xcoord(point): Any program consist of two parts.
return point[0] The two parts of a program are, the part
- -selector that operates on abstract data and the part
ycoord(point): that defines a concrete representation, is
return point[1] connected by a small set of functions that
implement abstract data in terms of the
concrete representation. To illustrate this
Note technique, let us consider an example to
Data abstraction is supported by design a set of functions for manipulating
defining an abstract data type (ADT), rational numbers.
which is a collection of constructors
and selectors. Constructors create an Example
object, bundling together different pieces A rational number is a ratio of
of information, while selectors extract integers, and rational numbers constitute
individual pieces of information from the an important sub-class of real numbers.
object.
A rational number such as 8/3 or 19/23 is
typically written as:
2.4 Representation of Abstract
datatype using Rational <numerator>/<denominator>
numbers
where both the <numerator> and
The basic idea of data abstraction is <denominator> are placeholders for integer
to structure programs so that they operate values. Both parts are needed to exactly
on abstract data. That is, our programs characterize the value of the rational number.
www.tntextbooks.org

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

Chapter 2.indd 13 20-02-2019 15:18:04


www.tntextbooks.org

8/3 =2.6666666666666665 component. Let us further assume that the


However, you can create an exact constructor and selectors are also available.
representation for rational numbers by
We are using here a powerful strategy
combining together the numerator and
for designing programs: 'wishful thinking'.
denominator.
We haven't yet said how a rational number
As we know from using functional is represented, or how the constructor and
abstractions, we can start programming selectors should be implemented.
productively before you have an
implementation of some parts of our
Note
program. Let us begin by assuming that
you already have a way of constructing a Wishful Thinking is the formation
rational number from a numerator and a of beliefs and making decisions according
denominator. You also assume that, given to what might be pleasing to imagine
a rational number, you have a way of instead of by appealing to reality.
selecting its numerator and its denominator

Example: An ADT for rational numbers


- - constructor
- - constructs a rational number with numerator n, denominator d
rational(n, d)
- - selector
numer(x) → returns the numerator of rational number x
denom(y) → returns the denominator of rational number y

Now you have the operations on 2.5 Lists,Tuples


rational numbers defined in terms of the
selector functions numer and denom, and To enable us to implement the
the constructor function rational, but you concrete level of our data abstraction, Some
haven't yet defined these functions. What languages like Python provides a compound
you need is some way to glue together structure called Pair which is made up of list
a numerator and a denominator into a or Tuple. The first way to implement pairs is
compound value. with the List construct.
The pseudo code for the
2.5.1 List
representation of the rational number using
the above constructor and selector is List is constructed by placing
expressions within square brackets
x,y:=8,3 separated by commas. Such an expression
www.tntextbooks.org

rational(n,d) is called a list literal. List can store multiple


numer(x)/numer(y) values. Each value can be of any type and
- - output : 2.6666666666666665 can even be another list.

XII Std Computer Science 14

Chapter 2.indd 14 20-02-2019 15:18:04


www.tntextbooks.org

Example for List is [10, 20]. code : a numerator and a denominator.


The elements of a list can be accessed rational(n, d):
in two ways. The first way is via our familiar
return [n, d]
method of multiple assignment, which
numer(x):
unpacks a list into its elements and binds
return x[0]
each element to a different name.
denom(x):
lst := [10, 20] return x[1]
x, y := lst
In the above example x will become10 2.5.2 Tuple
and y will become 20. Remember, a pair is a compound
A second method for accessing the data type that holds two other pieces of data.
elements in a list is by the element selection So far,we have provided you with two ways
operator, also expressed using square of representing the pair data type. The first
brackets. Unlike a list literal, a square- way is using List construct and the second
brackets expression directly following way to implement pairs is with the tuple
another expression does not evaluate to a construct.
list value, but instead selects an element A tuple is a comma-separated
from the value of the preceding expression. sequence of values surrounded with
lst[0] parentheses. Tuple is similar to a list. The
10 difference between the two is that you
cannot change the elements of a tuple once
lst[1]
it is assigned whereas in a list, elements can
20 be changed.
In both the example mentioned above
mathematically we can represent list similar Example colour= ('red', 'blue', 'Green')
to a set.
Representation of Tuple as a Pair
lst[(0, 10), (1, 20)] - where
nums := (1, 2)
(0, 10) (1, 20) nums[0]
1
Index position value Index position value nums[1]
2
Any way of bundling two values
together into one can be considered as a
Note the square bracket notation is
pair. Lists are a common method to do so.
used to access the data you stored in the
Therefore List can be called as Pairs.
pair. The data is zero indexed, meaning you
www.tntextbooks.org

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

Chapter 2.indd 15 20-02-2019 15:18:04


www.tntextbooks.org

2.6 Data Abstraction in person=['Padmashri', 'Baskar', '994-


Structure 222-1234', '[email protected]']

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

lastName, the id, and the email. One could


use a list to represent a person:

Person class name (multi part data representation)

creation ( )
function belonging to the new datatype

}
first Name

last Name variable (field) beloging to the new


datatype
id

email
www.tntextbooks.org

XII Std Computer Science 16

Chapter 2.indd 16 20-02-2019 15:18:04


www.tntextbooks.org

Let main() contains

p1:=Person() statement creates the object.


firstName := " Padmashri " setting a field called firstName with value Padmashri
lastName :="Baskar" setting a field called lastName with value Baskar
id :="994-222-1234" setting a field called id value 994-222-1234
email="[email protected]" setting a field called email with value [email protected]
- - output of firstName : Padmashri

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

Chapter 2.indd 17 20-02-2019 15:18:04


www.tntextbooks.org

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

Choose the best answer (1 Mark)


1. Which of the following functions that build the abstract data type ?
(A) Constructors (B) Destructors (C) recursive (D)Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D)Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
www.tntextbooks.org

7. Which of the following is a compound structure?


(A) Pair (B) Triplet (C) single (D) quadrat

XII Std Computer Science 18

Chapter 2.indd 18 20-02-2019 15:18:04


www.tntextbooks.org

8. Bundling two values together into one can be considered as


(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats

Part - II

Answer the following questions (2 Marks)


1. What is abstract data type?
2. Differentiate constructors and selectors.
3. What is a Pair? Give an example.
4. What is a List? Give an example.
5. What is a Tuple? Give an example.

Part - III

Answer the following questions (3 Marks)


1. Differentiate Concrete data type and abstract datatype.
2. Which strategy is used for program designing? Define that Strategy.
3. Identify Which of the following are constructors and selectors?
(a) N1=number() (b) accetnum(n1) (c) displaynum(n1)
(d) eval(a/b) (e) x,y= makeslope (m), makeslope(n)
(f) display()
4. What are the different ways to access the elements of a list. Give example.
5. Identify Which of the following are List, Tuple and class ?
(a) arr [1, 2, 34] (b) arr (1, 2, 34) (c) student [rno, name, mark]
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) (e) x= [2, 5, 6.5, [5, 6], 8.2]
www.tntextbooks.org

(f) employee [eno, ename, esal, eaddress]

19 Data Abstraction

Chapter 2.indd 19 20-02-2019 15:18:04


www.tntextbooks.org

Part - IV

Answer the following questions (5Marks)


1. How will you facilitate data abstraction. Explain it with suitable example
2. What is a List? Why List can be called as Pairs. Explain with suitable example
3. How will you access the multi-item. Explain with example.

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

XII Std Computer Science 20

Chapter 2.indd 20 20-02-2019 15:18:04


www.tntextbooks.org

CHAPTER 3
Unit I
SCOPING

you assign a variable with := to an instance


Learning Objectives (object), you're binding (or mapping) the
variable to that instance. Multiple variables
After the completion of this chapter, the can be mapped to the same instance.
student will be able to

• Understand what is Scoping Note


The process of binding a
• Able to implement the LEGB rule
variable name with an object is called
• Understand what is module mapping. = (equal to sign) is used in
• Understand the implementation of programming languages to map the
access control in programming language variable and object.

3.1 Introduction Programming languages keeps track


of all these mappings with namespaces.
Scope refers to the visibility of Namespaces are containers for mapping
variables, parameters and functions in one names of variables to objects. You can think
part of a program to another part of the of them as dictionaries, containing list
same program. In other words, which parts of words and its meanings. The words are
of your program can see or use it. Normally, mapped with its meaning in dictionaries
every variable defined in a program has whereas names are mapped with objects
global scope. Once defined, every part of (name : = object) in programming language.
your program can access that variable. But it This allows access to objects by names you
is a good practice to limit a variable's scope choose to assign to them.
to a single definition. This way, changes
inside the function can't affect the variable In the following example, a is first
on the outside of the function in unexpected mapped to the integer 5. In this case, a is the
ways. variable name, while the integer value 5 is
the object.
3.2 Variable Scope Then, b is set equal to a. This actually
To understand the scope of variables means that b is now bound to the same
in a programming language, it is important integer value as a, which is 5.
www.tntextbooks.org

to learn about what variables really are.


1. a:=5
Essentially, they're addresses (references, or
pointers), to an object in memory. When 2. b:=a

21

Chapter 3.indd 21 20-02-2019 15:18:40


www.tntextbooks.org

Mapping the error “name ‘a’ is not defined”. This is


because the lifetime of the variable is only till
the end of the procedure. Also, the duration
a for which a variable is alive is called its ‘life
5 time’.
3.3 LEGB rule
b
Scope also defines the order in which
variables have to be mapped to the object
Now consider the following extension in order to obtain the value. Let us take a
of the above statements simple example as shown below:

1. a:=5 1. x:= 'outer x variable'


2. b:=a 2. display():
3. a:=3 3. x:= 'inner x variable'
4. print x
If you then change a to be equal to 3,
a budding programmer might expect b also 5. display()
be equal to 3, but that is not the case. b is still When the above statements are executed the
mapped (or pointing) to the integer value of statement (4) and (5) display the result as
5. The only thing that changed is a, which is
now mapped to the integer value 3.
Output
outer x variable
Mapping after changing the value of a
inner x variable
Above statements give different
a 3 outputs because the same variable name x
resides in different scopes, one inside the
function display() and the other in the upper
level. The value ‘outer xvariable’ is printed
b 5 when x is referenced outside the function
definition. Whereas when display() gets
executed, ‘inner x variable’ is printed which
The scope of a variable is that part of is the x value inside the function definition.
the code where it is visible. Actually, to refer From the above example, we can guess that
to it, you don’t need to use any prefixes then. there is a rule followed, in order to decide
Let’s take an example, from which scope a variable has to be picked.

1. Disp(): The LEGB rule is used to decide the


order in which the scopes are to be searched
www.tntextbooks.org

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

XII Std Computer Science 22

Chapter 3.indd 22 20-02-2019 15:18:40


www.tntextbooks.org

Local(L) Defined inside function/class

Enclosed(E) Defined inside enclosing functions (Nested function concept)

Global(G) Defined at the uppermost level

Built-in (B) Reserved names in built-in functions (modules)

BUILT-IN

GLOBAL

ENCLOSED

LOCAL

3.4 Types of Variable Scope


There are 4 types of Variable Scope, let’s discuss them one by one:
3.4.1 Local Scope
Local scope refers to variables defined in current function. Always, a function will first
look up for a variable name in its local scope. Only if it does not find it there, the outer scopes
are checked.
Look at this example

1. Disp(): Entire program Output of the Program

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

Chapter 3.indd 23 20-02-2019 15:18:40


www.tntextbooks.org

3.4.2 Global Scope


A variable which is declared outside of all the functions in a program is known as global
variable. This means, global variable can be accessed inside or outside of all the functions in a
program. Consider the following example

1. a:=10 Entire program Output of the Program

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

1. Disp(): Entire program Output of the Program

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

XII Std Computer Science 24

Chapter 3.indd 24 20-02-2019 15:18:40


www.tntextbooks.org

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.

Entire program Library files associated

Built in/module scope with the software

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.

3.5 Module independently. The examples of modules are


procedures, subroutines, and functions.
A module is a part of a program.
Programs are composed of one or more 3.5.1 Characteristics of Modules
independently developed modules. A
The following are the desirable
single module can contain one or several
characteristics of a module.
statements closely related each other.
Modules work perfectly on individual level 1. Modules contain instructions, processing
and can be integrated with other modules. logic, and data.
A software program can be divided into
2. Modules can be separately compiled and
modules to ease the job of programming
stored in a library.
and debugging as well. A program can be
divided into small functional modules that 3. Modules can be included in a program.
work together to get the output. The process
4. Module segments can be used by
of subdividing a computer program into
invoking a name and some parameters.
separate sub-programs is called Modular
programming. Modular programming 5. Module segments can be used by other
www.tntextbooks.org

enables programmers to divide up the modules.


work and debug pieces of the program

25 Scoping

Chapter 3.indd 25 20-02-2019 15:18:40


www.tntextbooks.org

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

XII Std Computer Science 26

Chapter 3.indd 26 20-02-2019 15:18:40


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

Chapter 3.indd 27 20-02-2019 15:18:41


www.tntextbooks.org

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

Choose the best answer (1 Mark)


1. Which of the following refers to the visibility of variablesin one part of a program to
another part of the same program.
(A) Scope (B) Memory (C) Address (D) Accessibility
2. The process of binding a variable name with an object is called
(A) Scope (B) Mapping (C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called
(A) Scope (B) Mapping (C) Binding (D) Namespaces
www.tntextbooks.org

5. Which scope refers to variables defined in current function?


(A) Local Scope (B) Global scope
(C) Module scope (D) Function Scope
XII Std Computer Science 28

Chapter 3.indd 28 20-02-2019 15:18:41


www.tntextbooks.org

6. The process of subdividing a computer program into separate sub-programs is called


(A) Procedural Programming (B) Modular programming
(C)Event Driven Programming (D) Object oriented Programming
7. Which of the following security technique that regulates who canuse resources in a
computing environment?
(A) Password (B)Authentication
(C) Access control (D) Certification
8. Which of the following members of a class can be handled only from within the class?
(A) Public members (B)Protected members
(C) Secured members (D) Private members
9. Which members are accessible from outside the class?
(A) Public members (B)Protected members
(C) Secured members (D) Private members
10. The members that are accessible from within the class and are also available to its sub-
classes is called
(A) Public members (B)Protected members
(C) Secured members (D) Private members

Part - II

Answer the following questions (2 Marks)


1. What is a scope?
2. Why scope should be used for variable. State the reason.
3. What is Mapping?
4. What do you mean by Namespaces?
5. How Python represents the private and protected Access specifiers?

Part - III

Answer the following questions (3 Marks)


1. Define Local scope with an example.
www.tntextbooks.org

2. Define Global scope with an example.


3. Define Enclosed scope with an example.

29 Scoping

Chapter 3.indd 29 20-02-2019 15:18:41


www.tntextbooks.org

4. Why access control is required?


5. Identify the scope of the variables in the following pseudo code and write its
output
color:= Red
mycolor():
b:=Blue

myfavcolor():

g:=Green

printcolor, b, g

myfavcolor()

printcolor, b

mycolor()
print color

Part - IV

Answer the following questions (5Marks)


1 Explain the types of scopes for variable or LEGB rule with example.
2. Write any Five Characteristics of Modules.
3. Write any five benefits in using modular programming.

REFERENCES

1. Data Structures and Algorithms in Python By Michael T.Goodrich, RobertoTamassia and


Michael H. Goldwasser.
2. Data Structure and Algorithmic Thinking in Python By Narasimha Karumanchi
3. https://www.python.org
www.tntextbooks.org

XII Std Computer Science 30

Chapter 3.indd 30 20-02-2019 15:18:41


www.tntextbooks.org

CHAPTER 4
Unit I
ALGORITHMIC STRATEGIES

To search an item in a data


Learning Objectives Search structure using linear and
binary search.
At the end of this chapter the students will
be able to: To sort items in a certain
Sort order using the methods such
• Know the basics and technical
as bubble sort, insertion sort,
perspective of algorithms. selection sort, etc.
• Understand the efficiency, time and
Insert To insert an item (s) in a data
space complexity of an algorithm. structure.
• Develop and analyze algorithms for
Update To update an existing item (s)
searching and sorting.
in a data structure.
• Learn about dynamic programming
Delete To delete an existing item (s) in
through algorithmic approach.
a data structure.
4.1 Introduction to Algorithmic
The way of defining an algorithm is
strategies
called algorithmic strategy. For example to
An algorithm is a finite set of calculate factorial for the given value n then
instructions to accomplish a particular task. it can be done by defining the function to
It is a step-by-step procedure for solving calculate factorial once for the iteration-1
a given problem. An algorithm can be then it can be called recursively until the
implemented in any suitable programming number of required iteration is reached.
language.
The word Algorithm comes
Algorithms must have input, from the name of a Persian author,
output and should satisfy the following Abu Jafar Mohammed ibn Musa al
characteristics such as definiteness, Khowarizmi(c. 825 AD(CE)), who
correctness and effectiveness. Data are wrote a textbook on mathematics. The
maintained and manipulated effectively word Algorithm has come to refer to a
through data structures. Algorithms can be method to solve a problem.
developed to store, manipulate and retrieve
www.tntextbooks.org

data from such data structures. Examples 4.1.1Characteristics of an Algorithm


for data structures are arrays, structures, list,
An algorithm should have the
tuples, dictionary etc.
following characteristics:

31

Chapter 4.indd 31 20-02-2019 15:19:14


www.tntextbooks.org

Input Zero or more quantities Independent An algorithm should


to be supplied. have step-by-step
directions, which should
Output At least one quantity is
be independent of any
produced.
programming code.
Finiteness Algorithms must
4.1.2 Writing an Algorithm
terminate after finite
number of steps. Algorithms are generic and not
limited to computer alone. It can be used in
Definiteness All operations should be various real time activities also. Knowingly or
well defined. For example unknowingly we perform many algorithms
operations involving in our daily life such as packing books in
division by zero or school bag, finding shortest path to search
taking square root for a place, scheduling day-to-day activities,
negative number are preparation for examination, etc. As we
unacceptable. know that all programming languages share
Effectiveness Every instruction must basic code constructs like conditions and
be carried out effectively. iterations can be used to write an algorithm.
A typical algorithm is shown in the following
Correctness The algorithms should be Figure 4.1.
error free.
Simplicity Easy to implement.
Unambiguous Algorithm should be
Input Process Output
clear and unambiguous.
Each of its steps and their A Typical Algorithm
inputs/outputs should Example
be clear and must lead to Consider the example of Coffee
only one meaning. preparation. To make coffee, we need to
Feasibility Should be feasible with have the following ingredients: Water, milk,
the available resources. coffee powder and sugar. These ingredients
are the inputs of an algorithm. Preparing a
Portable An algorithm should be cup of coffee is called process. The output of
generic, independent of this process is coffee.
any programming
language or an operating The procedure for preparing coffee is as
system able to handle all follows:
range of inputs.
1. Take a bowl with coffee powder
www.tntextbooks.org

2. Boil the water and pour it into the


bowl

XII Std Computer Science 32

Chapter 4.indd 32 20-02-2019 15:19:14


www.tntextbooks.org

3. Filter it Algorithm Program


4. Boil milk • Algorithm • Program is an
helps to solve a expression of
5. Mix sugar and filtered coffee along
given problem algorithm in a
with boiled milk
logically and programming
6. Pour the coffee into the cup to serve it can be language
contrasted with
This kind of procedure can be
the program
represented using an algorithm. Thus,
the algorithm consists of step-step-by • Algorithm can • Algorithm
instructions that are required to accomplish be categorized can be
a task and helps the programmer to develop based on their implemented
the program. implementation by structured
methods, design or object
Problem: Design an algorithm to find
techniques etc oriented
square of the given number and display the
programming
result.
approach
The algorithm can be written as:
• There is no • Program
Step 1 – start the process
specific rules should be
Step 2 – get the input x for algorithm written for
writing but the selected
Step 3 –calculate the square by
some guidelines language with
multiplying the input value ie.,
should be specific syntax
square ← x* x
followed.
Step 4 − display the result square
• Algorithm • Program
Step 5 − stop resembles a is more
Algorithm could be designed to get pseudo code specific to a
a solution of a given problem. A problem which can be programming
can be solved in many ways. Among many implemented in language
algorithms the optimistic one can be taken any language
for implementation. Table 4.1 Algorithm Vs Program

An algorithm that yields 4.1.3. Analysis of Algorithm


expected output for a valid input Computer resources are limited.
is called an algorithmic solution. Efficiency of an algorithm is defined by the
utilization of time and space complexity.
www.tntextbooks.org

33 Algorithmic Strategies

Chapter 4.indd 33 20-02-2019 15:19:14


www.tntextbooks.org

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

Suppose A is an algorithm and n is Computer resources are limited that


the size of input data, the time and space should be utilized efficiently. The efficiency
used by the algorithm A are the two main of an algorithm is defined as the number
factors, which decide the efficiency of A. of computational resources used by the
algorithm. An algorithm must be analyzed to
Time Factor -Time is measured by
determine its resource usage. The efficiency
counting the number of key
of an algorithm can be measured based on
operations like comparisons
the usage of different resources.
in the sorting algorithm.
Space Factor - Space is measured by the For maximum efficiency of algorithm
www.tntextbooks.org

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,

XII Std Computer Science 34

Chapter 4.indd 34 20-02-2019 15:19:14


www.tntextbooks.org

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.

The efficiency of an algorithm depends To solve a given programming


on how efficiently it uses time and memory problem, many different algorithms may
space. be used. Some of these algorithms may
be extremely time-efficient and others
The time efficiency of an algorithm is
extremely space-efficient.
measured by different factors. For example,
write a program for a defined algorithm, Time/space trade off refers to a
execute it by using any programming situation where you can reduce the use
language, and measure the total time it takes of memory at the cost of slower program
to run. The execution time that you measure execution, or reduce the running time at the
in this case would depend on a number of cost of increased memory usage.
factors such as:
The best algorithm to solve
• Speed of the machine
a given problem is one that
• Compiler and other system Software requires less space in memory

tools and takes less time to execute its
instructions to generate output.
• Operating System

• Programming language used 4.3.3 Asymptotic Notations


Asymptotic Notations are languages
• Volume of data required
that uses meaningful statements about time
However, to determine how and space complexity. The following three
efficiently an algorithm solves a given asymptotic notations are mostly used to
problem, you would like to determine how represent time complexity of algorithms:
the execution time is affected by the nature
(i) Big O
of the algorithm. Therefore, we need to
develop fundamental laws that determine Big O is often used to describe the
the efficiency of a program in terms of the worst-case of an algorithm.
nature of the underlying algorithm.
(ii) Big Ω
Big Omega is the reverse Big O, if
A way of designing algorithm Bi O is used to describe the upper bound
is called algorithmic strategy (worst - case) of a asymptotic function, Big
Omega is used to describe the lower bound
www.tntextbooks.org

(best-case).
4.3.2 Space-Time tradeoff
A space-time or time-memory

35 Algorithmic Strategies

Chapter 4.indd 35 20-02-2019 15:19:14


www.tntextbooks.org

(iii) Big Θ If the element not found then maximum


When an algorithm has a complexity number of comparison =n
with lower bound = upper bound, say that an Therefore, average number of
algorithm has a complexity O (n log n) and comparisons = (n + 1)/2
Ω (n log n), it’s actually has the complexity
Θ (n log n), which means the running time Hence the average case efficiency will
of that algorithm always falls in n log n in be expressed as O (n).
the best-case and worst-case.
4.4 Algorithm for Searching
Techniques
4.3.4 Best, Worst, and Average ease

Ef f i ci enc y 4.4.1 Linear Search
Let us assume a list of n number of Linear search also called sequential
values stored in an array. Suppose if we want search is a sequential method for finding a
to search a particular element in this list, particular value in a list. This method checks
the algorithm that search the key element the search element with each element in
in the list among n elements, by comparing sequence until the desired element is found
the key element with each element in the list or the list is exhausted. In this searching
sequentially. algorithm, list need not be ordered.

The best case would be if the first Pseudo code


element in the list matches with the key 1. Traverse the array using for loop
element to be searched in a list of elements. 2. In every iteration, compare the target
The efficiency in that case would be expressed search key value with the current value
as O(1) because only one comparison is of the list.
enough.
• If the values match, display the current
Similarly, the worst case in this index and value of the array
scenario would be if the complete list is
• If the values do not match, move on to
searched and the element is found only
the next array element.
at the end of the list or is not found in the
list. The efficiency of an algorithm in that 3. If no match is found, display the search
case would be expressed as O(n) because element not found.
n comparisons required to complete the To search the number 25 in the array
search. given below, linear search will go step by
The average case efficiency of an step in a sequential order starting from the
algorithm can be obtained by finding the first element in the given array if the search
average number of comparisons as given element is found that index is returned
below: otherwise the search is continued till the last
www.tntextbooks.org

index of the array. In this example number


Minimum number of comparisons = 1 25 is found at index number 3.
Maximum number of comparisons = n

XII Std Computer Science 36

Chapter 4.indd 36 20-02-2019 15:19:14


www.tntextbooks.org

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)

4.4.2. Binary Search 3. If no match is found for all comparisons,


Binary search also called half-interval then display unsuccessful message.
search algorithm. It finds the position of a
Binary Search Working principles
search element within a sorted array. The
binary search algorithm can be done as List of elements in an array must be
divide-and-conquer search algorithm and sorted first for Binary search. The following
executes in logarithmic time. example describes the step by step operation
of binary search. Consider the following
Pseudo code for Binary search
array of elemnts, the array is being sorted so
1. Start with the middle element: it enables to do the binary search algorithm.
• If the search element is equal to the Let us assume that the search element is 60
middle element of the array i.e., the and we need to search the location or index
middle value = number of elements in of search element 60 using binary search.
array/2, then return the index of the
middle element. 10 20 30 40 50 60 70 80 90 99
0 1 2 3 4 5 6 7 8 9
• If not, then compare the middle element
with the search value, First, we find index of middle element of the
• If the search element is greater than the array by using this formula :
number in the middle index, then select
the elements to the right side of the mid = low + (high - low) / 2
middle index, and go to Step-1.
Here it is, 0 + (9 - 0 ) / 2 = 4 (fractional
• If the search element is less than the part ignored). So, 4 is the mid value of the
number in the middle index, then select array.
the elements to the left side of the middle
index, and start with Step-1.
www.tntextbooks.org

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

Chapter 4.indd 37 20-02-2019 15:19:15


www.tntextbooks.org

Now compare the search element 10 20 30 40 50 60 70 80 90 99


with the value stored at mid value location 0 1 2 3 4 5 6 7 8 9
4. The value stored at location or index 4 is
50, which is not match with search element. We can conclude that the search
As the search value 60 is greater than 50. element 60 is found at lcoation or index 5.
10 20 30 40 50 60 70 80 90 99 For example if we take the search element
0 1 2 3 4 5 6 7 8 9 as 95, For this value this binary search
algorithm return unsuccessful result.
Now we change our low to mid + 1 and find
the new mid value again using the formula. 4.5 Sorting Techniques

low to mid + 1 4.5.1 Bubble sort algorithm

mid = low + (high - low) / 2 Bubble sort is a simple sorting


algorithm. The algorithm starts at the
Our new mid is 7 now. We compare the value beginning of the list of values stored in an
stored at location 7 with our target value 31. array. It compares each pair of adjacent
elements and swaps them if they are in the
10 20 30 40 50 60 70 80 90 99 unsorted order. This comparison and passed
0 1 2 3 4 5 6 7 8 9 to be continued until no swaps are needed,
which indicates that the list of values stored
The value stored at location or index in an array is sorted. The algorithm is a
7 is not a match with search element, rather comparison sort, is named for the way
it is more than what we are looking for. So, smaller elements "bubble" to the top of the
the search element must be in the lower part list. Although the algorithm is simple, it is
from the current mid value location too slow and less efficient when compared
10 20 30 40 50 60 70 80 90 99 to insertion sort and other sorting methods.
0 1 2 3 4 5 6 7 8 9
Assume list is an array of n elements.
The search element still not found. Hence, The swap function swaps the values of the
we calculated the mid again by using the given array elements.
formula.
Pseudo code
high = mid -1
1. Start with the first element i.e., index =
mid = low + (high - low)/2 0, compare the current element with the
Now the mid value is 5. next element of the array.

2. If the current element is greater than the


10 20 30 40 50 60 70 80 90 99 next element of the array, swap them.
0 1 2 3 4 5 6 7 8 9
3. If the current element is less than the
www.tntextbooks.org

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.

XII Std Computer Science 38

Chapter 4.indd 38 20-02-2019 15:19:15


www.tntextbooks.org

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

4.5.2 Selection sort


The selection sort is a simple sorting algorithm that improves on the performance of
bubble sort by making only one exchange for every pass through the list. This algorithm will
first find the smallest elements in array and swap it with the element in the first position of an
array, then it will find the second smallest element and swap that element with the element in
the second position, and it will continue until the entire array is sorted in respective order.

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

Chapter 4.indd 39 20-02-2019 15:19:15


www.tntextbooks.org

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.

Initial At the At the end At the At the end At the


array end First Second end Third Fourth end Fifth
pass pass pass pass pass
13 11 11 11 11
11
16 16 13 13 13 13

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.

After that, next smallest element will 4.5.3 Insertion sort


be searched from an array. Now we will get Insertion sort is a simple sorting
13 as the smallest, so it will be then placed at algorithm. It works by taking elements from
the second position. the list one by one and inserting then in
their correct position in to a new sorted list.
Then leaving the first element, next
This algorithm builds the final sorted array
smallest element will be searched, from
at the end. This algorithm uses n-1 number
the remaining elements. We will get 13 as
of passes to get the final sorted list as per the
the smallest, so it will be then placed at the
pervious algorithm as we have discussed.
second position.
Then leaving 11 and 13 because they Pseudo for Insertion sort
are at the correct position, we will search for Step 1 − If it is the first element, it is already
www.tntextbooks.org

the next smallest element from the rest of sorted.


the elements and put it at third position and
keep doing this until array is sorted. Step 2 − Pick next element

XII Std Computer Science 40

Chapter 4.indd 40 20-02-2019 15:19:15


www.tntextbooks.org

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

expensive function calls and returning


Dynamic programming approaches are
the cached result when the same inputs
used to find the solution in optimized way.
occur again.
For every inner sub problem, dynamic

41 Algorithmic Strategies

Chapter 4.indd 41 20-02-2019 15:19:15


www.tntextbooks.org

4.6.1 Fibonacci Series – An example Initialize f0=0, f1 =1


Fibonacci series generates the
step-1: Print the initial values of Fibonacci
subsequent number by adding two previous
f0 and f1
numbers. Fibonacci series starts from two
numbers − Fib 0 & Fib 1. The initial values step-2: Calculate fibanocci fib ← f0 + f1
of Fib 0 & Fib 1 can be taken as 0 and 1.
step-3: Assign f0← f1, f1← fib
Fibonacci series satisfies the following
conditions : step-4: Print the next consecutive value of
fibanocci fib
Fibn = Fibn-1 + Fibn-2
step-5: Goto step-2 and repeat until the
Hence, a Fibonacci series for the n value 8 specified number of terms generated
can look like this
For example if we generate fibobnacci series
Fib8 = 0 1 1 2 3 5 8 13 upto 10 digits, the algorithm will generate
the series as shown below:
4.6.2 Fibonacci Iterative Algorithm with
Dynamic programming approach The Fibonacci series is : 0 1 1 2 3 5 8 13 21
The following example shows a 34 55
simple Dynamic programming approach
for the generation of Fibonacci series.

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

type the representation of a data type is unknown


• Pair is a compound structure which is made up of list or Tuple

XII Std Computer Science 42

Chapter 4.indd 42 20-02-2019 15:19:15


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

Choose the best answer: (1 Marks)


1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed ibn-i

Musa al Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number of

swaps?
(A) Bubble sort (B) Quick sort (C) Merge sort (D) Selection sort
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The complexity of linear search algorithm is
(A) O(n) (B) O(log n) (C) O(n2) (D) O(n log n)
5. From the following sorting algorithms which has the lowest worst case complexity?
(A) Bubble sort (B) Quick sort (C) Merge sort (D) Selection sort
6. Which of the following is not a stable sorting algorithm?
(A) Insertion sort (B) Selection sort (C) Bubble sort (D) Merge sort
7. Time complexity of bubble sort in best case is
www.tntextbooks.org

(A) θ (n) (B) θ (nlogn) (C) θ (n2) (D) θ (n(logn) 2)

43 Algorithmic Strategies

Chapter 4.indd 43 20-02-2019 15:19:16


www.tntextbooks.org

8. The Θ notation in asymptotic evaluation represents


(A) Base case (B) Average case (C) Worst case (D) NULL case
9. If a problem can be broken into subproblems which are reused several times, the problem
possesses which property?
(A) Overlapping subproblems (B) Optimal substructure
(C) Memoization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is

called ?
(A) Saving value property (B) Storing value property
(C) Memoization (D) Mapping

Part - II

Answer the following questions (2 Marks)

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

Answer the following questions (3 Marks)


1. List the characteristics of an algorithm.
2. Discuss about Algorithmic complexity and its types.
3. What are the factors that influence time and space complexity.
4. Write a note on Asymptotic notation.
5. What do you understand by Dynamic programming?
www.tntextbooks.org

XII Std Computer Science 44

Chapter 4.indd 44 20-02-2019 15:19:16


www.tntextbooks.org

Part - IV

Answer the following questions (5Marks)


1. Explain the characteristics of an algorithm.
2. Discuss about Linear search algorithm.
3. What is Binary search? Discuss with example.
4. Explain the Bubble sort algorithm with example.
5. Explain the concept of Dynamic programming with suitable example.

Reference Books

1. Fundamentals Computer Algorithms, Ellis Horowitz, Sartaj Sahni, Sanguthevar,


Rajasekaran, Second Edition, University press (India) Limited, 2013.
2. Design and Analysis of Algorithms, S. Sridhar, Oxford University Press, 2015

Web References

www.wickipedia.org

CASE STUDY/ STUDENT’S ACTIVITY

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

Chapter 4.indd 45 20-02-2019 15:19:16


www.tntextbooks.org

Why Python in standard XII curriculum?

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

magazine published by the Institute chartered accountants or homemakers, the


of Electrical & Electronics Engineers, style of working has changed drastically.
New York, ranks Python as the top language So as we go, let us accept the change and
for 2018, for the second consecutive year. move towards a brighter day ahead.

python interleaf page.indd 46 20-02-2019 15:53:35


www.tntextbooks.org

CHAPTER 5
Unit II
PYTHON  VARIABLES AND OPERATORS

Learning Objectives

After studying this lesson, students will be able to:


• Appreciate the use of Graphical User Interface (GUI) and Integrated Development
Environment (IDE) for creating Python programs.
• Work in Interactive & Script mode for programming.
• Create and assign values to variables.
• Understand the concept and usage of different data types in Python.
• Appreciate the importance and usage of different types of operators (Arithmetic, Relational
and Logical)
• Creating Python expression (s) and statement (s).

5.1 Introduction

Python is a general purpose


programming language created by Guido
Van Rossum from CWI (Centrum Wiskunde
& Informatica) which is a National Research
Institute for Mathematics and Computer
Science in Netherlands. The language was
released in I991. Python got its name from a
BBC comedy series from seventies- “Monty
Python’s Flying Circus”. Python supports both
Procedural and Object Oriented programming
approaches.

5.2 Key features of Python


 It is a general purpose programming language which can be used for both scientific
www.tntextbooks.org

and non-scientific programming.


 It is a platform independent programming language.
 The programs written in Python are easily readable and understandable.

47

Chapter 5.indd 47 20-02-2019 15:19:39


www.tntextbooks.org

The version 3.x of Python IDLE (Integrated Development Learning Environment)


is used to develop and run Python code. It can be downloaded from the web resource
www.python.org.

5.3 Programming in Python


In Python, programs can be written in two ways namely Interactive mode and Script
mode. The Interactive mode allows us to write codes in Python command prompt (>>>)
whereas in script mode programs can be written and stored as separate file with the extension
.py and executed. Script mode is used to create and edit python source file.

5.3.1 Interactive mode Programming


In interactive mode Python code can be directly typed and the interpreter displays the
result(s) immediately. The interactive mode can also be used as a simple calculator.

(i) Invoking Python IDLE


The following command can be used to invoke Python IDLE from Window OS.

Start → All Programs → Python 3.x → IDLE (Python 3.x)

(Or)

Click python Icon on the Desktop if available.

Now Python IDLE window appears as shown in the Figure 5.1


Menu Bar Tilte Bar

Python prompt (>>>)

Python IDLE Window


The prompt (>>>) indicates that Interpreter is ready to accept instructions. Therefore,
www.tntextbooks.org

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.

XII Std Computer Science 48

Chapter 5.indd 48 20-02-2019 15:19:40


www.tntextbooks.org

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

Python Interactive Window

5.3.2 Script mode Programming


Basically, a script is a text file containing the Python statements. Python Scripts are
reusable code. Once the script is created, it can be executed again and again without retyping.
The Scripts are editable.

(i) Creating Scripts in Python


1. Choose File → New File or press Ctrl + N in Python shell window.
www.tntextbooks.org

49 Python – Variables and Operators

Chapter 5.indd 49 20-02-2019 15:19:40


www.tntextbooks.org

Figure 5.3 – To create new File


2. An untitled blank script text editor will be displayed on screen as shown in Figure 5.3(a)

Figure 5.3(a) Untitled, blank Python script editor


3. Type the following code in Script editor
a =100

b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)
www.tntextbooks.org

Figure 5.4 – Python Sample code



XII Std Computer Science 50

Chapter 5.indd 50 20-02-2019 15:19:40


www.tntextbooks.org

(ii) Saving Python Script


(1) Choose File → Save or Press Ctrl + S

Figure 5.5 – To Save the file First time


(2) Now, Save As dialog box appears on the screen as shown in the Figure 5.6
File Location

File Name (demo1)


www.tntextbooks.org

File Type (Python file (.py))

Figure 5.6 – Save As Dialog Box

51 Python – Variables and Operators

Chapter 5.indd 51 20-02-2019 15:19:40


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)

Figure 5.7 – To Execute Python Script

(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

Figure 5.8 –Python Script Output Window

XII Std Computer Science 52

Chapter 5.indd 52 20-02-2019 15:19:40


www.tntextbooks.org

5.4 Input and Output Functions

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.

5.4.2 input() function


In Python, input( ) function is used to accept data as input at run time. The syntax for
input() function is,
www.tntextbooks.org

Variable = input (“prompt string”)

53 Python – Variables and Operators

Chapter 5.indd 53 20-02-2019 15:19:40


www.tntextbooks.org

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.

Example 1:input( ) with prompt string

>>> city=input (“Enter Your City: ”)


Enter Your City: Madurai
>>> print (“I am from “, city)
I am from Madurai

Example 2:input( ) without prompt string

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

XII Std Computer Science 54

Chapter 5.indd 54 20-02-2019 15:19:40


www.tntextbooks.org

Example 4: Alternate method for the above program


x,y=int (input("Enter Number 1 :")),int(input("Enter Number 2:"))
print ("X = ",x," Y = ",y)
Output:
Enter Number 1 :30
Enter Number 2:50
X = 30 Y = 50

5.5 Comments in Python


In Python, comments begin with hash symbol (#). The lines that begins with # are
considered as comments and ignored by the Python interpreter. Comments may be single line
or no multi-lines. The multiline comments should be enclosed within a set of # as given below.
# It is Single line Comment
# It is multiline comment
which contains more than one line #

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.

55 Python – Variables and Operators

Chapter 5.indd 55 20-02-2019 15:19:40


www.tntextbooks.org

• An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).


• Identifiers may contain digits (0 .. 9)
• Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
• Identifiers must not be a python keyword.
• Python does not allow punctuation character such as %,$, @ etc., within identifiers.

Example of valid identifiers


Sum, total_marks, regno, num1
Example of invalid identifiers
12Name, name$, total-mark, continue

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

false class finally is return

none continue for lambda try

true def from nonlocal while

and del global not with

as elif If or yield

assert else import pass

break except In raise

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

Chapter 5.indd 56 20-02-2019 15:19:40


www.tntextbooks.org

Python supports the following Arithmetic operators.

Operator - Operation Examples Result

Assume a=100 and b=10. Evaluate the following expressions


+ (Addition) >>> a + b 110
- (Subtraction) >>>a – b 90
* (Multiplication) >>> a*b 1000
/ (Divisioin) >>> a / b 10.0
% (Modulus) >>> a % 30 10
** (Exponent) >>> a ** 2 10000
// (Floor Division) >>> a//30 (Integer Division) 3

Program 5.1 To test Arithmetic Operators:


#Demo Program to test Arithmetic Operators
a=100
b=10
print ("The Sum = ",a+b)
print ("The Difference = ",a-b)
print ("The Product = ",a*b)
print ("The Quotient = ",a/b)
print ("The Remainder = ",a%30)
print ("The Exponent = ",a**2)
print ("The Floor Division =",a//30)
#Program End
Output:
The Sum = 110

The Difference = 90
The Product = 1000

The Quotient = 10.0

The Remainder = 10
The Exponent = 10000
The Floor Division = 3

(ii) Relational or Comparative operators


www.tntextbooks.org

A Relational operator is also called as Comparative operator which checks the


relationship between two operands. If the relation is true, it returns True; otherwise it returns
False.

57 Python – Variables and Operators

Chapter 5.indd 57 20-02-2019 15:19:40


www.tntextbooks.org

Python supports following relational operators

Operator - Operation Examples Result


Assume the value of a=100 and b=35. Evaluate the following expressions.
== (is Equal) >>> a==b False
> (Greater than) >>> a > b True
< (Less than) >>> a < b False
>= (Greater than or Equal to) >>> a >= b True
<= (Less than or Equal to) >>> a <= b False
!= (Not equal to) >>> a != b True

Coding 5.2 To test Relational Operators:


#Demo Program to test Relational Operators
a=int (input("Enter a Value for A:"))
b=int (input("Enter a Value for B:"))
print ("A = ",a," and B = ",b)
print ("The a==b = ",a==b)
print ("The a > b = ",a>b)
print ("The a < b = ",a<b)
print ("The a >= b = ",a>=b)
print ("The a <= b = ",a<=0)
print ("The a != b = ",a!=b)
#Program End
Output:
Enter a Value for A:35
Enter a Value for B:56
A = 35 and B = 56
The a==b = False

The a > b = False

The a < b = True

The a >= b = False

The a <= b = False

The a != b = True

www.tntextbooks.org

(iii) Logical operators


In python, Logical operators are used to perform logical operations on the given
relational expressions. There are three logical operators they are and, or and not.

XII Std Computer Science 58

Chapter 5.indd 58 20-02-2019 15:19:40


www.tntextbooks.org

Operator Example Result


Assume a = 97 and b = 35, Evaluate the following Logical expressions
or >>> a>b or a==b True
and >>> a>b and a==b False
not >>> not a>b False i.e. Not True

Program 5.3 To test Logical Operators:

Example – Code Example - Result

#Demo Program to test Logical Operators Enter a Value for A:50


a=int (input("Enter a Value for A:")) Enter a Value for B:40
b=int (input("Enter a Value for B:")) A = 50 and b = 40
print ("A = ",a, " and b = ",b) The a > b or a == b = True
print ("The a > b or a == b = ",a>b or a==b) The a > b and a == b = False
print ("The a > b and a == b = ",a>b and a==b) The not a > b = False
print ("The not a > b = ",not a>b)
#Program End

(iv) Assignment operators


In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and
b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also be given
as a,b=5,10 that assigns the value 5 and 10 on the right to the variables a and b respectively.
There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also
available.

Operator Description Example


Assume x=10
>>> x=10
= Assigns right side operands to left variable
>>> b=”Computer”
Added and assign back the result
+= >>> x+=20 # x=x+20
to left operand i.e. x=30
Subtracted and assign back the
-= >>> x-=5 # x=x-5
result to left operand i.e. x=25
Multiplied and assign back the
*= >>> x*=5 # x=x*5
result to left operand i.e. x=125
Divided and assign back the
www.tntextbooks.org

/= >>> x/=2 # x=x/2


result to left operand i.e. x=62.5

59 Python – Variables and Operators

Chapter 5.indd 59 20-02-2019 15:19:40


www.tntextbooks.org

Taken modulus(Remainder) using two


%= operands and assign the result >>> x%=3 # x=x%3
to left operand i.e. x=2.5
Performed exponential (power) calculation on
**= operators and assign value to the left operand >>> x**=2 # x=x**2
i.e. x=6.25
Performed floor division on operators and
//= >>> x//=3
assign value to the left operand i.e. x=2.0

Program 5.4 To test Assignment Operators:

Program Coding Output

#Demo Program to test Assignment Operators Type a Value for X : 10


x=int (input("Type a Value for X : ")) X = 10
print ("X = ",x) The x is = 10
print ("The x is =",x) The x += 20 is = 30
x+=20 The x -= 5 is = 25
print ("The x += 20 is =",x) The x *= 5 is = 125
x-=5 The x /= 2 is = 62.5
print ("The x -= 5 is = ",x) The x %= 3 is = 2.5
x*=5 The x **= 2 is = 6.25
print ("The x *= 5 is = ",x) The x //= 3 is = 2.0
x/=2
print ("The x /= 2 is = ",x)
x%=3
print ("The x %= 3 is = ",x)
x**=2
print ("The x **= 2 is = ",x)
x//=3
print ("The x //= 3 is = ",x)
#Program End

(v) Conditional operator


Ternary operator is also known as conditional operator that evaluate something based
www.tntextbooks.org

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.

XII Std Computer Science 60

Chapter 5.indd 60 20-02-2019 15:19:40


www.tntextbooks.org

The Syntax conditional operator is,

Variable Name = [on_true] if [Test expression] else [on_false]

Example :

min= 50 if 49<50 else 70 # min = 50


min= 50 if 49>50 else 70 # min = 70

Program 5.5 To test Conditional (Ternary) Operator:


# Program to demonstrate conditional operator
a, b = 30, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print ("The Minimum of A and B is ",min)
# End of the Program

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

(i) Numeric Literals


Numeric Literals consists of digits and are immutable (unchangeable). Numeric literals
can belong to 3 different numerical types Integer, Float and Complex.

61 Python – Variables and Operators

Chapter 5.indd 61 20-02-2019 15:19:40


www.tntextbooks.org

Program 5.6 : To demonstrate Numeric literals


# Program to demonstrate Numeric Literals
a = 0b1010 #Binary Literals


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

(ii) String Literals


In Python a string literal is a sequence of characters surrounded by quotes. Python
supports single, double and triple quotes for a string. A character literal is a single character
surrounded by single or double quotes. The value with triple-quote "' '" is used to give multi-
line string literal.

Program 5.7 To test String Literals


# Demo Program to test String Literals
strings = "This is Python"
char = "C"
multiline_str = "'This is a multiline string with more than one line code."'
print (strings)
print (char)
print (multiline_str)
# End of the Program

Output:
www.tntextbooks.org

This is Python
C
This is a multiline string with more than one line code.

XII Std Computer Science 62

Chapter 5.indd 62 20-02-2019 15:19:41


www.tntextbooks.org

(iii) Boolean Literals


A Boolean literal can have any of the two values: True or False.

Program 5.8 To test Boolean Literals:


# Demo Program to test String Literals
boolean_1 = True
boolean_2 = False
print ("Demo Program for Boolean Literals")
print ("Boolean Value1 :",boolean_1)
print ("Boolean Value2 :",boolean_2)
# End of the Program
Output:
Demo Program for Boolean Literals
Boolean Value1 : True
Boolean Value2 : False

(iv) Escape Sequences


In Python strings, the backslash "\" is a special character, also called the "escape"
character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a
newline, and "\r" is a carriage return. For example to print the message "It's raining", the
Python command is
>>> print ("It\'s rainning")
It's rainning
Python supports the following escape sequence characters.

Escape sequence Description Example Output


character

\\ Backslash >>> print("\\test") \test

\’ Single-quote >>> print("Doesn\'t") Doesn't


\” Double-quote >>> print("\"Python\"") "Python"
\n New line print("Python","\n","Lang..") Python Lang..
\t Tab print("Python","\t","Lang..") Python Lang..
www.tntextbooks.org

5.8 Python Data types


All data values in Python are objects and each object or value has type. Python has Built-
in or Fundamental data types such as Number, String, Boolean, tuples, lists and dictionaries.

63 Python – Variables and Operators

Chapter 5.indd 63 20-02-2019 15:19:41


www.tntextbooks.org

5.8.1 Number Data type


The built-in number objects in Python supports integers, floating point numbers and
complex numbers.
Integer Data can be decimal, octal or hexadecimal. Octal integer use O (both upper
and lower case) to denote octal digits and hexadecimal integer use OX (both upper and lower
case) and L (only upper case) to denote long integer.
Example :
102, 4567, 567 # Decimal integers

O102, o876, O432 # Octal integers


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

5.8.3 String Data type


String data can be enclosed with single quote or double quote or triple quote.

Example :
Char_data = ‘A’
www.tntextbooks.org

String_data= "Computer Science"


Multiline_data= ”””String data can be enclosed with single quote or
double quote or triple quote.”””

XII Std Computer Science 64

Chapter 5.indd 64 20-02-2019 15:19:41


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

65 Python – Variables and Operators

Chapter 5.indd 65 20-02-2019 15:19:41


www.tntextbooks.org

7. Which of the following is not a Keyword in Python ?


A) break B) while
C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational
C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or
C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational
C) Logical D) Assignment

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

1. Describe in detail the procedure Script mode programming.


2. Explain input() and print() functions with examples.
3. Discuss in detail about Tokens in Python

XII Std Computer Science 66

Chapter 5.indd 66 20-02-2019 15:19:41


www.tntextbooks.org

CHAPTER 6
Unit II
CONTROL STRUCTURES

Learning Objectives

After studying this lesson, students will be able to:

• To gain knowledge on the various flow of control in Python language.

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

6.2 Control Structures


A program statement that causes a jump of control from one part of the program to
another is called control structure or control statement. As you have already learnt in C++,
these control statements are compound statements used to alter the control flow of the process
or program depending on the state of the process.
www.tntextbooks.org

67

Chapter 6.indd 67 20-02-2019 15:20:07


www.tntextbooks.org

There are three important control structures

Sequential

Alternative or
Branching

Iterative or Looping

6.2.1 Sequential Statement


A sequential statement is composed of a sequence of statements which are executed
one after another. A code to print your name, address and phone number is an example of
sequential statement.

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

6.2.2 Alternative or Branching Statement


In our day-to-day life we need to take various decisions and choose an alternate path
to achieve our goal. May be we would have taken an alternate route to reach our destination
when we find the usual road by which we travel is blocked. This type of decision making is
what we are to learn through alternative or branching statement. Checking whether the given
number is positive or negative, even or odd can all be done using alternative or branching
statement.

Python provides the following types of alternative or branching statements:


• Simple if statement • if..else statement • if..elif statement
www.tntextbooks.org

(i) Simple if statement


Simple if is the simplest of all decision making statements. Condition should be in the
form of relational or logical expression.

XII Std Computer Science 68

Chapter 6.indd 68 20-02-2019 15:20:07


www.tntextbooks.org

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

Chapter 6.indd 69 20-02-2019 15:20:07


www.tntextbooks.org

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.

Example 6.3: #Program to check if the accepted number odd or even


a = int(input("Enter any number :"))
if a%2==0:
print (a, " is an even number")
else:
print (a, " is an odd number")
Output 1:
Enter any number :56
56 is an even number
Output 2:
Enter any number :67
67 is an odd number

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

XII Std Computer Science 70

Chapter 6.indd 70 20-02-2019 15:20:07


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.

Example 6.4: #Program to check if the accepted number is odd or even


(using alternate method of if...else)
a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
print (a, " is ",x)
Output 1:
Enter any number :3
3 is odd
Output 2:
Enter any number :22
22 is even

(iii) Nested if..elif...else statement:


When we need to construct a chain of if statement(s) then ‘elif ’ clause can be used
instead of ‘else’.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n

In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then


statements-block1 is executed, otherwise the control checks condition-2, if it is true statements-
block2 is executed and even if it fails statements-block n mentioned in else part is executed.
www.tntextbooks.org

71 Control Structures

Chapter 6.indd 71 20-02-2019 15:20:07


www.tntextbooks.org

Test false
Expression
of if

True Test false


Expression
Body of if of elif

True

Body of else
Body of elif

Fig 6.2 if..elif..else statement execution

‘elif ’ clause combines if..else-if..else statements to one if..elif…else. ‘elif ’ can be


considered to be abbreviation of ‘else if ’. In an ‘if ’ statement there is no limit of ‘elif ’ clause
that can be used, but an ‘else’ clause if used should be placed at the end.

Note
if..elif..else statement is similar to nested if statement which you have learnt in C++.

www.tntextbooks.org

XII Std Computer Science 72

Chapter 6.indd 72 20-02-2019 15:20:07


www.tntextbooks.org

Example 6.5: #Program to illustrate the use of nested if statement

Average Grade
>=80 and above A
>=70 and <80 B
>=60 and <70 C
>=50 and <60 D
Otherwise E

m1=int (input(“Enter mark in first subject : ”))


m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : 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

Chapter 6.indd 73 20-02-2019 15:20:08


www.tntextbooks.org

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

6.2.3. Iteration or Looping constructs

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

Python provides two types of looping constructs:


• while loop
• for loop
XII Std Computer Science 74

Chapter 6.indd 74 20-02-2019 15:20:08


www.tntextbooks.org

(i) while loop


The syntax of while loop in Python has the following syntax:

Syntax:
while <condition>:
statements block 1
[else:
statements block2]

while Expression:
Statement (s)
Condition

if conditions is true
if condition is
Conditional Code
false

Fig 6.4 while loop execution


In the while loop, the condition is any valid Boolean expression returning True or
False. The else part of while is optional part of while. The statements block1 is kept executed
till the condition is True. If the else part is written, it is executed when the condition is tested
False. Recall while loop belongs to entry check loop type, that is it is not executed even once if
the condition is tested False in the beginning.

Example 6.6: program to illustrate the use of while loop - to print all numbers
from 10 to 15

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable

Output:
10 11 12 13 14 15
www.tntextbooks.org

75 Control Structures

Chapter 6.indd 75 20-02-2019 15:20:08


www.tntextbooks.org

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

Following is an example for using else part within while loop.

Example 6.7: program to illustrate the use of while loop - with else part

i=10 # intializing part of the control variable


while (i<=15): # test condition
print (i,end='\t') # statements - block 1
i=i+1 # Updation of the control variable
else:
print ("\nValue of i when the loop exit ",i)
Output: 1
10 11 12 13 14 15
Value of i when the loop exit 16

(ii) for loop


for loop is the most comfortable loop. It is also an entry check loop. The condition is
checked in the beginning and the body of the loop(statements-block 1) is executed if it is only
True otherwise the loop is not executed.

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

XII Std Computer Science 76

Chapter 6.indd 76 20-02-2019 15:20:08


www.tntextbooks.org

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.

The syntax of range() is as follows:

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)

for each item


in sequence

Yes
Last item
reached?

No
Body of for

Exit loop
Fig 6.5 for loop execution
www.tntextbooks.org

77 Control Structures

Chapter 6.indd 77 20-02-2019 15:20:08


www.tntextbooks.org

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

Following is an illustration using else part in for loop


Example 6.10 : #program to illustrate the use of for loop - to print single
digit even number with else part
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop

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

Example 6.11: # program to calculate the sum of numbers 1 to 100


n = 100
sum = 0
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum))
Output:
Sum of 1 until 100: 5050
In the above code, n is initialized to 100, sum is initialized to 0, the for loop
starts executing from 1, for every iteration the value of sum is added with the value
www.tntextbooks.org

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)

XII Std Computer Science 78

Chapter 6.indd 78 20-02-2019 15:20:08


www.tntextbooks.org

Note
range () can also take values from string, list, dictionary etc. which will be dealt
in the later chapters.

Following is an example to illustrate the use of string in range()


Example 6.12: program to illustrate the use of string in range() of for loop
for word in 'Computer':
print (word,end=' ')
else:
print ("\nEnd of the loop")

Output
Computer
End of the loop

(iii) Nested loop structure


A loop placed within another loop is called as nested loop structure. One can place a
while within another while; for within another for; for within while and while within for to
construct such nested loops.
Following is an example to illustrate the use of for loop to print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Example 6.13: program to illustrate the use nested loop -for within while loop
i=1
while (i<=6):
for j in range (1,i):
print (j,end='\t')

print (end='\n')
i +=1
www.tntextbooks.org

79 Control Structures

Chapter 6.indd 79 20-02-2019 15:20:08


www.tntextbooks.org

Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

6.2.4 Jump Statements in Python


The jump statement in Python, is used to unconditionally transfer the control from one
part of the program to another. There are three keywords to achieve jump statements in Python
: break, continue, pass. The following flowchart illustrates the use of break and continue.

False
Condition

True else
Statement 1
Statement 1 Statement 2
... ...
break Statementn
...
continue Further
... Statements
Statementn of Program

Fig 6.6 Use of break, continue statement in loop structure

(i) break statement


The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
A while or for loop will iterate till the condition is tested false, but one can even transfer
the control out of the loop (terminate) with help of break statement. When the break statement
is executed, the control flow of the program comes out of the loop and starts executing the
segment of code after the loop structure.
www.tntextbooks.org

If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.

XII Std Computer Science 80

Chapter 6.indd 80 20-02-2019 15:20:08


www.tntextbooks.org

Syntax:
break

Enter loop

false
Condition

true

break?
yes
Exit loop
no
Remaining body of loop

Fig 6.7 Working of break statement

The working of break statement in for loop and while loop is shown below.

for var in sequence:


if condition:
break
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
break

#code inside while loop

#code outside while loop

www.tntextbooks.org

81 Control Structures

Chapter 6.indd 81 20-02-2019 15:20:08


www.tntextbooks.org

Example 6.14: Program to illustrate the use of break statement inside


for loop
for word in “Jump Statement”:
if word = = “e”:
break

print (word, end= ' ')

Output:
Jump Stat

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:

Example 6.15: Program to illustrate the use of break statement inside


for loop
for word in “Jump Statement”:
if word = = “e”:
break

print (word, end=”)

else:
print (“End of the loop”)

print (“\n End of the program”)
Output:
Jump Stat
End of the program

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.

(ii) continue statement


Continue statement unlike the break statement is used to skip the remaining part of a
www.tntextbooks.org

loop and start with next iteration.

XII Std Computer Science 82

Chapter 6.indd 82 20-02-2019 15:20:08


www.tntextbooks.org

Syntax:
continue

Enter loop

Test false
Expression
of loop

true

yes
continue?

Exit loop
no
Remaining body of loop

Fig 6.8 Working of continue statement

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

Chapter 6.indd 83 20-02-2019 15:20:08


www.tntextbooks.org

Example 6.16: Program to illustrate the use of continue statement inside


for loop
for word in “Jump Statement”:
if word = = “e”:
continue

print (word, end=”)

print (“\n End of the program”)
Output:
Jump Statement
End of the program

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.

(iii) pass statement


pass statement in Python programming is a null statement. pass statement when
executed by the interpreter it is completely ignored. Nothing happens when pass is executed,
it results in no operation.
pass statement can be used in ‘if ’ clause as well as within loop construct, when you do
not want any statements or commands within that block to be executed.

Syntax:
pass

Example 6.17: Program to illustrate the use of pass statement


a=int (input(“Enter any number :”))
if (a==0):
pass
else:
print (“non zero value is accepted”)
Output:
Enter any number :3
non zero value is accepted
When the above code is executed if the input value is 0 (zero)
then no action will be performed, for all the other input values the
www.tntextbooks.org

output will be as follows:

XII Std Computer Science 84

Chapter 6.indd 84 20-02-2019 15:20:08


www.tntextbooks.org

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:

• Programs consists of statements which are executed in sequence, to alter the


flow we use control statements.
• A program statement that causes a jump of control from one part of the
program to another is called control structure or control statement.
• Three types of flow of control are
o Sequencing
o Branching or Alternative
o Iteration
• In Python, branching is done using various forms of ‘if ’ structures.
• Indentation plays a vital role in Python programming, it is the indentation
that group statements no need to use {}.
• Python Interpreter will throw error for all indentation errors.
• To accept input at runtime, earlier versions of Python supported raw_input(),
latest versions support input().
• print() supports the use of escape sequence to format the output to the user’s
choice.
• range() is used to supply a range of values in for loop.
www.tntextbooks.org

• break, continue, pass act as jump statements in Python.


• pass statement is a null statement, it is generally used as a place holder.

85 Control Structures

Chapter 6.indd 85 20-02-2019 15:20:08


www.tntextbooks.org

Hands on Experience

1. Write a program to check whether the given character is a vowel or not.

2. Using if..else..elif statement check smallest of three numbers.

3. Write a program to check if a number is Positive, Negative or zero.

4. Write a program to display Fibonacci series 0 1 1 2 3 4 5…… (upto n terms)


5. Write a program to display sum of natural numbers, upto n.
6. Write a program to check if the given number is a palindrome or not.
7. Write a program to print the following pattern
* * * * *
* * * *
* * *
* *
*
8. Write a program to check if the year is leap year or not.

Evaluation

Part - I

Choose the best answer 1 Marks


1. How many important control structures are there in Python?
A) 3 B) 4
C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else
C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control
C) Structure D) Indentation
www.tntextbooks.org

4. Which statement is generally used as a placeholder?


A) continue B) break
C) pass D) goto

XII Std Computer Science 86

Chapter 6.indd 86 20-02-2019 15:20:08


www.tntextbooks.org

5. The condition in the if statement should be in the form of


A) Arithmetic or Relational expression
B) Arithmetic or Logical expression
C) Relational or Logical expression
D) Arithmetic
6. Which is the most comfortable loop?
A) do..while B) while
C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:

break

print(i,end='')

i +=1

A) 12 B) 123
C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:

print(True)
break

A) False B) True
C) 0 D) no output
9. Which amongst this is not a jump statement ?
A) for B) goto
C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1

else:
www.tntextbooks.org

statements-block 2

A) ; B) :
C) :: D) !
87 Control Structures

Chapter 6.indd 87 20-02-2019 15:20:08


www.tntextbooks.org

Part -II

Answer the following questions 2 Marks


1. List the control structures in Python.
2. Write note on break statement.
3. Write is the syntax of if..else statement
4. Define control structure.
5. Write note on range () in loop
Part -III

Answer the following questions 3 Marks


1. Write a program to display
A
A B
A B C
A B C D
A B C D E
2. Write note on if..else structure.
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
4. Write the syntax of while loop.
5. List the differences between break and continue statements.
Part -IV

Answer the following questions 5 Marks


1. Write a detail note on for loop
2. Write a detail note on if..else..elif statement with suitable example.
3. Write a program to display all 3 digit odd numbers.
4. Write a program to display multiplication table for a given number.
www.tntextbooks.org

XII Std Computer Science 88

Chapter 6.indd 88 20-02-2019 15:20:09


www.tntextbooks.org

CHAPTER 7
Unit II
PYTHON FUNCTIONS

Main advantages of functions are


Learning Objectives
• It avoids repetition and makes high degree
of code reusing.
After studying this chapter, students will be
able to: • It provides better modularity for your
application.
• Understand the concept of function and
their types.
Note
• Know the difference between User Functions are nothing but a group
defined and Built in functions. of related statements that perform a
• Know how to call a function. specific task.

• Understand the function arguments. 7.1.1 Types of Functions

• Know Anonymous functions. Basically, we can divide functions


into the following types:
• Know Mathematical and some String
functions. 1 User-defined Functions
2 Built-in Functions
7.1 Introduction Lambda Functions
3
Recursion Functions
Functions are named blocks of code 4

that are designed to do specific job. When


Figure – 7.1 – Types of Python Functions
you want to perform a particular task that
you have defined in a function, you call
Functions Description
the name of the function responsible for it.
If you need to perform that task multiple User-defined Functions defined by
times throughout your program, you don’t functions the users themselves.
need to type all the code for the same task Built-in Functions that are
again and again; you just call the function functions inbuilt with in Python.
dedicated to handling that task, and the Lambda Functions that are
call tells Python to run the code inside the
www.tntextbooks.org

functions anonymous un-named


function. You’ll find that using functions function.
makes your programs easier to write, read,
test, and fix errors.
89

Chapter 7.indd 89 20-02-2019 15:20:32


www.tntextbooks.org

• Any input parameters or arguments


Recursion Functions that calls
functions itself is known as should be placed within these
recursive. parentheses when you define a function.

Table – 7.1 – Python Functions and it's • The code block always comes after a
Description colon (:) and is indented.

Defining Functions • The statement “return [expression]”


7.2
exits a function, optionally passing back
Functions must be defined, to create an expression to the caller. A “return”
and use certain functionality. There are with no arguments is the same as return
many built-in functions that comes with the None.
language python (for instance, the print()
function), but you can also define your own Note
function. When defining functions there are Python keywords should not be used
multiple things that need to be noted; as function name.
• Function blocks begin with the keyword
“def ” followed by function name and
parenthesis ().

7.2.1 Syntax for User defined function

def <function_name ([parameter1, parameter2…] )> : Note


<Block of Statements> In the above Syntax, the Text
return <expression / None> which is given in square
bracket [] is optional.

Block: Nested Block:


A block is one or more lines of A block within a block is called
code, grouped together so that they nested block. When the first block
are treated as one big sequence of statement is indented by a single tab
statements while execution. In Python, space, the second block of statement is
statements in a block are written with indented by double tab spaces.
indentation. Usually, a block begins
when a line is indented (by four Here is an example of defining a function;
spaces) and all the statements of the
Do_Something( ):
block should be at same indent level.
value =1 #Assignment Statement
www.tntextbooks.org

return value #Return Statement

XII Std Computer Science 90

Chapter 7.indd 90 20-02-2019 15:20:33


www.tntextbooks.org

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

7.2.2 Advantages of User-defined Functions


1. Functions help us to divide a program into modules. This makes the code easier to
manage.
2. It implements code reuse. Every time you need to execute a sequence of statements, all
you need to do is to call the function.
3. Functions, allows us to change functionality easily, and different programmers can work
on different functions.
7.3 Calling a Function
To call the hello() function from example 7.2-1, you use this code:
When you call the “hello()” function, the program displays the following string as
output:

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

Chapter 7.indd 91 20-02-2019 15:20:33


www.tntextbooks.org

7.4 Passing Parameters in Functions

Parameters or arguments can be passed to functions

def function_name (parameter(s) separated by comma):

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

7.5 Function Arguments

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

XII Std Computer Science 92

Chapter 7.indd 92 20-02-2019 15:20:33


www.tntextbooks.org

Function Arguments

1 Required arguments

2 Keyword arguments

3 Default arguments

4 Variable-length arguments

7.5.1 Required Arguments


“Required Arguments” are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly with the
function definition. You need atleast one parameter to prevent syntax errors to get the required
output.
Example :
def printstring(str):
print ("Example - Required arguments ")
print (str)
return
# Now you can call printstring() function
printstring()

When the above code is executed, it produces the following error.


Traceback (most recent call last):
File "Req-arg.py", line 10, in <module>
printstring()
TypeError: printstring() missing 1 required positional argument: 'str'

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

Chapter 7.indd 93 20-02-2019 15:20:33


www.tntextbooks.org

7.5.2 Keyword Arguments


Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the parameter
name and so, one can also put arguments in improper order (not in order).
Example:
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
# Now you can call printdata() function
printdata(name = “Gshan”)

When the above code is executed, it produces the following output :

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

When the above code is executed, it produces the following result :

TypeError: printdata() got an unexpected keyword argument 'name1'

Example:
def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
www.tntextbooks.org

# Now you can call printdata() function


printdata (age=25, name="Gshan")

XII Std Computer Science 94

Chapter 7.indd 94 20-02-2019 15:20:33


www.tntextbooks.org

When the above code is executed, it produces the following result:

Output:
Example-3 Keyword arguments
Name : Gshan
Age : 25

Note
In the above program the parameters orders are changed

7.5.3 Default Arguments


In Python the default argument is an argument that takes a default value if no value
is provided in the function call. The following example uses default arguments, that prints
default salary when no argument is passed.

Example:
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)

When the above code is executed, it produces the following output

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

Chapter 7.indd 95 20-02-2019 15:20:33


www.tntextbooks.org

7.5.4 Variable-Length Arguments


In some instances you might need to pass more arguments than have already been
specified. Going back to the function to redefine it can be a tedious process. Variable-Length
arguments can be used instead. These are not specified in the function’s definition and an
asterisk (*) is used to define such arguments.
Lets see what happens when we pass more than 3 arguments in the sum() function.

Example:
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)

When the above code is executed, it produces the following result :

TypeError: sum() takes 3 positional arguments but 5 were given

7.5.4.1 Syntax - Variable-Length Arguments


def function_name(*args):
function_body
return_statement

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.

XII Std Computer Science 96

Chapter 7.indd 96 20-02-2019 15:20:33


www.tntextbooks.org

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.

The Python’s print() function is itself an example of such a function which


supports variable length arguments.

7.6 Anonymous Functions

What is anonymous function?


In Python, anonymous function is a function that is defined without a name. While
normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword. Hence, anonymous functions are also called as lambda
functions.

What is the use of lambda or anonymous function?


• Lambda function is mostly used for creating small and one-time anonymous function.
• Lambda functions are mainly used in combination with the functions like filter(), map()
and reduce().

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

Chapter 7.indd 97 20-02-2019 15:20:33


www.tntextbooks.org

7.6.1 Syntax of Anonymous Functions


The syntax for anonymous functions is as follows:

lambda [argument(s)] :expression Example:


sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10

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

7.7 The return Statement

• 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

return [expression list ]

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

XII Std Computer Science 98

Chapter 7.indd 98 20-02-2019 15:20:33


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.

7.8.1 Local Scope


A variable declared inside the function's body or in the local scope is known as local
variable.
Rules of local variable
• A variable with local scope can be accessed only within the function/block that it is created
in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formate arguments are also local to function.
www.tntextbooks.org

99 Python Functions

Chapter 7.indd 99 20-02-2019 15:20:33


www.tntextbooks.org

Example : Create a Local Variable


def loc():
y=0 # local scope
print(y)
loc()
Output:
0

Example : Accessing local variable outside the scope


def loc():
y = "local"
loc()
print(y)

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.

NameError: name 'y' is not defined

7.8.2 Global Scope


A variable, with global scope can be used anywhere in the program. It can be created by
defining a variable outside the scope of any function/block.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
Example : Accessing global Variable From Inside a Function
c=1 # global variable

def add():
print(c)
www.tntextbooks.org

add()
Output:
1

XII Std Computer Science 100

Chapter 7.indd 100 20-02-2019 15:20:33


www.tntextbooks.org

Example : Accessing global Variable From Inside a Function


c=1 # global variable


def add():
print(c)
add()
Output:
1

Example : Modifying Global Variable From Inside the Function


c=1 # global variable

def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
Unbound Local Error: local variable 'c' referenced before assignment

Note
Without using the global keyword we cannot modify the global variable inside
the function but we can only access the global variable.

Example : Changing Global Variable From Inside a Function using global



keyword
x=0 # global variable

def add():
global x
x=x+5 # increment by 2

print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5
www.tntextbooks.org

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.

101 Python Functions

Chapter 7.indd 101 20-02-2019 15:20:33


www.tntextbooks.org

7.8.3 Global and local variables


Here, we will show how to use global variables and local variables in the same code.
Example : Using Global and Local variables in same code
x=8 # x is a global variable
def loc():
global x
y = "local"
x=x*2
print(x)
print(y)
loc()
Output:
16
local

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.

Example : Global variable and Local variable with same name

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

The output :- local x: 10, is called local scope of variable.


The output:- global x: 5, is called global scope of variable.

XII Std Computer Science 102

Chapter 7.indd 102 20-02-2019 15:20:33


www.tntextbooks.org

7.9 Functions using libraries


7.9.1 Built-in and Mathematical functions

Function Description Syntax Example


abs ( ) Returns an x=20
absolute value y=-23.2
of a number. print('x = ', abs(x))
The argument
print('y = ', abs(y))
may be an abs (x)
integer or a Output:
floating point
x = 20
n u m b e r.
y = 23.2
ord ( ) Returns the c= 'a'
ASCII value d= 'A'
for the given print ('c = ',ord (c))
Unicode ord (c) print ('A = ',ord (d))
character.
This function is Output:
inverse of chr() c = 97
function. A = 65
chr ( ) Returns the c=65
Unicode d=43
character for print (chr (c))
the given ASCII chr (i) prin t(chr (d))
value.
This function is Output:
inverse of ord() A
function. +
bin ( ) Returns a x=15
binary string y=101
prefixed with print ('15 in binary : ',bin (x))
“0b” for the print ('101 in binary : ',bin (y))
given integer bin (i)
number. Output:
Note: format 15 in binary : 0b1111
() can also be 101 in binary : 0b1100101
used instead of
this function.
www.tntextbooks.org

103 Python Functions

Chapter 7.indd 103 20-02-2019 15:20:33


www.tntextbooks.org

type ( ) Returns the x= 15.2


type of object y= 'a'
for the given s= True
single object. print (type (x))
Note: This type (object) print (type (y))
function print (type (s))
used with
single object Output:
parameter. <class 'float'>
<class 'str'>
<class 'bool'>
id ( ) id( ) Return x=15
the “identity” of y='a'
an object. i.e. print ('address of x is :',id (x))
the address of id (object) print ('address of y is :',id (y))
the object in
Output:
memory.
Note: the address of x is : 1357486752
address of x address of y is : 13480736
and y may
differ in your
system.
min ( ) Returns the MyList = [21,76,98,23]
minimum value print ('Minimum of MyList :', min(MyList))
in a list. min (list)
Output:
Minimum of MyList : 21
max ( ) Returns the MyList = [21,76,98,23]
maximum print ('Maximum of MyList :', max(MyList))
value in a list.
max (list) Output:
Maximum of MyList : 98
sum ( ) Returns the MyList = [21,76,98,23]
sum of values print ('Sum of MyList :', sum(MyList))
in a list. sum (list)
Output:
Sum of MyList : 218
www.tntextbooks.org

XII Std Computer Science 104

Chapter 7.indd 104 20-02-2019 15:20:33


www.tntextbooks.org

format ( ) Returns the x= 14


output based y= 25
on the given print ('x value in binary :',format(x,'b'))
format print ('y value in octal :',format(y,'o'))
1. Binary print('y value in Fixed-point no ',format(y,'f '))
format.
Outputs the format (value Output:
number in [, format_ x value in binary : 1110
base 2. spec]) y value in octal : 31
2. Octal y value in Fixed-point no : 25.000000
format.
Outputs the
number in
base 8.
3. Fixed-point
notation.
Displays the
number as a
fixed-point
number.
The default
precision
is 6.
round ( ) Returns the x= 17.9
nearest integer y= 22.2
to its input. z= -18.3
1. First print ('x value is rounded to', round (x))
argument round print ('y value is rounded to', round (y))
(number) (number print ('z value is rounded to', round (z))
is used to [,ndigits])
specify the
value to be
rounded.
www.tntextbooks.org

105 Python Functions

Chapter 7.indd 105 20-02-2019 15:20:33


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.

Function Description Syntax Example


floor ( ) Returns the largest integer math.floor (x) x=26.7
less than or equal to x y=-26.7
z=-23.2
print (math.floor (x))
print (math.floor (y))
print (math.floor (z))
Output:
www.tntextbooks.org

26
-27
-24

XII Std Computer Science 106

Chapter 7.indd 106 20-02-2019 15:20:33


www.tntextbooks.org

ceil ( ) Returns the smallest math.ceil (x) x= 26.7


integer greater than or y= -26.7
equal to x z= -23.2
print (math.ceil (x))
print (math.ceil (y))
print (math.ceil (z))
Output:
27
-26
-23
sqrt ( ) Returns the square root sqrt (x ) a= 30
of x b= 49
Note: x must be greater c= 25.5
than 0 (zero) print (math.sqrt (a))
print (math.sqrt (b))
print (math.sqrt (c))
Output:
5.477225575051661
7.0
5.049752469181039
7.9.2 Composition in functions
What is Composition in functions?
The value returned by a function may be used as an argument for another function in
a nested manner. This is called composition. For example, if we wish to take a numeric value
or an expression as a input from the user, we take the input string from the user using the
function input() and apply eval() function to evaluate its value, for example:
Example :
# This program explains composition
>>> n1 = eval (input ("Enter a number: "))
Enter a number: 234
>>> n1
234
>>> n2 = eval (input ("Enter an arithmetic expression: "))
Enter an arithmetic expression: 12.0+13.0 * 2
>>> n2
38.0

7.10 Python recursive functions


www.tntextbooks.org

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.

107 Python Functions

Chapter 7.indd 107 20-02-2019 15:20:33


www.tntextbooks.org

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.

Overview of how recursive function works


1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue
recursion.
Here is an example of recursive function used to calculate factorial.

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

XII Std Computer Science 108

Chapter 7.indd 108 20-02-2019 15:20:33


www.tntextbooks.org

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

109 Python Functions

Chapter 7.indd 109 20-02-2019 15:20:34


www.tntextbooks.org

Hands on Experience
1. Try the following code in the above program

Slno code Result


1 printinfo(“3500”)
2 printinfo(“3500”,”Sri”)
3 printinfo(name=”balu”)
4 printinfo(“Jose”,1234)
5 printinfo(“ ”,salary=1234)

2. Evaluate the following functions and write the output

Slno Function Output

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)

3. Evaluate the following functions and write the output


Slno function Output
1 1) abs(-25+12.0))
2) abs(-3.2)
2 1) ord('2')
2) ord('$')
3 type('s')
4 bin(16)
5 1) chr(13)
2) print(chr(13))
6 1) round(18.2,1)
2) round(18.2,0)
3) round(0.5100,3)
www.tntextbooks.org

4) round(0.5120,3)

XII Std Computer Science 110

Chapter 7.indd 110 20-02-2019 15:20:34


www.tntextbooks.org

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

6. While defining a function which of the following symbol is used.


(a) ; (semicolon) (b) . (dot)
(c) : (colon) (d) $ (dollar)

111 Python Functions

Chapter 7.indd 111 20-02-2019 15:20:34


www.tntextbooks.org

7. In which arguments the correct positional order is passed to a function?


(a) Required (b) Keyword
(c) Default (d) Variable-length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don’t have to mention the specific data types while defining
function.
(II) Python keywords can be used as function name.
(a) I is correct and II is wrong
(b) Both are correct
(c) I is wrong and II is correct
(d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0
(c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(a) define (b) pass
(c) def (d) while

Part - II

Answer the following questions: (2 Marks)


1. What is function?
2. Write the different types of function.
3. What are the main advantages of function?
4. What is meant by scope of variable? Mention its types.
5. Define global scope.
6. What is base condition in recursive function
7. How to set the limit for recursive function? Give an example.
www.tntextbooks.org

XII Std Computer Science 112

Chapter 7.indd 112 20-02-2019 15:20:34


www.tntextbooks.org

Part - III

Answer the following questions: (3 Marks)


1. Write the rules of local variable.
2. Write the basic rules for global keyword in python.
3. What happens when we modify global variable inside the function?
4. Differentiate ceil() and floor() function?
5. Write a Python code to check whether a given year is leap year or not.
6. What is composition in functions?
7. How recursive function works?
8. What are the points to be noted while defining a function?

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

113 Python Functions

Chapter 7.indd 113 20-02-2019 15:20:34


www.tntextbooks.org

CHAPTER 8
Unit II
STRINGS AND STRING MANIPULATION

Learning Objectives

After completion of this chapter, the student will be able to


• Know how to process text.
• Understanding various string functions in Python.
• Know how to format Strings.
• Know about String Slicing.
• Know about Strings application in real world.

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

‘Welcome to learning Python’


“Welcome to learning Python”
‘‘‘ “Welcome to learning Python” ’’’

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.

XII Std Computer Science 114

Chapter 8.indd 114 20-02-2019 15:20:52


www.tntextbooks.org

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

#A string defined within double quotes


>>>print (“Computer Science”)
Computer Science
#double quoted string defined within double quotes
>>> print (''' "Computer Science" ''')
"Computer Science"
#single and double quoted multiline string defined within triple quotes
>>> print (''' "Strings are immutable in 'Python',
which means you can't make any changes

once you declared" ''')

"Strings are immutable in 'Python',
which means you can't make any changes once you declared"

8.3 Accessing characters in a String


Once you define a string, python allocate an index value for its each character. These
index values are otherwise called as subscript which are used to access and manipulate the
strings. The subscript can be positive or negative integer numbers.

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

115 Strings and String Manipulation

Chapter 8.indd 115 20-02-2019 15:20:52


www.tntextbooks.org

Example 1 : Program to access each character with its positive subscript of


a giving string
str1 = input ("Enter a string: ")
index=0
for i in str1:
print ("Subscript[",index,"] : ", i)
index + = 1
Output
Enter a string: welcome
Subscript [ 0 ] : w
Subscript [ 1 ] : e
Subscript [ 2 ] : l
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e

Example 2 : Program to access each character with its negative subscript of


a giving string
str1 = input ("Enter a string: ")
index=-1
while index >= -(len(str1)):
print ("Subscript[",index,"] : " + str1[index])
index += -1
Output
Enter a string: welcome
Subscript [ -1 ] : e
Subscript [ -2 ] : m
Subscript [ -3 ] : o
Subscript [ -4 ] : c
Subscript [ -5 ] : l
Subscript [ -6 ] : e
Subscript [ -7 ] : w

8.4 Modifying and Deleting Strings


As you already learnt, strings in python are immutable. That means, once you define a
string modifications or deletion is not allowed. If you want to modify the string, a new string
www.tntextbooks.org

value can be assign to the existing string variable.

XII Std Computer Science 116

Chapter 8.indd 116 20-02-2019 15:20:52


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.

117 Strings and String Manipulation

Chapter 8.indd 117 20-02-2019 15:20:53


www.tntextbooks.org

Example 3: Code lines to delete a particular character in a string:

>>> str1="How are you"


>>> del str1[2]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
del str1[2]

TypeError: 'str' object doesn't support item deletion

Example 4: Code lines to delete a string variable

>>> str1="How about you"


>>> print (str1)
How about you
>>> del str1
>>> print (str1)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
print (str1)

NameError: name 'str1' is not defined

8.5 String Operators


Python provides the following operators for string operations. These operators are
useful to manipulate string.
(i) Concatenation (+)
Joining of two or more strings is called as Concatenation. The plus (+) operator is used
to concatenate strings in python.
Example
>>> "welcome" + "Python"
'welcomePython'

(ii) Append (+ =)
Adding more strings at the end of an existing string is known as append. The operator
+= is used to append a new string with an existing string.
www.tntextbooks.org

Example
>>> str1="Welcome to "

XII Std Computer Science 118

Chapter 8.indd 118 20-02-2019 15:20:53


www.tntextbooks.org

>>> str1+="Learn Python"


>>> print (str1)
Welcome to Learn Python

(iii) Repeating (*)
The multiplication operator (*) is used to display a string in multiple number of times.
Example
>>> str1="Welcome "
>>> print (str1*4)
Welcome Welcome Welcome Welcome

(iv) String slicing
Slice is a substring of a main string. A substring can be taken from the original string
by using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing operator.
Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the
string. Python takes the end value less than one from the actual index specified. For example,
if you want to slice first 4 characters from a string, you have to specify it as 0 to 5. Because,
python consider only the end value as n-1.

Example I : slice a single character from a string


>>> str1="THIRUKKURAL"

>>> print (str1[0])


T

Example II : slice a substring from index 0 to 4
>>> print (str1[0:5])
THIRU

Example III : slice a substring using index 0 to 4 but without specifying the beginning

index.
>>> print (str1[:5])
THIRU

www.tntextbooks.org

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

Chapter 8.indd 119 20-02-2019 15:20:53


www.tntextbooks.org

Example V : Program to slice substrings using for loop

str1="COMPUTER"
index=0
for i in str1:
print (str1[:index+1])
index+=1
Output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER

(v) Stride when slicing string


When the slicing operation, you can specify a third argument as the stride, which refers
to the number of characters to move forward after the first character is retrieved from the
string. The default value of stride is 1.

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

Note: Remember that, python takes the last value as n-1


You can also use negative value as stride (third argument). If you specify a negative
value, it prints in reverse order.
www.tntextbooks.org

XII Std Computer Science 120

Chapter 8.indd 120 20-02-2019 15:20:53


www.tntextbooks.org

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

8.7 Formatting characters


Format characters USAGE
%c Character
%d (or) %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer (lower case x refers a-f; upper case X refers
A-F)
%e or %E Exponential notation
%f Floating point numbers
%g or %G Short numbers in floating point or exponential notation.
www.tntextbooks.org

121 Strings and String Manipulation

Chapter 8.indd 121 20-02-2019 15:20:53


www.tntextbooks.org

Escape sequence in python


Escape sequences starts with a backslash and it can be interpreted differently. When
you have use single quote to represent a string, all the single quotes inside the string must be
escaped. Similar is the case with double quotes.

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?"

Escape sequences supported by python


Escape Sequence DESCRIPTION
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Form feed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

8.8 The format( ) function


www.tntextbooks.org

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.

XII Std Computer Science 122

Chapter 8.indd 122 20-02-2019 15:20:53


www.tntextbooks.org

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

8.9 Built-in String functions


Python supports the following built-in functions to manipulate string.

Syntax Description Example


len(str) Returns the length (no of >>> A="Corporation"
characters) of the string. >>> print(len(A))
11
capitalize( ) Used to capitalize the first >>> city="chennai"
character of the string >>> print(city.capitalize())
Chennai
center(width, fillchar) Returns a string with the >>> str1="Welcome"
original string centered to >>> print(str1.center(15,'*') )
a total of width columns ****Welcome****
and filled with fillchar in
columns that do not have
characters
find(sub[, start[, end]]) The function is used to >>>str1=’mammals’
search the first occurrence >>>str1.find(‘ma’)
of the sub string in the 0
given string. It returns On omitting the start parameters,
the index at which the the function starts the search
substring starts. It returns from the beginning.
-1 if the substring does >>>str1.find(‘ma’,2)
not occur in the string. 3
>>>str1.find(‘ma’,2,4)
-1
Displays -1 because the substring
could not be found between the
index 2 and 4-1.
www.tntextbooks.org

>>>str1.find(‘ma’,2,5)
3

123 Strings and String Manipulation

Chapter 8.indd 123 20-02-2019 15:20:53


www.tntextbooks.org

Syntax Description Example


isalnum( ) Returns True if the string >>>str1=’Save Earth’
contains only letters and >>>str1.isalnum()
digit. It returns False. If False
the string contains any The function returns False as space
special character like _, @, is an alphanumeric character.
#, *, etc. >>>’Save1Earth’.isalnum()
True
isalpha( ) Returns True if the string >>>’Click123’.isalpha()
contains only letters. False
Otherwise return False. >>>’python’.isalpha( )
True
isdigit( ) Returns True if the string >>> str1=’Save Earth’
contains only numbers. >>>print(str1.isdigit( ))
Otherwise it returns False. False
lower( ) Returns the exact copy >>>str1=’SAVE EARTH’
of the string with all the >>>print(str1.lower())
letters in lowercase. save earth
islower( ) Returns True if the string >>> str1=’welcome’
is in lowercase. >>>print (str1.islower( ))
True
isupper( ) Returns True if the string >>> str1=’welcome’
is in uppercase. >>>print (str1.isupper( ))
False
upper( ) Returns the exact copy of >>> str1=’welcome’
the string with all letters >>>print (str.upper( ))
in uppercase. WELCOME
title( ) Returns a string in title >>> str1='education department'
case >>> print(str1.title())
Education Department
swapcase( ) It will change case of >>> str1="tAmiL NaDu"
every character to its >>> print(str1.swapcase())
opposite case vice-versa. TaMIl nAdU
www.tntextbooks.org

XII Std Computer Science 124

Chapter 8.indd 124 20-02-2019 15:20:53


www.tntextbooks.org

Syntax Description Example


count(str, beg, end) Returns the number >>> str1="Raja Raja Chozhan"
of substrings occurs >>> print(str1.count('Raja'))
within the given range. 2
Remember that substring >>> print(str1.count('r'))
may be a single character. 0
Range (beg and end) >>> print(str1.count('R'))
arguments are optional. 2
If it is not given, python >>> print(str1.count('a'))
searched in whole string. 5
Search is case sensitive. >>> print(str1.count('a',0,5))
2
>>> print(str1.count('a',11))
1
ord(char ) Returns the ASCII code >>> ch = 'A'
of the character. >>> print(ord(ch))
65
>>> print(ord('B'))
66
chr(ASII) Returns the character >>> ch=97
represented by a ASCII. >>> print(chr(ch))
a
>>> print(chr(87))
W
8.10 Membership Operators
The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is
present in another string. Therefore, these operators are called as Membership Operators.

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

125 Strings and String Manipulation

Chapter 8.indd 125 20-02-2019 15:20:53


www.tntextbooks.org

Example 8.11 Programs using Strings :


Example 8.11.1 : Program to check whether the given string is palindrome


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

Example 8.11.2 : Program to display the following pattern

*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)

i+=1

Output
*
www.tntextbooks.org

* *
* * *
* * * *
* * * * *

XII Std Computer Science 126

Chapter 8.indd 126 20-02-2019 15:20:53


www.tntextbooks.org

Example 8.11.3 : Program to display the number of vowels and consonants


in the given string
str1=input ("Enter a string: ")
str2="aAeEiIoOuU"
v,c=0,0
for i in str1:
if i in str2:
v+=1

else:
c+=1

print ("The given string contains { } vowels and { } consonants".format(v,c))

Output
Enter a string: Tamilnadu School Education
The given string contains 11 vowels and 15 consonants

Example 9: Program to create an Abecedarian series. (Abecedarian refers


list of elements appear in alphabetical order)
str1="ABCDEFGH"
str2="ate"
for i in str1:
print ((i+str2),end='\t')
Output
Aate Bate Cate Date Eate Fate Gate Hate

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

127 Strings and String Manipulation

Chapter 8.indd 127 20-02-2019 15:20:53


www.tntextbooks.org

Example 8.11.5 : Program that count the occurrences of a character in a


string
def count(s, c):
c1=0
for i in s:
if i == c:

c1+=1

return c1
str1=input ("Enter a String: ")
ch=input ("Enter a character to be searched: ")
cnt=count (str1, ch)
print ("The given character {} is occurs {} times in the given string".format(ch,cnt))
Out Put
Enter a String: Software Engineering
Enter a character to be searched: e
The given character e is occurs 3 times in the given string

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

1. Write a python program to find the length of a string.

2. Write a program to count the occurrences of each word in a given string.

XII Std Computer Science 128

Chapter 8.indd 128 20-02-2019 15:20:53


www.tntextbooks.org

3. Write a program to add a prefix text to all the lines in a string.

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

6. Write a program to removes all the occurrences of a give character in a string.

7. Write a program to append a string to another string without using += operator.

8. Write a program to swap two strings.

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

Choose the best answer (1 Mark)


1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau
(c) udanlimaT d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School
(c) Type error (D) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * d) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings
5. Strings in python:
www.tntextbooks.org

(a) Changeable (b) Mutable


(c) Immutable (d) flexible

129 Strings and String Manipulation

Chapter 8.indd 129 20-02-2019 15:20:53


www.tntextbooks.org

6. Which of the following is the slicing operator?


(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation


(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

Answer the following questions (2 Marks)


1. What is String?
2. Do you modify a string in Python?
3. How will you delete a string in Python?
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
5. What is slicing?
Part -III

Answer the following questions (3 Marks)


1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
www.tntextbooks.org

COM
CO
C

XII Std Computer Science 130

Chapter 8.indd 130 20-02-2019 15:20:53


www.tntextbooks.org

2. Write a short about the followings with suitable example:


(a) capitalize( ) (b) swapcase( )
3. What will be the output of the given python program?
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
4. What is the use of format( )? Give an example.
5. Write a note about count( ) function in python.

Part -IV

Answer the following questions (5 Marks)


1. Explain about string operators in python with suitable example.

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

131 Strings and String Manipulation

Chapter 8.indd 131 20-02-2019 15:20:53


www.tntextbooks.org

CHAPTER 9
Unit III
LISTS, TUPLES, SETS AND DICTIONARY

Learning Objectives

After studying this chapter, students will be able to:


• Understand the basic concepts of various collection data types in python such as List,
Tuples, sets and Dictionary.
• Work with List, Tuples, sets and Dictionaries using variety of functions.
• Writting Python programs using List, Tuples, sets and Dictionaries.
• Understand the relationship between List, Tuples and Dictionaries.

9.1 Introduction to List

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

XII Std Computer Science 132

Chapter 9.indd 132 20-02-2019 15:21:14


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.

Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

In the above example, Mylist contains another list as an element. This type of list is
known as “Nested List”.

Nested list is a list containing another list as an element.

9.1.2 Accessing List elements


Python assigns an automatic index value for each element of a list begins with zero.
Index value can be used to access an element in a list. In python, index value is an integer
number which can be positive or negative.

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

133 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 133 20-02-2019 15:21:14


www.tntextbooks.org

Example (Accessing single element):


>>> Marks = [10, 23, 41, 75]
>>> print (Marks[0])
10

In the above example, print command prints 10 as output, as the index of 10 is zero.

Example: Accessing elements in revevrse order


>>> Marks = [10, 23, 41, 75]
>>> print (Marks[-1])
75

Note
A negative index can be used to access an element in reverse order.

(i) Accessing all elements of a list


Loops are used to access all elements from a list. The initial value of the loop must be
zero. Zero is the beginning index value of a list.

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.

XII Std Computer Science 134

Chapter 9.indd 134 20-02-2019 15:21:14


www.tntextbooks.org

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

1 0 0 < 4 True Marks [0] = 10 0+1=1

2 1 1 < 4 True Marks [1] = 23 1+1=2

3 2 2 < 4 True Marks [2] = 41 2+1=3

4 3 3 < 4 True Marks [3] = 75 3+1=4

5 4 4 < 4 False -- --

(ii) Reverse Indexing


Python enables reverse or negative indexing for the list elements. Thus, python lists
index in opposite order. The python sets -1 as the index value for the last element in list and -2
for the preceding element and so on. This is called as Reverse Indexing.

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

135 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 135 20-02-2019 15:21:14


www.tntextbooks.org

Iteration i while i >= -4 print ( Marks[i] ) i = i + -1


1 -1 -1 >= -4 True Marks[-1] = 75 -1 + (-1) = -2
2 -2 -2 >= -4 True Marks[-2] = 41 -2 + (-1) = -3
3 -3 -3 >= -4 True Marks[-3] = 23 -3 + (-1) = -4
4 -4 -4 >= -4 True Marks[-4] = 10 -4 + (-1) = -5
5 -5 -5 >= -4 False -- --

9.1.3 List Length


The len( ) function in Python is used to find the length of a list. (i.e., the number of
elements in a list). Usually, the len( ) function is used to set the upper limit in a loop to read all
the elements of a list. If a list contains another list as an element, len( ) returns that inner list
as a single element.

Example :Accessing single element


>>> MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]
>>> len(MySubject)
4

Example : Program to display elements in a list using loop


MySubject = ["Tamil", "English", "Comp. Science", "Maths"]
i=0
while i < len(MySubject):
print (MySubject[i])
i=i+1
Output
Tamil
English
Comp. Science
Maths

9.1.4 Accessing elements using for loop


In Python, the for loop is used to access all the elements in a list one by one. This is just
like the for keyword in other programming language such as C++.

Syntax:
www.tntextbooks.org

for index_var in list:


print (index_var)

XII Std Computer Science 136

Chapter 9.indd 136 20-02-2019 15:21:14


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

Marks=[23, 45, 67, 78, 98]


for x in Marks:
print( x )
Output
23
45
67
78
98

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

9.1.5 Changing list elements


In Python, the lists are mutable, which means they can be changed. A list element or
range of elements can be changed or altered by using simple assignment operator (=).

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

137 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 137 20-02-2019 15:21:14


www.tntextbooks.org

Example 9.1: Python program to update/change single value


MyList = [2, 4, 5, 8, 10]
print ("MyList elements before update... ")
for x in MyList:
print (x)
MyList[2] = 6
print ("MyList elements after updation... ")
for y in MyList:
print (y)
Output:
MyList elements before update...
2

4

5

8

10

MyList elements after updation...
2

4

6

8

10

Example 9.2: Python program to update/change range of values
MyList = [1, 3, 5, 7, 9]
print ("List Odd numbers... ")
for x in MyList:
print (x)
MyList[0:5] = 2,4,6,8,10
print ("List Even numbers... ")
for y in MyList:
print (y)
Output
List Odd numbers...
1

3

5

7

9

List Even numbers...
2

4
www.tntextbooks.org

6

8

10

XII Std Computer Science 138

Chapter 9.indd 138 20-02-2019 15:21:15


www.tntextbooks.org

9.1.6 Adding more elements in a list Example


In Python, append( ) function is >>> Mylist.extend([71, 32, 29])
used to add a single element and extend(
>>> print(Mylist)
) function is used to add more than one
element to an existing list. [34, 45, 48, 90, 71, 32, 29]

Syntax: In the above code, extend( ) function


List.append (element to be added) is used to include multiple elements, the
List.extend ( [elements to be added]) print statement shows all the elements of
the list after the inclusion of additional
In extend( ) function, multiple elements.
elements should be specified within square 9.1.7 Inserting elements in a list
bracket as arguments of the function.
As you learnt already, append( )
Example function in Python is used to add more
>>> Mylist=[34, 45, 48] elements in a list. But, it includes elements
>>> Mylist.append(90) at the end of a list. If you want to include
>>> print(Mylist) an element at your desired position, you can
[34, 45, 48, 90] use insert ( ) function. The insert( ) function
is used to insert an element at any position
In the above example, Mylist is of a list.
created with three elements. Through >>>
Syntax:
Mylist.append(90) statement, an additional
value 90 is included with the existing list List.insert (position index, element)
as last element, following print statement
shows all the elements within the list MyList.

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.

139 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 139 20-02-2019 15:21:15


www.tntextbooks.org

9.1.8 Deleting elements from a list


There are two ways to delete an element from a list viz. del statement and remove( )
function. del statement is used to delete known elements whereas remove( ) function is used
to delete elements of a list if its index is unknown. The del statement can also be used to delete
entire list.

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.

XII Std Computer Science 140

Chapter 9.indd 140 20-02-2019 15:21:15


www.tntextbooks.org

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

141 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 141 20-02-2019 15:21:15


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.

9.1.9 List and range ( ) function


The range( ) is a function used to generate a series of values in Python. Using range( )
function, you can create list with series of values. The range( ) function has three arguments.

Syntax of range ( ) function:


range (start value, end value, step value)

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

XII Std Computer Science 142

Chapter 9.indd 142 20-02-2019 15:21:15


www.tntextbooks.org

Example : Generating whole numbers upto 10


for x in range (1, 11):
print(x)
Output
1
2
3
4
5
6
7
8
9
10

Example : Generating first 10 even numbers


for x in range (2, 11, 2):
print(x)
Output
2
4
6
8
10

(i) Creating a list with series of values


Using the range( ) function, you can create a list with series of values. To convert the
result of range( ) function into list, we need one more function called list( ). The list( )

function makes the result of range( ) as a list.

Syntax:
List_Varibale = list ( range ( ) )

Note
www.tntextbooks.org

The list ( ) function is all so used to create list in python.

143 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 143 20-02-2019 15:21:15


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.

Example : Generating squares of first 10 natural numbers


squares = [ ]
for x in range(1,11):
s = x ** 2
squares.append(s)
print (squares)

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]

9.1.10 List comprehensions


List comprehension is a simplest way of creating sequence of elements that satisfy a
certain condition.

Syntax:
List = [ expression for variable in range ]

Example : Generating squares of first 10 natural numbers using the


concept of List comprehension

>>> squares = [ x ** 2 for x in range(1,11) ]


>>> print (squares)
www.tntextbooks.org

Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

XII Std Computer Science 144

Chapter 9.indd 144 20-02-2019 15:21:15


www.tntextbooks.org

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.

9.1.11 Other important list funcion

Function Description Syntax Example

MyList=[12, 12, 36]


x = MyList.copy()
Returns a copy of the print(x)
copy ( ) List.copy( )
list
Output:
[12, 12, 36]
MyList=[36 ,12 ,12]
Returns the number x = MyList.count(12)
count ( ) of similar elements List.count(value) print(x)
present in the last. Output:
2
MyList=[36 ,12 ,12]
Returns the index value x = MyList.index(12)
index ( ) of the first recurring List.index(element) print(x)
element Output:
0
MyList=[36 ,23 ,12]
MyList.reverse()
Reverses the order of print(MyList)
reverse ( ) List.reverse( )
the element in the list.
Output:
[12 ,23 ,36]

sort ( ) Sorts the element in list List.sort(reverse=True|False, key=myFunc)

MyList=['Thilothamma', 'Tharani', 'Anitha',


Both arguments are optional 'SaiSree', 'Lavanya']
• If reverse is set as True, list sorting MyList.sort( )
is in descending order. print(MyList)
• Ascending is default. MyList.sort(reverse=True)
• Key=myFunc; “myFunc” - the name print(MyList)
of the user defined function that
specifies the sorting criteria. Output:
['Anitha', 'Lavanya', 'SaiSree', 'Tharani',
Note: sort( ) will affect the original list. 'Thilothamma']
www.tntextbooks.org

['Thilothamma', 'Tharani', 'SaiSree', 'Lavanya',


'Anitha']

145 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 145 20-02-2019 15:21:15


www.tntextbooks.org

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

Program 1: write a program that creates a list of numbers from 1 to 20


that are divisible by 4
divBy4=[ ]
for i in range(21):
if (i%4==0):
divBy4.append(i)

print(divBy4)
Output
[0, 4, 8, 12, 16, 20]

Program 2: Write a program to define a list of countries that are a member of


BRICS. Check whether a county is member of BRICS or not
country=["India", "Russia", "Srilanka", "China", "Brazil"]
is_member = input("Enter the name of the country: ")
if is_member in country:
print(is_member, " is the member of BRICS")
else:
print(is_member, " is not a member of BRICS")
Output
Enter the name of the country: India
India is the member of BRICS
www.tntextbooks.org

Output
Enter the name of the country: Japan
Japan is not a member of BRICS

XII Std Computer Science 146

Chapter 9.indd 146 20-02-2019 15:21:15


www.tntextbooks.org

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

Program 4: Python program to read prices of 5 items in a list and then


display sum of all the prices, product of all the prices and find the average

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

print("Average of all prices = Rs.",sum(items)/len(items))

147 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 147 20-02-2019 15:21:15


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

Program 5: Python program to count the number of employees earning


more than 1 lakh per annum. The monthly salaries of n number of
employees are given

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

XII Std Computer Science 148

Chapter 9.indd 148 20-02-2019 15:21:15


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

Program 6: Write a program to create a list of numbers in the range 1 to 10.


Then delete all the even numbers from the list and print the final list.
Num = []
for x in range(1,11):
Num.append(x)
print("The list of numbers from 1 to 10 = ", Num)

for index, i in enumerate(Num):


if(i%2==0):
del Num[index]

print("The list after deleting even numbers = ", Num)

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

149 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 149 20-02-2019 15:21:15


www.tntextbooks.org

Program 7: Write a program to generate in the Fibonacci series and store it


in a list. Then find the sum of all values.
a=-1
b=1
n=int(input("Enter no. of terms: "))
i=0
sum=0
Fibo=[]
while i<n:
s=a+b
Fibo.append(s)
sum+=s
a=b
b=s
i+=1
print("Fibonacci series upto "+ str(n) +" terms is : " + str(Fibo))
print("The sum of Fibonacci series: ",sum)
Output
Enter no. of terms: 10
Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The sum of Fibonacci series: 88

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.

3. Iterating tuples is faster than list.

XII Std Computer Science 150

Chapter 9.indd 150 20-02-2019 15:21:15


www.tntextbooks.org

9.2.2 Creating Tuples


Creating tuples is similar to list. In a list, elements are defined within square brackets,
whereas in tuples, they may be enclosed by parenthesis. The elements of a tuple can be even
defined without parenthesis. Whether the elements defined within parenthesis or without
parenthesis, there is no differente in it's function.

Syntax:
# Empty tuple
Tuple_Name = ( )

# Tuple with n number elements


Tuple_Name = (E1, E2, E2 ……. En)

# Elements of a tuple without parenthesis


Tuple_Name = E1, E2, E3 ….. En

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

Chapter 9.indd 151 20-02-2019 15:21:15


www.tntextbooks.org

Note
Type ( ) function is used to know the data type of a python object.

(ii) Creating Single element tuple


While creating a tuple with a single element, add a comma at the end of the element.
In the absence of a comma, Python will consider the element as an ordinary data type; not a
tuple. Creating a Tuple with one element is called “Singleton” tuple.

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

Chapter 9.indd 152 20-02-2019 15:21:15


www.tntextbooks.org

9.2.4 Update and Delete Tuple


As you know a tuple is immutable, the elements in a tuple cannot be changed. Instead of
altering values in a tuple, joining two tuples or deleting the entire tuple is possible.

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)

To delete an entire tuple, the del command can be used.

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.

9.2.5 Tuple Assignment


www.tntextbooks.org

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

153 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 153 20-02-2019 15:21:15


www.tntextbooks.org

operator. Each value is assigned to its respective variable.

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.

9.2.6 Returning multiple values in Tuples


A function can return only one value at a time, but Python returns more than one value
from a function. Python groups multiple values and returns them together.

Example : Program to return the maximum as well as minimum values in



a list
def Min_Max(n):
a = max(n)
b = min(n)
return(a, b)
Num = (12, 65, 84, 1, 18, 85, 99)
(Max_Num, Min_Num) = Min_Max(Num)
print("Maximum value = ", Max_Num)
print("Minimum value = ", Min_Num)

Output:
Maximum value = 99
www.tntextbooks.org

Minimum value = 1

XII Std Computer Science 154

Chapter 9.indd 154 20-02-2019 15:21:15


www.tntextbooks.org

9.2.7 Nested Tuples


In Python, a tuple can be defined inside another tuple; called Nested tuple. In a nested
tuple, each tuple is considered as an element. The for loop will be useful to access all the
elements in a nested tuple.

Example

Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5),


("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8))

for i in Toppers:
print(i)

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.

9.2.8 Programs using Tuples

Program 1: Write a program to swap two values using tuple assignment

a = int(input("Enter value of A: "))


b = int(input("Enter value of B: "))
print("Value of A = ", a, "\n Value of B = ", b)
(a, b) = (b, a)
print("Value of A = ", a, "\n Value of B = ", b)

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

155 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 155 20-02-2019 15:21:15


www.tntextbooks.org

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

Numbers = (5, -8, 6, 8, -4, 3, 1)


Positive = ( )
for i in Numbers:
if i > 0:
Positive += (i, )

print("Positive Numbers: ", Positive)

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.

XII Std Computer Science 156

Chapter 9.indd 156 20-02-2019 15:21:15


www.tntextbooks.org

9.3.1 Creating a Set


A set is created by placing all the elements separated by comma within a pair of curly
brackets. The set( ) function can also used to create sets in Python.

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.

9.3.2 Creating Set using List or Tuple


A list or Tuple can be converted as set by using set( ) function. This is very simple
procedure. First you have to create a list or Tuple then, substitute its variable within set( )
function as argument.

Example

MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)
www.tntextbooks.org

Output:
{2, 4, 6, 8, 10}

157 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 157 20-02-2019 15:21:15


www.tntextbooks.org

9.3.3 Set Operations


As you learnt in mathematics, the python is also supports the set operations such as
Union, Intersection, difference and Symmetric difference.

(i) Union: It includes all elements from two or more sets

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.

Example: Program to Join (Union) two sets using union operator

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'}

Example: Program to Join (Union) two sets using union function

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

{'D', 2, 4, 6, 8, 'B', 'C', 'A'}

XII Std Computer Science 158

Chapter 9.indd 158 20-02-2019 15:21:15


www.tntextbooks.org

(ii) Intersection: It includes the common elements in two sets

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.

Example: Program to insect two sets using intersection operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)

Output:
{'A', 'D'}

Example: Program to insect two sets using intersection function

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))

Output:
{'A', 'D'}
www.tntextbooks.org

159 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 159 20-02-2019 15:21:16


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.

Example: Program to difference of two sets using minus operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)

Output:
{2, 4}

Example: Program to difference of two sets using difference function

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference(set_B))

Output:
{2, 4}
www.tntextbooks.org

XII Std Computer Science 160

Chapter 9.indd 160 20-02-2019 15:21:16


www.tntextbooks.org

(iv) Symmetric difference


It includes all the elements that are in two sets (say sets A and B) but not the one that are
common to two sets.

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.

Example: Program to symmetric difference of two sets using caret operator

set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)

Output:
{2, 4, 'B', 'C'}

Example: Program to difference of two sets using symmetric difference


function

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

161 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 161 20-02-2019 15:21:16


www.tntextbooks.org

9.3.4 Programs using Sets


Program 1: Program that generate a set of prime numbers and another set of even
numbers. Demonstrate the result of union, intersection, difference and symmetirc
difference operations.

Example

even=set([x*2 for x in range(1,11)])


primes=set()
for i in range(2,20):
j=2
f=0
while j<i/2:
if i%j==0:

f=1

j+=1

if f==0:
primes.add(i)

print("Even Numbers: ", even)
print("Prime Numbers: ", primes)
print("Union: ", even.union(primes))
print("Intersection: ", even.intersection(primes))
print("Difference: ", even.difference(primes))
print("Symmetric Difference: ", even.symmetric_difference(primes))
Output:
Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Prime Numbers: {2, 3, 4, 5, 7, 11, 13, 17, 19}
Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
Intersection: {2, 4}
Difference: {6, 8, 10, 12, 14, 16, 18, 20}
Symmetric Difference: {3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}

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

XII Std Computer Science 162

Chapter 9.indd 162 20-02-2019 15:21:16


www.tntextbooks.org

Syntax of defining a dictionary:


Dictionary_Name = { Key_1: Value_1,
Key_2:Value_2,


……..


Key_n:Value_n


}

Key in the dictionary must be unique case sensitive and can be of any valid Python type.

9.4.1 Creating a Dictionary


# Empty dictionary
Dict1 = { }

# Dictionary with Key


Dict_Stud = { RollNo: 1234, Name:Murali, Class:XII, Marks:451}

9.4.2 Dictionary Comprehensions


In Python, comprehension is another way of creating dictionary. The following is the
syntax of creating such dictionary.

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

Dict = { x : 2 * x for x in range(1,10)}


Output of the above code is
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

9.4.3 Accessing, Adding, Modifying and Deleting elements from a Dictionary


Accessing all elements from a dictionary is very similar as Lists and Tuples. Simple print
function is used to access all the elements. If you want to access a particular element, square
www.tntextbooks.org

brackets can be used along with key.

163 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 163 20-02-2019 15:21:16


www.tntextbooks.org

Example : Program to access all the values stored in a dictionary


MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',

'School' : 'CGHSS',

'Address' : 'Rotler St., Chennai 112' }

print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
Output:
{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
School: CGHSS
Address: Rotler St., Chennai 112

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

Example : Program to add a new value in the dictionary


MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',

'School' : 'CGHSS', 'Address' : '

Rotler St., Chennai 112'}

print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value

print("Class: ", MyDict['Class']) # Printing newly added value

print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

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

Chapter 9.indd 164 20-02-2019 15:21:16


www.tntextbooks.org

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

Example : Program to delete elements from a dictionary and finally deletes


the dictionary.

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

9.4.4 Difference between List and Dictionary


(1) List is an ordered set of elements. But, a dictionary is a data structure that is used for
matching one element (Key) with another (Value).

(2) The index values can be used to access a particular element. But, in dictionary key
www.tntextbooks.org

represents index. Remember that, key may be a number of a string.

(3) Lists are used to look up a value whereas a dictionary is used to take one value and look
up another value.

165 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 165 20-02-2019 15:21:16


www.tntextbooks.org

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

1. Write a program to remove duplicates from a list.

2. Write a program that prints the maximum value in a Tuple.

3. Write a program that finds the sum of all the numbers in a Tuples using while loop.
www.tntextbooks.org

4. Write a program that finds sum of all even numbers in a list.

XII Std Computer Science 166

Chapter 9.indd 166 20-02-2019 15:21:16


www.tntextbooks.org

5. Write a program that reverse a list using a loop.

6. Write a program to insert a value in a list at the specified location.

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

Choose the best answer (1 Marks)


1. Pick odd one in connection with collection data type
(a) List (b) Tuple (c) Dictionary (d) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(a) 10 (b) 8 (c) 4 (d) 6
3. Which of the following function is used to count the number of elements in a list?
(a) count() (b) find() (c)len() (d) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result
(a) [35,10,20,30,40,50] (b) [10,20,30,40,50,35]
(c) [10,20,35,40,50] (d) [10,35,30,40,50]
5. If List=[17,23,41,10] then List.append(32) will result
(a) [32,17,23,41,10] (b) [17,23,41,10,32]

(c) [10,17,23,32,41] (d) [41,32,23,17,10]

6. Which of the following Python function can be used to add more than one element
within an existing list?
www.tntextbooks.org

(a) append() (b) append_more() (c)extend() (d) more()


7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]

167 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 167 20-02-2019 15:21:16


www.tntextbooks.org

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

Answer the following questions (2 Marks)


1. What is List in Python?
2. How will you access the list elements in reverse order?
3. What will be the value of x in following python code?
List1=[2,4,6[1,3,5]]
www.tntextbooks.org

x=len(List1)
4. Differentiate del with remove( ) function of List.

XII Std Computer Science 168

Chapter 9.indd 168 20-02-2019 15:21:16


www.tntextbooks.org

5. Write the syntax of creating a Tuple with n number of elements.


6. What is set in Python?

Part - III

Answer the following questions (3 Marks)


1. What are the advantages of Tuples over a list?
2. Write a shot note about sort( ).
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
4. Explain the difference between del and clear( ) in dictionary with an example.
5. List out the set operations supported by python.
6. What are the difference between List and Dictionary?

Part - IV

Answer the following questions (5 Marks)


1. What the different ways to insert an element in a list. Explain with suitable example.
2. What is the purpose of range( )? Explain with an example.
3. What is nested tuple? Explain with an example.
4. Explain the different set operations supported by python with suitable example.

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

169 Lists, Tuples, Sets and Dictionary

Chapter 9.indd 169 20-02-2019 15:21:16


www.tntextbooks.org

CHAPTER 10
Unit III
PYTHON CLASSES AND OBJECTS

Learning Objectives

After the completion of this chapter, the student is able to

• Understand the fundamental concepts of Object Oriented Programming like: Classes,


Objects, Constructor and Destructor.

• Gain the knowledge of creating classes and objects in Python.

• Create classes with Constructors.

• Write complex programs in Python using classes.

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

XII Std Computer Science 170

Chapter 10.indd 170 20-02-2019 15:21:36


www.tntextbooks.org

Where, statement in a class definition may be a variable declaration, decision control,


loop or even a function definition. Variables defined inside a class are called as “Class Variable”
and functions are called as “Methods”. Class variable and methods are together known as
members of the class. The class members should be accessed through objects or instance of
class. A class can be defined anywhere in a Python program.
Example: Program to define a class
class Sample:
x, y = 10, 20 # class variables


In the above code, name of the class is Sample and it has two variables x and y having
the initial value 10 and 20 respectively. To access the values defined inside the class, you need
an object or instance of the class.

10.3 Creating Objects


Once a class is created, next you should create an object or instance
of that class. The process of creating object is called as “Class Instantiation”.

Syntax:
Object_name = class_name( )

Note that the class instantiation uses function notation ie. class_name with

10.4 Accessing Class Members


Any class member ie. class variable or method (function) can be accessed by using
object with a dot ( . ) operator.
Syntax:
Object_name . class_member

Example : Program to define a class and access its member variables


class Sample:
#class variables
x, y = 10, 20
S=Sample( ) # class instantiation

print("Value of x = ", S.x)
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)
Output :
www.tntextbooks.org

Value of x = 10
Value of y = 20
Value of x and y = 30

171 Python Classes and Objects

Chapter 10.indd 171 20-02-2019 15:21:36


www.tntextbooks.org

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.

10.5 Class Methods


Python class function or Method is very similar to ordinary function with a small
difference that, the class method must have the first argument named as self. No need to pass
a value for this argument when we call the method. Python provides its value automatically.
Even if a method takes no arguments, it should be defined with the first argument called self.
If a method is defined to accept only one argument it will take it as two arguments ie. self and
the defined argument.
When you declare class variable within class, methods must be prefixed by the class
name and dot operator.

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.

XII Std Computer Science 172

Chapter 10.indd 172 20-02-2019 15:21:36


www.tntextbooks.org

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

Example : program to check and print if the given number is odd or



even using class

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

10.6 Constructor and Destructor in Python

Constructor is the special function that is automatically executed when an object of a


class is created. In Python, there is a special function called “init” which act as a Constructor.
It must begin and end with double underscore. This function will act as an ordinary function;
www.tntextbooks.org

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.

173 Python Classes and Objects

Chapter 10.indd 173 20-02-2019 15:21:36


www.tntextbooks.org

General format of __init__ method (Constructor function)


def __init__(self, [args ……..]):
<statements>

Example : Program to illustrate Constructor


class Sample:
def __init__(self, num):
print("Constructor of class Sample...")

self.num=num

print("The value is :", num)

S=Sample(10)

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.

Constructor of class Sample...



The value is : 10

Class variable defined within constructor keep count of number of objects created with
the class.

Example : Program to illustrate class variable to keep count of number



of objects created.
class Sample:
num=0
def __init__(self, var):
Sample.num+=1

self.var=var

print("The object value is = ", var)

print("The count of object created = ", Sample.num)

S1=Sample(15)
www.tntextbooks.org

S2=Sample(35)
S3=Sample(45)

XII Std Computer Science 174

Chapter 10.indd 174 20-02-2019 15:21:36


www.tntextbooks.org

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)

10.7 Public and Private Data Members

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

175 Python Classes and Objects

Chapter 10.indd 175 20-02-2019 15:21:36


www.tntextbooks.org

Example : Program to illustrate private and public variables


class Sample:
def __init__(self, n1, n2):
self.n1=n1

self.__n2=n2

def display(self):
print("Class variable 1 = ", self.n1)

print("Class variable 2 = ", self.__n2)

S=Sample(12, 14)
S.display()
print("Value 1 = ", S.n1)
print("Value 2 = ", S.__n2)

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

Traceback (most recent call last):


File "D:/Python/Class-Test-04.py", line 12, in <module>

print("Value 2 = ", S.__n2)

AttributeError: 'Sample' object has no attribute '__n2'
www.tntextbooks.org

XII Std Computer Science 176

Chapter 10.indd 176 20-02-2019 15:21:36


www.tntextbooks.org

10.8 Sample Programs to illustrate classes and objects

Program 1: Write a program to calculate area and circumference of a circle


class Circle:
pi=3.14
def __init__(self,radius):
self.radius=radius
def area(self):
return Circle.pi*(self.radius**2)
def circumference(self):
return 2*Circle.pi*self.radius
r=int(input("Enter Radius: "))
C=Circle(r)
print("The Area =",C.area())
print("The Circumference =", C.circumference())

Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002

Program 2: write a menu driven program that keeps record of books


available in you school library

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

177 Python Classes and Objects

Chapter 10.indd 177 20-02-2019 15:21:36


www.tntextbooks.org

book=[] #empty list


ch = 'y'
while(ch=='y'):
print("1. Add New Book \n 2.Display Books")
resp = int(input("Enter your choice : "))

if(resp==1):
L=Library()
L.getdata()
book.append(L)
elif(resp==2):
for x in book:
x.display()

else:
print("Invalid input....")

ch = input("Do you want continue....")

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

1. Add New Book


2.Display Books
Enter your choice : 1
Enter Name of the Book: Learn Python
Enter Author of the Book: V.G.Ramakrishnan
Do you want continue....y
www.tntextbooks.org

XII Std Computer Science 178

Chapter 10.indd 178 20-02-2019 15:21:36


www.tntextbooks.org

1. Add New Book


2.Display Books
Enter your choice : 1
Enter Name of the Book: Advanced Python
Enter Author of the Book: Dr. Vidhya
Do you want continue....y
1. Add New Book
2.Display Books
Enter your choice : 1
Enter Name of the Book: Working with OpenOffice
Enter Author of the Book: N.V.Gowrisankar
Do you want continue....y
1. Add New Book
2.Display Books
Enter your choice : 1
Enter Name of the Book: Data Structure
Enter Author of the Book: K.Lenin
Do you want continue....y
1. Add New Book
2.Display Books
Enter your choice : 1
Enter Name of the Book: An Introduction to Database System
Enter Author of the Book: R.Sreenivasan
Do you want continue....y
1. Add New Book
2.Display Books
www.tntextbooks.org

179 Python Classes and Objects

Chapter 10.indd 179 20-02-2019 15:21:36


www.tntextbooks.org

Enter your choice : 2


Name of the Book: Programming in C++
Author of the Book: K. Kannan

Name of the Book: Learn Python


Author of the Book: V.G.Ramakrishnan

Name of the Book: Advanced Python


Author of the Book: Dr. Vidhya

Name of the Book: Working with OpenOffice


Author of the Book: N.V.Gowrisankar

Name of the Book: Data Structure


Author of the Book: K.Lenin

Name of the Book: An Introduction to Database System


Author of the Book: R.Sreenivasan

Do you want continue....n

Program 3: Write a program to accept a string and print the number of


uppercase, lowercase, vowels, consonants and spaces in the given string

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

XII Std Computer Science 180

Chapter 10.indd 180 20-02-2019 15:21:36


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

181 Python Classes and Objects

Chapter 10.indd 181 20-02-2019 15:21:36


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

XII Std Computer Science 182

Chapter 10.indd 182 20-02-2019 15:21:36


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]

print(" Invoice Receipt ")




print("-----------------------------------------------------------------------------")
print("Product Code\t Product Name\t Cost Price\t Quantity \t Total Amount")
print("-----------------------------------------------------------------------------")
for x in range(self.p):
print(self.__prod_code[x], "\t\t", self.__prod_name[x], "\t\t",

self.__cost_price[x], "\t\t", self.__prod_quant[x], "\t\t",

self.__prod_quant[x]*self.__cost_price[x])

print("-----------------------------------------------------------------------------")
print(" Total Amount = ", total_price)

www.tntextbooks.org

183 Python Classes and Objects

Chapter 10.indd 183 20-02-2019 15:21:36


www.tntextbooks.org

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

XII Std Computer Science 184

Chapter 10.indd 184 20-02-2019 15:21:36


www.tntextbooks.org

Enter the quantify for the product code 101 : 10


Enter the quantify for the product code 201 : 15
Enter the quantify for the product code 301 : 10
Enter the quantify for the product code 401 : 20
Enter the quantify for the product code 501 : 10

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

• Python is an Object Oriented Programming language.


• Classes and Objects are the key features of Object Oriented Programming.
• In Python, a class is defined by using the keyword class.
• Variables defined inside a class is called as “Class Variable” and function are
called as “Methods”.
• The process of creating object is called as “Class Instantiation”.
• Constructor is the special function that is automatically executed when an
object of a class is created.
• In Python, there is a special function called “init” is used as Constructor.
• Destructor is also a special method gets execution automatically when an
object exits from the scope.
• In Python, __del__( ) method is used as destructor.
• A variable prefixed with double underscore is becomes private in nature.
www.tntextbooks.org

185 Python Classes and Objects

Chapter 10.indd 185 20-02-2019 15:21:36


www.tntextbooks.org

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

Choose the best answer (1 Marks)


1. Which of the following are the key features of an Object Oriented Programming language?
(a) Constructor and Classes (b) Constructor and Object
(c) Classes and Objects (d) Constructor and Destructor
2. Functions defined inside a class:
(a) Functions (b) Module
(c) Methods (d) section
3. Class members are accessed through which operator?
(a) & (b) .
(c) # (d) %
4. Which of the following method is automatically executed when an object is created?
(a) __object__( ) (b) __del__( )
(c) __func__( ) (d) __init__( )
5. A private class variable is prefixed with
(a) __ (b) &&
(c) ## (d) **
6. Which of the following method is used as destructor?
(a) __init__( ) (b) __dest__( )
www.tntextbooks.org

(c) __rem__( ) (d) __del__( )

XII Std Computer Science 186

Chapter 10.indd 186 20-02-2019 15:21:36


www.tntextbooks.org

7. Which of the following class declaration is correct?


(a) class class_name (b) class class_name<>
(c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:

def __init__(self, name):

self.name=name

S=Student(“Tamil”)

(a) Error (b) Tamil
(c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num
(c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor
(c) Initialize (d) Instantiation

Part -II

Answer the following questions (2 Marks)

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

5. What is the purpose of Destructor?

187 Python Classes and Objects

Chapter 10.indd 187 20-02-2019 15:21:37


www.tntextbooks.org

Part -III

Answer the following questions (3 Marks)


1. What are class members? How do you define it?
2. Write a class with two private class variables and print the sum using a method.
3. Find the error in the following program to get the given output?
class Fruits:

def __init__(self, f1, f2):

self.f1=f1

self.f2=f2

def display(self):

print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))

F = Fruits ('Apple', 'Mango')

del F.display

F.display()

Output
Fruit 1 = Apple, Fruit 2 = Mango

4. What is the output of the following program?
class Greeting:

def __init__(self, name):

self.__name = name

def display(self):

print("Good Morning ", self.__name)

obj=Greeting('Bindu Madhavan')

obj.display()

5. How do define constructor and destructor in Python?
Part -IV

Answer the following questions (5 Marks)


1. Write a menu driven program to add or delete stationary items. You should use dictionary
to store items and the brand.

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.

XII Std Computer Science 188

Chapter 10.indd 188 20-02-2019 15:21:37


www.tntextbooks.org

CHAPTER 11
Unit IV
DATABASE CONCEPTS

Example : 600006, DPI Campus, SCERT,


Learning Objectives Chennai, College Road

At the completion of this chapter, the student 11.2 Information


will be able to know Information is formatted data, which
• the concept of a database and relational allows to be utilized in a significant way.
database. Example
• different components of the database. SCERT
• types of database models. College Road
DPI Campus
• types of relationship.
Chennai 600006
• the concepts of relational algebra.
As you can see
Introduction from the example above, data appears as a set
A database is an organized collection of words and numbers. However, when the
of data, generally stored and accessed data is processed, organized and formatted,
it gives a meaningful information about the
electronically from a computer system. The
SCERT institution contact address.
term "database" is also used to refer to any
of the DBMS, the database system or an 11.3 Database
application associated with the database.
Database is a repository collection of
Because of the close relationship between related data organized in a way that data can
them, the term "database" is often used be easily accessed, managed and updated.
casually to refer to both a database and Database can be a software or hardware
the DBMS used to manipulate it. A school based, with one sole purpose of storing data.
class register is a database where names are
11.4 DataBase Management
arranged alphabetically. Databases have
System (DBMS)
been around since people started recording
things. Here we tend to focus on electronic A DBMS is a software that allows us
ones. to create, define and manipulate database,
11.1 Data allowing users to store, process and analyze
data easily. DBMS provides us with an
Data are raw facts stored in a interface or a tool, to perform various
www.tntextbooks.org

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

Chapter 11.indd 189 20-02-2019 15:22:46


www.tntextbooks.org

databases. It also maintains data consistency in case of multiple users.

Examples of DBMS softwares are : Foxpro, dbase.

11.4.1 Characteristics of Database Management System


1. Data stored into Tables Data is never directly stored into the database. Data is stored
into tables, created inside the database. DBMS also allows to
have relationship between tables which makes the data more
meaningful and connected.

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.

3.Data Consistency On live data, it is being continuously updated and added,


maintaining the consistency of data can become a challenge.
But DBMS handles it by itself.

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.

11.4.2 Advantages of DBMS


• Segregation of application program
• Minimal data duplication or Data Redundancy
• Easy retrieval of data using the Query Language
www.tntextbooks.org

• Reduced development time and maintenance

XII Std Computer Science 190

Chapter 11.indd 190 20-02-2019 15:22:47


www.tntextbooks.org

11.4.3 Components of DBMS 3. Data: It is that resource for which DBMS


The Database Management System is designed. DBMS creation is to store and
can be divided into five major components utilize data.
as follows: 4. Procedures/Methods: They are general
1.Hardware instructions to use a database management

2.Software 3.Data system such as installation of DBMS,

manage databases to take backups, report
4.Procedures/Methods
generation, etc.
5.Database Access Languages
5. DataBase Access Languages: They are
the languages used to write commands to
access, insert, update and delete data stored
in any database.
Hardware Examples of popular DBMS: Dbase,
FoxPro

Software 11.5 Database Structure

Procedures Table is the entire collection of


Data Base related data in one table, referred to as a File
Access / Methods
or Table where the data is organized as row
DATA

Languages and column.


USER
Each row in a table represents a
Components of DBMS
record, which is a set of data for each
Figure 11.1 database entry.

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

191 Database Concepts

Chapter 11.indd 191 20-02-2019 15:22:47


www.tntextbooks.org

Attribute / Column Tuple / Row

StuNo StuName StuAge StuClass StuSec


1101 Kannan 14 9 A
1102 Ramakrishnan 14 9 A
1103 Vidhya 14 10 B
1104 Britto 15 9 A
1105 Padmaja 14 10 B

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.

11.6.1 Types of Data Model


Following are the different types of a Data Model

• 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

XII Std Computer Science 192

Chapter 11.indd 192 20-02-2019 15:22:47


www.tntextbooks.org

School

Course Resources

Theory Lab

Hierarchical Model Fig. 11.3

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

Stu_id Name Age Subj_id Name Teacher


1 Malar 17 1 C++ Kannan
2 Suncar 16 2 Php Ramakrishnan
3 Velu 16 3 Python Vidhya

Stu_id Subj_id Marks


1 1 92
1 2 89
3 2 96
Relational Model
Fig. 11.4

3. Network Model
Network database model is an extended form of hierarchical data model. The difference
www.tntextbooks.org

between hierarchical and Network data model is :


• In hierarchical model, a child record has only one parent node,

193 Database Concepts

Chapter 11.indd 193 20-02-2019 15:22:47


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

Student Student has 3 parent node

Network Model
Fig. 11.5

School represents the parent node


Library, Office and Staff room is a child to school (parent node)
Student is a child to library, office and staff room (one to many relationship)
4. Entity Relationship Model. (ER model)
In this database model, relationship are created by dividing the object into entity and its
characteristics into attributes.
It was developed by Chen in 1976. This model is useful in developing a conceptual
design for the database. It is very simple and easy to design logical view of data. The developer
can easily understand the system by looking at ER model constructed.
Rectangle represents the entities. E.g. Doctor and Patient
Ellipse represents the attributes E.g. D-id, D-name, P-id, P-name. Attributes describes
the characteristics and each entity becomes a major part of the data stored in the database.

Diamond represents the relationship in ER diagrams

E.g. Doctor diagnosis the Patient


www.tntextbooks.org

XII Std Computer Science 194

Chapter 11.indd 194 20-02-2019 15:22:47


www.tntextbooks.org

Doctor Diagnosis Patient

D-id D-Name P-id P-Name


ER model
Fig. 11.6

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

Circle Rectangle Triangle


Radius Length Base
breath Height
Object Model
Fig. 11.7

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.

11.6.2 Types of DBMS Users


Database Administrators
Database Administrator or DBA is the one who manages the complete database
www.tntextbooks.org

management system. DBA takes care of the security of the DBMS, managing the license keys,
managing user accounts and access etc.

195 Database Concepts

Chapter 11.indd 195 20-02-2019 15:22:47


www.tntextbooks.org

Application Programmers or Software Developers


This user group is involved in developing and designing the parts of DBMS.
End User
All modern applications, web or mobile, store user data. Applications are programmed
in such a way that they collect user data and store the data on DBMS systems running on their
server. End users are the one who store, retrieve, update and delete data.
Database designers: are responsible for identifying the data to be stored in the database for
choosing appropriate structures to represent and store the data.

11.7 Difference between DBMS and RDBMS

Basis of Comparison DBMS RDBMS

Expansion Database Management System Relational DataBase


Management System

Data storage Navigational model Relational model (in tables).


ie data by linked records ie data in tables as row and
column

Data redundancy Exhibit Not Present

Normalization Not performed RDBMS uses normalization


to reduce redundancy

Data access Consumes more time Faster, compared to DBMS.

Keys and indexes Does not use. used to establish


relationship. Keys are used in
RDBMS.

Transaction Inefficient, Efficient and secure.


management Error prone and insecure.

Distributed Databases Not supported Supported by RDBMS.

Example Dbase, FoxPro. SQL server, Oracle, mysql,


MariaDB, SQLite.

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.

XII Std Computer Science 196

Chapter 11.indd 196 20-02-2019 15:22:47


www.tntextbooks.org

11.8 Types of Relationships staff members.

Following are the types of relationships used Staff


in a database. Department

1. One-to-One Relationship Gajalakshmi

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

For example: A student can have only


one exam number One to Many Mapping
Fig 11.9
Student Exam No
3. Many-to-One Relationship
In Many-to-One Relationship, many
entities can be related with only one in the
Tamilselvi 1001 other entity.
For example: A number of staff
Jayapandiyan 1002 members working in one Department.
Multiple rows in staff members table
Sarojini 1003 is related with only one row in Department
table.
Staff Department

One to one Relationships


Fig 11.8
Suganya
Computer
2. One-to-Many Relationship
Bala
In One-to-Many relationship, one Maths
entity is related to many other entities. Valarmathi
One row in a table A is linked to
www.tntextbooks.org

many rows in a table B, but one row in a


table B is linked to only one row in table A. Many to one Relationship
For example: One Department has many Fig 11.10

197 Database Concepts

Chapter 11.indd 197 20-02-2019 15:22:47


www.tntextbooks.org

4. Many-to-Many Relationship 11.9 Relational Algebra in DBMS


A many-to-many relationship
occurs when multiple records in a table are What is Relational Algebra?
associated with multiple records in another Relational Algebra, was first created
table. by Edgar F Codd while at IBM. It was used
for modeling the data stored in relational
Example 1: Customers and Product
databases and defining queries on it.
Customers can purchase various
products and Products can be purchased by Relational Algebra is a procedural
many customers query language used to query the database
tables using SQL.
Example 2: Students and Courses
Relational algebra operations are
A student can register for many
performed recursively on a relation (table)
Courses and a Course may include many
to yield an output. The output of these
stu d e nt s
operations is a new relation, which might be
Example 3: Books and Student. formed by one or more input relations.
Many Books in a Library are issued
Relational Algebra is divided into various
to many students.
groups
Book Student
Unary Relational Operations
SELECT ( symbol : σ)
C++ Kalaivani
PROJECT ( symbol : ∏)

SQL Manjula Relational Algebra Operations from Set


Theor y
python Sridevi
• UNION (∪)
• INTERSECTION (∩)
Many to Many Relationship • DIFFERENCE (−)
Fig 11.11
• CARTESIAN PRODUCT (X)
SELECT (symbol : σ)
The relational model
was invented by Edgar General form σ ( R ) with a relation
c
Frank Codd (Father of R and a condition C on the attributes of R.
Relational DataBase) as The SELECT operation is used for
a general model of data, and selecting a subset with tuples according to a
www.tntextbooks.org

subsequently promoted by Chris Date given condition.


and Hugh Darwen among others.
Select filters out all tuples that do not
satisfy C.

XII Std Computer Science 198

Chapter 11.indd 198 20-02-2019 15:22:47


www.tntextbooks.org

STUDENT

Studno Name Course Year

cs1 Kannan Big Data II

cs2 Gowri Shankar R language I

cs3 Lenin Big Data I

cs4 Padmaja Python Programming I

Table 11.1

σcourse = “Big Data” (STUDENT )

Studno Name Course Year

cs1 Kannan Big Data II

cs3 Lenin Big Data I

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.

Example 1 using Table 11.1


Πcourse (STUDENT)
Result

Course

Big Data

R language

Python Programming

Note
duplicate row is removed in the result
www.tntextbooks.org

199 Database Concepts

Chapter 11.indd 199 20-02-2019 15:22:47


www.tntextbooks.org

Example 2 (using Table 11.1)


Πstudno, course (STUDENT)
Result
Studno Course
cs1 Big Data
cs2 R language
cs3 Big Data
cs4 Python Programming

UNION (Symbol :∪)


It includes all tuples that are in tables A or in B. It also eliminates duplicates. Set A
Union Set B would be expressed as A ∪ B
Example 3
Consider the following tables

Table A Table B

Studno Name Studno Name

cs1 Kannan cs1 Kannan

cs3 Lenin cs2 GowriShankarn

cs4 Padmaja cs3 Lenin


Table 11.2
Result
Table A ∪ B
Studno Name
cs1 Kannan
cs2 GowriShankar
cs3 Lenin
cs4 Padmaja

SET DIFFERENCE ( Symbol : - )


The result of A – B, is a relation which includes all tuples that are in A but not in B.
www.tntextbooks.org

The attribute name of A has to match with the attribute name in B.


Example 4 ( using Table 11.2)

XII Std Computer Science 200

Chapter 11.indd 200 20-02-2019 15:22:47


www.tntextbooks.org

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.

Example 5 (using Table 11.2)

A∩B
cs1 Kannan
cs3 Lenin

PRODUCT OR CARTESIAN PRODUCT (Symbol : X )


Cross product is a way of combining two relations. The resulting relation contains, both
relations being combined.

A x B means A times B, where the relation A and B have different attributes.


This type of operation is helpful to merge columns from two relations.
Table A Table B Table A x Table B

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

cs2 Gowri Shankar cs62 R language


cs4 Padmaja cs25 python programming
Table 11.3

201 Database Concepts

Chapter 11.indd 201 20-02-2019 15:22:48


www.tntextbooks.org

Cartesian product : Table A x Table B


studno name course subject
cs1 Kannan cs28 Big Data
cs1 Kannan cs62 R language
cs1 Kannan cs25 python rogramming
cs2 Gowri Shankar cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs2 Gowri Shankar cs25 python programming
cs4 Padmaja cs28 Big Data
cs4 Padmaja cs62 R language
cs4 Padmaja cs25 python programming

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

• ER model consists of entities, attributes and relationships

XII Std Computer Science 202

Chapter 11.indd 202 20-02-2019 15:22:48


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

Choose the best answer (1 Marks)


1. What is the acronym of DBMS?
a) DataBase Management Symbol b) Database Managing System
c) DataBase Management System d) DataBasic Management System
2 A table is known as
a) tuple b) attribute
c) relation d)entity
3 Which database model represents parent-child relationship?
a) Relational b) Network
c) Hierarchical d) Object
4 Relational database model was first proposed by
a) E F Codd b) E E Codd
c) E F Cadd d) E F Codder
5 What type of relationship does hierarchical model represents?
a) one-to-one b) one-to-many
c) many-to-one d) many-to-many
www.tntextbooks.org

6. Who is called Father of Relational Database from the following?


a) Chris Date b)Hugh Darween
c) Edgar Frank Codd d) Edgar Frank Cadd

203 Database Concepts

Chapter 11.indd 203 20-02-2019 15:22:48


www.tntextbooks.org

7. Which of the following is an RDBMS?


a) Dbase b) Foxpro
c) Microsoft Access d) SQLite
8 What symbol is used for SELECT statement?
a) σ b) Π c) X d) Ω

9 A tuple is also known as
a) table b) row
c) attribute d) field
10. Who developed ER model?
a) Chen b) EF Codd
c) Chend d) Chand

Part - B

Answer the following questions (2 Marks)


1. Mention few examples of a database.
2. List some examples of RDBMS.
3. What is data consistency?
4. What is the difference between Hierarchical and Network data model?
5. What is normalization?
Part -C

Answer the following questions (3 Marks)


1. What is the difference between Select and Project command?
2. What is the role of DBA?
3. Explain Cartesian Product with a suitable example.
4. Explain Object Model with example.
5. Write a note on different types of DBMS users.
Part -D

Answer the following questions (5 Marks)


1. Explain the different types of data model.
2. Explain the different types of relationship mapping.
www.tntextbooks.org

3. Differentiate DBMS and RDBMS.


4. Explain the different operators in Relational algebra with suitable examples.
5. Explain the characteristics of DBMS.

XII Std Computer Science 204

Chapter 11.indd 204 20-02-2019 15:22:48


www.tntextbooks.org

CHAPTER 12
Unit IV
STRUCTURED QUERY LANGUAGE

Learning Objectives

After studying this lesson, students will be able to:


• The processing skills of SQL.
• The components of SQL.
• To create a table by specifying the fields and records.
• To apply various manipulations like inserting, updating and deleting records in a table.
• To learn about various constraints and to apply it on tables.
• To generate queries in the table by applying various clauses.
• To modify the structure of an existing table.
• The commands to delete records, table and revoke the commands.

12.1 Introduction to SQL

The Structured Query Language (SQL) is a standard programming language to access


and manipulate databases. SQL allows the user to create, retrieve, alter, and transfer information
among databases. It is a language designed for managing and accessing data in a Relational
Data Base Management System (RDBMS).
There are many versions of SQL. The original version was developed at IBM’s Research
centre and originally called as Sequel in early 1970’s. Later the language was changed to SQL.
In 1986, ANSI (American National Standard Institute) published an SQL standard that was
updated again in 1992, the latest SQL was released in 2008 and named as SQL 2008.

Note
Latest SQL standard as of now is SQL 2008, released in 2008.

12.2 Role of SQL in RDBMS


www.tntextbooks.org

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

Chapter 12.indd 205 20-02-2019 15:30:40


www.tntextbooks.org

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.

12.3 Processing Skills of SQL


The various processing skills of SQL are :
1. Data Definition Language (DDL) : The SQL DDL provides commands for defining
relation schemas (structure), deleting relations, creating indexes and modifying relation
schemas.
2. Data Manipulation Language (DML) : The SQL DML includes commands to insert,
delete, and modify tuples in the database.
3. Embedded Data Manipulation Language : The embedded form of SQL is used in high
level programming languages.
4. View Definition : The SQL also includes commands for defining views of tables.
5. Authorization : The SQL includes commands for access rights to relations and views of
tables.
6. Integrity : The SQL provides forms for integrity checking using condition.
7. Transaction control : The SQL includes commands for file transactions and control over
transaction processing.

SQL-Structured Query Language is a language used for accessing databases while


MySQL is a database management system, like SQL Server, Oracle, Informix,
www.tntextbooks.org

Postgres, etc. MySQL is a RDBMS.

Refer installing MYSQL in Annexure -1

XII
XII Std
Std Computer
Computer Science
Science 206

Chapter 12.indd 206 20-02-2019 15:30:40


www.tntextbooks.org

12.4 Creating Database

1. To create a database, type the following command in the prompt:


CREATE DATABASE database_name;
For example to create a database to store the tables:
CREATE DATABASE stud;
2. To work with the database, type the following command.
USE DATABASE;
For example to use the stud database created, give the command
USE stud;

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.

12.5 Components of SQL

SQL commands are divided into five categories:

DML - Data Manipulation Language

DDL - Data Definition Language

DCL - Data Control Language

TCL - Transaction Control Language

DQL - Data Query Language

12.5.1 DATA DEFINITION LANGUAGE

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.

207 Structured Query Language

Chapter 12.indd 207 20-02-2019 15:30:40


www.tntextbooks.org

A DDL performs the following functions :

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.

Alter Alters the structure of the database.

Drop Delete tables from database.

Truncate Remove all records from a table, also release the space occupied by those records.

12.5.2 DATA MANIPULATION LANGUAGE


A Data Manipulation Language (DML) is a computer programming language used
for adding (inserting), removing (deleting), and modifying (updating) data in a database.
In SQL, the data manipulation language comprises the SQL-data change statements, which
modify stored data but not the schema of the database table.
After the database schema has been specified and the database has been created, the
data can be manipulated using a set of procedures which are expressed by DML.

By Data Manipulation we mean,


• Insertion of new information into the database
• Retrieval of information stored in a database.
• Deletion of information from the database.
• Modification of data stored in the database.

The DML is basically of two types:


Procedural DML – Requires a user to specify what data is needed and how to get it.
www.tntextbooks.org

Non-Procedural DML - Requires a user to specify what data is needed without


specifying how to get it.

XII
XII Std
Std Computer
Computer Science
Science 208

Chapter 12.indd 208 20-02-2019 15:30:40


www.tntextbooks.org

SQL commands which comes under Data Manipulation Language are :

Insert Inserts data into a table

Update Updates the existing data within a table.

Delete Deletes all records from a table, but not the space occupied by them.

12.5.3 DATA CONTROL LANGUAGE


A Data Control Language (DCL) is a programming language used to control
the access of data stored in a database. It is used for controlling privileges in the database
(Authorization). The privileges are required for performing all the database operations such as
creating sequences, views of tables etc.

SQL commands which come under Data Control Language are:

Grant Grants permission to one or more users to perform specific tasks.

Revoke Withdraws the access permission given by the GRANT statement.

12.5.4 TRANSACTIONAL CONTROL LANGUAGE


Transactional control language (TCL) commands are used to manage transactions
in the database. These are used to manage the changes made to the data in a table by DML
statements.
SQL command which come under Transfer Control Language are:

Commit Saves any transaction into the database permanently.

Roll back Restores the database to last commit state.

Save point Temporarily save a transaction so that you can rollback.

12.5.5 DATA QUERY LANGUAGE


The Data Query Language consist of commands used to query or retrieve data from a
database. One such SQL command in Data Query Language is
Select : It displays the records from the table.

12.6 Data Types

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.

209 Structured Query Language

Chapter 12.indd 209 20-02-2019 15:30:40


www.tntextbooks.org

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 represents a floating point number in base 10 exponential notation and


float
may define a precision up to a maximum of 64.

It is same as float, except the size argument is not used and may define a
real
precision up to a maximum of 64.

double Same as real except the precision may exceed 64.


Table 12.1
12.7 SQL Commands and their Functions

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

Chapter 12.indd 210 20-02-2019 15:30:40


www.tntextbooks.org

Arguments They are the values given to make the clause complete.

12.7.1 DDL Commands


CREATE TABLE Command
You can create a table by using the CREATE TABLE command. When a table is created,
its columns are named, data types and sizes are to be specified. Each table must have at least
one column. The syntax of CREATE TABLE command is :

CREATE TABLE <table-name>


(<column name><data type>[<size>]
(<column name><data type>[<size>]……
);

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.

Column constraint: Column constraint apply only to individual column.


www.tntextbooks.org

Table constraint : Table constraint apply to a group of one or more columns.

211 Structured Query Language

Chapter 12.indd 211 20-02-2019 15:30:40


www.tntextbooks.org

The syntax for a table created with constraint is given as below:

CREATE TABLE <table-name>


(<column name><data type>[<size>]<column constraint>,
(<column name><data type>[<size>]<column constraint>……
<table constraint>(<column name>,[<column name>….])…..
);

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

Chapter 12.indd 212 20-02-2019 15:30:40


www.tntextbooks.org

CREATE TABLE Student


(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL,
Gender char (1),
Age integer,
Place char (10),
);

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.

(ii) Primary Key Constraint


This constraint declares a field as a Primary key which helps to uniquely identify a
record. It is similar to unique constraint except that only one field of a table can be set as
primary key. The primary key does not allow NULL values and therefore a field declared as
primary key must have the NOT NULL constraint.
Example showing Primary Key Constraint in the student table:

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

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.

213 Structured Query Language

Chapter 12.indd 213 20-02-2019 15:30:40


www.tntextbooks.org

Example showing DEFAULT Constraint in the student table:

CREATE TABLE Student


(
Admno integer NOT NULL PRIMARY KEY,
Name char(20)NOT NULL,
Gender char(1),
Age integer DEFAULT = “17”, → Default Constraint
Place char(10),
);

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.

(v) TABLE CONSTRAINT


When the constraint is applied to a group of fields of the table, it is known as Table
constraint. The table constraint is normally given at the end of the table definition. Let us take
a new table namely Student1 with the following fields Admno, Firstname, Lastname, Gender,
Age, Place:
www.tntextbooks.org

XII
XII Std
Std Computer
Computer Science
Science 214

Chapter 12.indd 214 20-02-2019 15:30:40


www.tntextbooks.org

CREATE TABLE Student 1


(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1),
Age integer,
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
In the above example, the two fields, Firstname and Lastname are defined as Primary
key which is a Table constraint.
12.7.3 DML COMMANDS
Once the schema or structure of the table is created, values can be added to the table.
The DML commands consist of inserting, deleting and updating rows into the table.

(i) INSERT command


The INSERT command helps to add new data to the database or add new records to the
table. The command is used as follows:
INSERT INTO <table-name> [column-list] VALUES (values);

INSERT INTO Student (Admno, Name, Gender, Age, Place)


VALUES (100,’ Ashish’,’ M’, 17,’ Chennai’);
INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (102, ‘Adarsh’, ‘M’, 18, ‘Delhi’);
Two new records are added to the table as shown below:
Admno Name Gender Age Placee
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi

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:

215 Structured Query Language

Chapter 12.indd 215 20-02-2019 15:30:40


www.tntextbooks.org

INSERT INTO Student(Admno, Name, Place) VALUES (103, ‘Ayush’, ‘Delhi’);


103 Ayush M 18 Delhi
The above command adds the following record with default values of ‘M’ for Gender and Age
as 18.
INSERT INTO Student (Admno, Name, Place) VALUES (104, ‘Abinandh’, ‘Chennai’);
104 Abinandh M 18 Chennai
The student table will have the following data:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
The fields that are not given in the INSERT command will take default values, if it is defined
for them, otherwise NULL value will be stored.

In the INSERT command the fields that are omitted will have either default value
defined or NULL value.

(ii) DELETE COMMAND


The DELETE command permanently removes one or more records from the table. It
removes the entire row, not individual fields of the row, so no field argument is needed. The
DELETE command is used as follows :

DELETE FROM table-name WHERE condition;


For example to delete the record whose admission number is 104 the command is given
as follows:
DELETE FROM Student WHERE Admno=104;
104 Abinandh M 18 Chennai

The following record is deleted from the Student table.


To delete all the rows of the table, the command is used as :
DELETE * FROM Student;
www.tntextbooks.org

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

Chapter 12.indd 216 20-02-2019 15:30:41


www.tntextbooks.org

(iii) UPDATE COMMAND


The UPDATE command updates some or all data values in a database. It can update
one or more records in a table. The UPDATE command specifies the rows to be changed using
the WHERE clause and the new data using the SET keyword. The command is used as follows:

UPDATE <table-name> SET column-name = value, column-name = value,…


WHERE condition;
For example to update the following fields:
UPDATE Student SET Age = 20 WHERE Place = “Bangalore”;
The above command will change the age to 20 for those students whose place is “Bangalore”.
The table will be as updated as below:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 20 Bangalore
103 Ayush M 18 Delhi
To update multiple fields, multiple field assignment can be specified with the SET clause
separated by comma. For example to update multiple fields in the Student table, the command
is given as:
UPDATE Student SET Age=18, Place = ‘Chennai’ WHERE Admno = 102;
102 Akshith M 18 Chennai
The above command modifies the record in the following way.

Admno Name Gender Age Place


100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 18 Chennai
103 Ayush M 18 Delhi

12.7.4 Some Additional DDL Commands:

(i) ALTER COMMAND


The ALTER command is used to alter the table structure like adding a column, renaming
the existing column, change the data type of any column or size of the column or delete the
www.tntextbooks.org

column from the table. It is used in the following way :

ALTER TABLE <table-name> ADD <column-name><data type><size>;

217 Structured Query Language

Chapter 12.indd 217 20-02-2019 15:30:41


www.tntextbooks.org

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

ALTER TABLE Student MODIFY Address char (25);


The above command will modify the address column of the Student table to now hold 25
characters.
The ALTER command can be used to rename an existing column in the following way :
ALTER <table-name> RENAME old-column-name TO new-column-name;

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 :

ALTER TABLE Student DROP COLUMN City;

(ii) TRUNCATE command


The TRUNCATE command is used to delete all the rows from the table, the structure
remains and the space is freed from the table. The syntax for TRUNCATE command is:
TRUNCATE TABLE table-name;

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.

(iii) DROP TABLE command


The DROP TABLE command is used to remove a table from the database. If you
www.tntextbooks.org

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

Chapter 12.indd 218 20-02-2019 15:30:41


www.tntextbooks.org

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;

For example to delete the Student table:

DROP TABLE Student;


DELETE, TRUNCATE AND DROP statement:

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.

12.7.5 DQL COMMAND– SELECT command


One of the most important tasks when working with SQL is to generate Queries and
retrieve data. A Query is a command given to get a desired result from the database table. The
SELECT command is used to query or retrieve data from a table in the database. It is used to
retrieve a subset of records from one or more tables. The SELECT command can be used in
various forms:
Syntax of SELECT command :

SELECT <column-list>FROM<table-name>;

• Table-name is the name of the table from which the information is retrieved.

• Column-list includes one or more columns from which data is retrieved.


www.tntextbooks.org

For example to view only admission number and name of students from the Student table the
command is given as follows:

219 Structured Query Language

Chapter 12.indd 219 20-02-2019 15:30:41


www.tntextbooks.org

If the Student table has the following data:

Admno Name Gender Age Place


100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
SELECT Admno, Name FROM Student;
The above SELECT command will display the following data:
Admno Name
100 Ashish
101 Adarsh
102 Akshith
103 Ayush
104 Abinandh
105 Revathi
106 Devika
107 Hema
To view all the fields and rows of the table the SELECT command can be given as
SELECT * FROM STUDENT;
(i) DISTINCT Keyword
The DISTINCT keyword is used along with the SELECT command to eliminate
duplicate rows in the table. This helps to eliminate redundant data. For Example:
SELECT DISTINCT Place FROM Student;
Will display the following data as follows :
SELECT * FROM Student;
Place
Chennai
Bangalore
Delhi
www.tntextbooks.org

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

Chapter 12.indd 220 20-02-2019 15:30:41


www.tntextbooks.org

(ii) ALL Keyword


The ALL keyword retains duplicate rows. It will display every row of the table without
considering duplicate entries.
SELECT ALL Place FROM Student;
The above command will display all values of place field from every row of the table
without considering the duplicate entries.
Place
Chennai
Delhi
Bangalore
Delhi
Chennai
Chennai
Bangalore
Chennai
The WHERE clause in the SELECT command specifies the criteria for getting the
desired result. The general form of SELECT command with WHERE Clause is:
SELECT <column-name>[,<column-name>,….] FROM <table-name>WHERE condition>;

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

Admno Name Place


100 Ashish Chennai
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
SELECT Admno, Name, Age FROM Student WHERE Age >= 18;
Admno Name Age
101 Adarsh 18
103 Ayush 18
104 Abinandh 18
105 Revathi 19
www.tntextbooks.org

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

221 Structured Query Language

Chapter 12.indd 221 20-02-2019 15:30:41


www.tntextbooks.org

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

Admno Name Age Place


101 Adarsh 18 Delhi
103 Ayush 18 Delhi
The SELECT command can also be used in the following ways:
SELECT Admno, Name, Age, Place FROM Student WHERE (Age>=18 OR Place ="Delhi");
SELECT Admno, Name, Place FROM Student WHERE (NOT Place ="Delhi");

(iii) BETWEEN and NOT BETWEEN Keywords


The BETWEEN keyword defines a range of values the record must fall into to make the
condition true. The range may include an upper value and a lower value between which the
criteria must fall into.
SELECT Admno, Name, Age, Gender FROM Student WHERE Age BETWEEN 18 AND 19;

Admno Name Gender Age Place


101 Adarsh M 18 Delhi
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore

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;

Admno Name Age


100 Ashish 17
102 Akshith 17
107 Hema 17

(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

Chapter 12.indd 222 20-02-2019 15:30:41


www.tntextbooks.org

Admno Name Place


100 Ashish Chennai
101 Adarsh Delhi
103 Ayush Delhi
104 Abinandh Chennai
105 Revathi Chennai
107 Hema Chennai
The NOT IN keyword displays only those records that do not match in the list.

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.

(v) ORDER BY clause


The ORDER BY clause in SQL is used to sort the data in either ascending or descending
based on one or more columns.
1. By default ORDER BY sorts the data in ascending order.
2. We can use the keyword DESC to sort the data in descending order and the keyword ASC
to sort in ascending order.
The ORDER BY clause is used as :

SELECT <column-name>[,<column-name>,….] FROM <table-name>ORDER


BY <column1>,<column2>,…ASC| DESC ;
www.tntextbooks.org

223 Structured Query Language

Chapter 12.indd 223 20-02-2019 15:30:41


www.tntextbooks.org

For example :
To display the students in alphabetical order of their names, the command is used as

SELECT * FROM Student ORDER BY Name;

The above student table is arranged as follows :

Admno Name Gender Age Place


104 Abinandh M 18 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
100 Ashish M 17 Chennai
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
105 Revathi F 19 Chennai

Note
The ORDER BY clause does not affect the original table.

(vi) WHERE clause


The WHERE clause is used to filter the records. It helps to extract only those records
which satisfy a given condition. For example in the student table, to display the list of students
of age18 and above in alphabetical order of their names, the command is given as below:
SELECT * FROM Student WHERE Age>=18 ORDER BY Name;

Admno Name Gender Age Place

104 Abinandh M 18 Chennai


101 Adarsh M 18 Delhi
103 Ayush M 18 Delhi
106 Devika F 19 Bangalore
105 Revathi F 19 Chennai
To display the list of students in the descending order of names of those students of age
www.tntextbooks.org

18 and above the command is given as :


SELECT * FROM Student WHERE Age>=18 ORDER BY Name DESC;

XII
XII Std
Std Computer
Computer Science
Science 224

Chapter 12.indd 224 20-02-2019 15:30:41


www.tntextbooks.org

Admno Name Gender Age Place


105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
101 Adarsh M 18 Delhi
104 Abinandh M 18 Chennai

Note
Sorting can be done on multiple fields.

(vii) GROUP BY clause


The GROUP BY clause is used with the SELECT statement to group the students on
rows or columns having identical values or divide the table in to groups. For example to know
the number of male students or female students of a class, the GROUP BY clause may be
used. It is mostly used in conjunction with aggregate functions to produce summary reports
from the database.

The syntax for the GROUP BY clause is

SELECT <column-names> FROM <table-name> GROUP BY <column-name>HAVING


condition];

To apply the above command on the student table :


SELECT Gender FROM Student GROUP BY Gender;
The following command will give the below given result:
Gender
M
F
The point to be noted is that only two results have been returned. This is because we
only have two gender types ‘Male’ and ‘Female’. The GROUP BY clause grouped all the ‘M’
students together and returned only a single row for it. It did the same with the ‘F’ students.
For example to count the number of male and female students in the student table, the
www.tntextbooks.org

following command is given :

225 Structured Query Language

Chapter 12.indd 225 20-02-2019 15:30:41


www.tntextbooks.org

SELECT Gender, count(*) FROM Student GROUP BY Gender;

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.

(viii) HAVING clause


The HAVING clause can be used along with GROUP BY clause in the SELECT
statement to place condition on groups and can include aggregate functions on them. For
example to count the number of Male and Female students belonging to Chennai .
SELECT Gender , count(*) FROM Student GROUP BY Gender HAVING Place = ‘Chennai’;

Gender count(*)
M 2
F 2
The above output shows the number of Male and Female students in Chennai from the
table student.

12.7.6 TCL commands


(i) COMMIT command
The COMMIT command is used to permanently save any transaction to the database.
When any DML commands like INSERT, UPDATE, DELETE commands are used, the
changes made by these commands are not permanent. It is marked permanent only after the
COMMIT command is given from the SQL prompt. Once the COMMIT command is given,
the changes made cannot be rolled back. The COMMIT command is used as

COMMIT;

(ii) ROLLBACK command


The ROLLBACK command restores the database to the last commited state. It is used
www.tntextbooks.org

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

Chapter 12.indd 226 20-02-2019 15:30:41


www.tntextbooks.org

(iii) SAVEPOINT command


The SAVEPOINT command is used to temporarily save a transaction so that you
can rollback to the point whenever required. The different states of our table can be saved at
anytime using different names and the rollback to that state can be done using the ROLLBACK
command.
SAVEPOINT savepoint_name;

Example showing COMMIT, SAVEPOINT and ROLLBACK in the student table


having the following data:

Admno Name Gender Age Place


105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
101 Adarsh M 18 Delhi
104 Abinandh M 18 Chennai

INSERT INTO Student VALUES (107, 'Beena', 'F', 20 , 'Cochin');


COMMIT;

Admno Name Gender Age Place


105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
101 Adarsh M 18 Delhi
104 Abinandh M 18 Chennai
107 Beena F 20 Cochin

UPDATE Student SET Name = ‘Mini’ WHERE Admno=105;


SAVEPOINT A;

Admno Name Gender Age Place


105 Mini F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
www.tntextbooks.org

101 Adarsh M 18 Delhi


104 Abinandh M 18 Chennai
107 Beena F 20 Cochin

227 Structured Query Language

Chapter 12.indd 227 20-02-2019 15:30:41


www.tntextbooks.org

INSERT INTO Student VALUES(106, 'Jisha', 'F', 19, 'Delhi');


SAVEPOINT B;

Admno Name Gender Age Place


105 Mini F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
101 Adarsh M 18 Delhi
104 vAbinandh M 18 Chennai
107 Beena F 20 Cochin
108 Jisha F 19 Delhi

ROLLBACK TO A;

Admno Name Gender Age Place


105 Mini F 19 Chennai
106 Devika F 19 Bangalore
103 Ayush M 18 Delhi
101 Adarsh M 18 Delhi
104 Abinandh M 18 Chennai
107 Beena F 20 Cochin

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

• The DQL commands help to generate queries in a database.


• The CREATE TABLE command creates a new table.

XII
XII Std
Std Computer
Computer Science
Science 228

Chapter 12.indd 228 20-02-2019 15:30:41


www.tntextbooks.org

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.

5. Prepare a list of all employees who are Managers.


www.tntextbooks.org

229 Structured Query Language

Chapter 12.indd 229 20-02-2019 15:30:41


www.tntextbooks.org

Evaluation

Part - I

Choose the best answer (1 Marks)


1. Which commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
a. DDL b. DML
c. DCL d. DQL
2. Which command lets to change the structure of the table?
a. SELECT b. ORDER BY
c. MODIFY d. ALTER
3. The command to delete a table is
A) DROP B) DELETE
C) DELETE ALL D) ALTER TABLE
4. Queries can be generated using
a. SELECT b. ORDER BY
c. MODIFY d. ALTER
5. The clause used to sort data in a database
a. SORT BY b. ORDER BY
c. GROUP BY d. SELECT

Part -II

Answer the following questions (2 Marks)


1. Write a query that selects all students whose age is less than 18 in order wise.
2. Differentiate Unique and Primary Key constraint.
3. Write the difference between table constraint and column constraint?
4. Which component of SQL lets insert values in tables and which lets to create a table?
5. What is the difference between SQL and MySQL?
www.tntextbooks.org

XII
XII Std
Std Computer
Computer Science
Science 230

Chapter 12.indd 230 20-02-2019 15:30:41


www.tntextbooks.org

Part -III

Answer the following questions (3 Marks)


1. What is a constraint? Write short note on Primary key constraint.
2. Write a SQL statement to modify the student table structure by adding a new field.
3. Write any three DDL commands.
4. Write the use of Savepoint command with an example.
5. Write a SQL statement using DISTINCT keyword.
Part -IV

Answer the following questions (5 Marks)


1. Write the different types of constraints and their functions.
2. Consider the following employee table. Write SQL commands for the qtns.(i) to (v).

EMP CODE NAME DESIG PAY ALLO WANCE

S1001 Hariharan Supervisor 29000 12000


P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
M1005 Ratheesh Mechanic 20000 7000

(i) To display the details of all employees in descending order of pay.


(ii) To display all employees whose allowance is between 5000 and 7000.
(iii) To remove the employees who are mechanic.
(iv) To add a new row.
(v) To display the details of all employees who are operators.
3. What are the components of SQL? Write the commands in each.
4. Construct the following SQL statements in the student table-
(i) SELECT statement using GROUP BY clause.
(ii) SELECT statement using ORDER BY clause.
5. Write a SQL statement to create a table for employee having any five fields and create a
table constraint for the employee table.
www.tntextbooks.org

231 Structured Query Language

Chapter 12.indd 231 20-02-2019 15:30:41


www.tntextbooks.org

CHAPTER 13
Unit IV
PYTHON AND CSV FILES

Learning Objectives

After the completion of this chapter, the student will be able to


• Understand what is CSV?
• Able to import CSV files in python programs.
• Execute and debug python programs.

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

XII Std Computer Science 232


232

Chapter 13.indd 232 20-02-2019 15:33:05


www.tntextbooks.org

Files saved in excel cannot be opened or edited by text editors.

13.3 Purpose Of CSV File

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.

13.4.1 Creating CSV Normal File


To create a CSV file in Notepad, First open a new file using
File →New or ctrl +N.
Then enter the data you want the file to contain, separating each value with a comma
and each row with a new line.
For example consider the following details
Topic1,Topic2,Topic3
one,two,three
Example1,Example2,Example3
www.tntextbooks.org

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:

233 Python and CSV files

Chapter 13.indd 233 20-02-2019 15:33:05


www.tntextbooks.org

Topic1 Topic2 Topic3

one two three


Example1 Example2 Example3

Fig. 13.1 CSV file when opened in MS-Excel

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.

13.4.2 Creating CSV File That contains Comma With Data


For example, let’s say that one of our fields contain commas in the description. If our
data looked like the below example:

RollNo Name Address


12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai
12103 Ram Gopalapuram,
Chennai

To retain the commas in “Address” column, you can enclose the fields in quotation
marks. For example:

RollNo, Name, Address


12101, Nivetha, “Mylapore, Chennai”
www.tntextbooks.org

12102, Lavanya, “Adyar, Chennai”


12103, Ram, “Gopalapuram, Chennai”

XII Std Computer Science 234


234

Chapter 13.indd 234 20-02-2019 15:33:06


www.tntextbooks.org

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

Roll No Name Address


12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai

12102 Ram Gopalapuram, Chennai

Fig 13.2 CSV Field data with comma in Excel

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

It should be written in CSV file as

RollNo, Name, Address


12101, Nivetha, “Mylapore, Chennai”
12102, Lavanya, “Adyar, Chennai”
12103, Ram, “Gopalapuram, Chennai”
www.tntextbooks.org

The Result will look like this

235 Python and CSV files

Chapter 13.indd 235 20-02-2019 15:33:06


www.tntextbooks.org

Roll No Name Address


Mylapore,
12101 Nivetha Chennai
12102 Lavanya Adyar,
Chennai
12102 Ram Gopalapuram,
Chennai

Fig 13.3 CSV Field Data with newline in Excel

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:

Roll No Name Favorite Sports Address


12101 Nivetha “Cricket”, “Football” Mylapore Chennai
12102 Lavanya “Basketball”, “Cricket” Adyar Chennai
12103 Ram “Soccer”, “Hockey” Gopala puram Chennai

It should be written in csv file as

RollNo, Name, FavoriteSports, Address


12101, Nivetha,””” Cricket ””,”” Football ”””, Mylapore chennai 12102, Lavanya,””” Basketball
””,”” Cricket ”””, Adyar hennai 12103, Ram,””” Soccer””,”” Hockey”””, Gopalapuram
chennai
www.tntextbooks.org

The output will be

XII Std Computer Science 236


236

Chapter 13.indd 236 20-02-2019 15:33:06


www.tntextbooks.org

Roll No Name Favorite Sports Address


12101 Nivetha "Cricket", "Football" Mylapore, Chennai
12102 Lavanya "Basketball", "Cricket" Adyar, Chennai
12103 Ram "Soccer", "Hockey" Gopalapuram, Chennai

Fig 13.4 CSV Field Data with Double quotes in Excel


13.4.4 Rules to be followed to format data in a CSV file
1. Each record (row of data) is to be located on a separate line, delimited by a line break by
pressing enter key. For example:
xxx,yyy

denotes enter Key to be pressed

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)

237 Python and CSV files

Chapter 13.indd 237 20-02-2019 15:33:06


www.tntextbooks.org

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:

"Red","Blue","Green" #Field data with doule quotes


Black,White,Yellow #Field data without doule quotes


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.

13.5 Create A CSV File Using Microsoft Excel

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

XII Std Computer Science 238


238

Chapter 13.indd 238 20-02-2019 15:33:06


www.tntextbooks.org

Item Name Cost - Rs Quantity Profit


Keyboard 480 12 1152
5200 10 10400
200 50 2000
Total Prof 13552

Fig 13.5 Sample Worksheet Data


Once the data is entered in the worksheet, select File → Save As option, and for the
“Save as type option”, select CSV (Comma delimited) or type the file name along with extension
.csv.
Saving excel file as CSV

Fig 13.6 Save As dialog box


After you save the file, you are free to open it up in a text editor to view it or to edit it
manually. Its contents will resemble the following:
www.tntextbooks.org

239 Python and CSV files

Chapter 13.indd 239 20-02-2019 15:33:06


www.tntextbooks.org

Item Name, Cost-Rs, Quantity, Profit


Keyboard, 480, 12, 1152
Monitor, 5200, 10, 10400
Mouse, 200, 50, 2000
,,Total Profit =,13552

13.5.1 Microsoft Excel to open a CSV file


If Microsoft Excel has been installed on the computer, by default CSV files should
open automatically in Excel when the file is double-clicked. If you are getting an Open With
prompt when opening the CSV file, choose Microsoft Excel from the available programs to
open the file.
Alternatively, you can open Microsoft Excel and in the menu bar, select File → Open,
and select the CSV file. If the file is not listed, make sure to change the file type to be opened
to Text Files (*.prn, *.txt, *.csv).

If both MS Excel and Open Office calc is installed in the computer, by


default the CSV file will be opened in MS Excel.

13.6 Read and write a CSV file Using Python

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.

CSV files have been used extensively in e-commerce applications because


they are considered very easy to process.

13.6.1 Read a CSV File Using Python


There are two ways to read a CSV file.
1. Use the csv module’s reader function
2. Use the DictReader class.
Two ways of Reading CSV File
www.tntextbooks.org

reader () function Dict Reader class

Fig 13.7 Ways to read CSV file

XII Std Computer Science 240


240

Chapter 13.indd 240 20-02-2019 15:33:06


www.tntextbooks.org

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

Step 1 Open a file

Step 2 Perform Read or write operation

Step 3 Close the file

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

>>> f = open("sample.txt") # open file in current directory and f is file object


>>> f = open('c:\\pyprg\\ch13sample5.csv') # specifying full path

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.

Python File Modes


Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if
it exists.
www.tntextbooks.org

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

241 Python and CSV files

Chapter 13.indd 241 20-02-2019 15:33:06


www.tntextbooks.org

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

f = open("test.txt") # since no mode is specified the default mode rt is used



# perform file operations
f.close()

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

(i) CSV Module’s Reader Function


You can read the contents of CSV file with the help of csv.reader() method. The reader
function is designed to take each line of the file and make a list of all columns. Then, you
just choose the column you want the variable data for. Using this method one can read data
www.tntextbooks.org

from csv files of different formats like quotes (" "), pipe (|) and comma (,).
The syntax for csv.reader() is

XII Std Computer Science 242


242

Chapter 13.indd 242 20-02-2019 15:33:07


www.tntextbooks.org

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

CSV file - data with default delimiter comma (,)


1

CSV file - data with Space at the beginning


2

CSV file - data with quotes


3

CSV file - data with custom Delimiters


4

(a) CSV file with default delimiter comma (,)


The following program read a file called “sample1.csv” with default delimiter comma (,)
and print row by row.
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open('c:\\pyprg\\sample1.csv', 'r') as F:
#other way to open the file is f= ('c:\\pyprg\\sample1.csv', 'r')
reader = csv.reader(F)
# printing each line of the Data row by row
print(row)
F.close()
OUTPUT
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']

(b) CSV files- data with Spaces at the beginning


Consider the following file “sample2.csv” containing the following data when opened
through notepad
Topic1, Topic2, Topic3,
www.tntextbooks.org

one, two, three


Example1, Example2, Example3

243 Python and CSV files

Chapter 13.indd 243 20-02-2019 15:33:07


www.tntextbooks.org

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.

These whitespaces can be removed, by registering new dialects using csv.register_dialect()


class of csv module. A dialect describes the format of the csv file that is to be read. In dialects
the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.

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

XII Std Computer Science 244


244

Chapter 13.indd 244 20-02-2019 15:33:07


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.

(c) CSV File-Data With Quotes


You can read the csv file with quotes, by registering new dialects using csv.register_dialect()
class of csv module.
Here, we have quotes.csv file with following 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.

245 Python and CSV files

Chapter 13.indd 245 20-02-2019 15:33:07


www.tntextbooks.org

(d) CSV files with Custom Delimiters


You can read CSV file having custom delimiter by registering a new dialect with the
help of csv.register_dialect().
In the following file called “sample4.csv”,each column is separated with | (Pipe symbol)

Roll No Name City


12101 Arun Chennai
12102 Meena Kovai
12103 Ram Nellai
103 Ayush M
104 Abinandh M

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.

13.6.2 Read a specific column In a File


To get the specific columns like only Item Name and profit for the “sample5.csv” file .
Then you have to do the following:

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

sample5.csv File in Excel

XII Std Computer Science 246


246

Chapter 13.indd 246 20-02-2019 15:33:07


www.tntextbooks.org

A B C D

1 item Nam Cost-Rs Quantity Profit


2 Keyboard 480 12 1152
3 Monitor 5200 10 10400
4 Mouse 200 50 2000

sample5.csv File with selected col

OUTPUT
Item Name Profit
Keyboard 1152
Monitor 10400
Mouse 2000

13.6.3 Read A CSV File And Store It In A List


In this topic you are going to read a CSV file and the contents of the file will be stored
as a list. The syntax for storing in the List is

list = [] # Start as the empty list



list.append(element) # Use append() to add elements

For example all the row values of “sample.csv” file is stored in a list using the following
program

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

247 Python and CSV files

Chapter 13.indd 247 20-02-2019 15:33:07


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

XII Std Computer Science 248


248

Chapter 13.indd 248 20-02-2019 15:33:07


www.tntextbooks.org

Item Name Cost - Rs Quantity Profit


Keyboard 480 12 1152
Monitor 5200 10 10400
200 50 2000
Total Prof 13552

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.

# sort a selected column given by user leaving the header column


import csv
# other way of declaring the filename
inFile= ‘c:\\pyprg\\sample6.csv’
# openning the csv file which is in the same location of this

www.tntextbooks.org

249 Python and CSV files

Chapter 13.indd 249 20-02-2019 15:33:07


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.

list_name.sort() command arranges a list value in ascending order. list_name.


sort(reverse) is used to arrange a list in descending order.

13.6.5 Sorting A CSV File With A Specified Column


In this program you are going to see the “sample8.csv” file’s entire content is transferred
to a list. Then the list of rows is sorted and displayed in ascending order of quantity. To sort
by more than one column you can use itemgetter with multiple indices: operator .itemgetter
www.tntextbooks.org

(1,2), The content of “sample8.csv” is

XII Std Computer Science 250


250

Chapter 13.indd 250 20-02-2019 15:33:07


www.tntextbooks.org

sample8.csv in Excel screen

Item Name Quantity


Keyboard 48
Monitor 52
Mouse 20

sample8.csv in Notepad
ItemName ,Quantity
Keyboard, 48
Monitor,52
Mouse ,20

Fig 13.6.5 CSV file Data into a list for sorting

The following program do the task mentioned above using operator.itemgetter(col_no)


#Program to sort the entire row by using a specified column.
# declaring multiple header files
import csv ,operator
#One more way to read the file
data = csv.reader(open(‘c:\\PYPRG\\sample8.csv’))
next(data) #(to omit the header)

#using operator module for sorting multiple columns
sortedlist = sorted (data, key=operator.itemgetter(1)) # 1 specifies we want to sort
# according to second column

for row in sortedlist:
print(row)
OUTPUT
www.tntextbooks.org

[‘Mouse ‘, ‘20’]
[‘Keyboard ‘, ‘48’]
[‘Monitor’, ‘52’]

251 Python and CSV files

Chapter 13.indd 251 20-02-2019 15:33:07


www.tntextbooks.org

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)

13.6.6 Reading CSV File Into A Dictionary


To read a CSV file into a dictionary can be done by using DictReader class of csv
module which works similar to the reader() class but creates an object which maps data to a
dictionary. The keys are given by the fieldnames as parameter. DictReader works by reading
the first line of the CSV and using each comma separated value in this line as a dictionary key.
The columns in each subsequent row then behave like dictionary values and can be accessed
with the appropriate key (i.e. fieldname).
If the first row of your CSV does not contain your column names, you can pass a
fieldnames parameter into the DictReader’s constructor to assign the dictionary keys manually.
The main difference between the csv.reader() and DictReader() is in simple terms 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.
For Example Reading “sample8.csv” file into a dictionary
import csv
filename = ‘c:\\pyprg\\sample8.csv’
input_file =csv.DictReader(open(filename,’r’))
for row in input_file:
print(dict(row)) #dict() to print data

OUTPUT
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’, ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}
www.tntextbooks.org

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

Chapter 13.indd 252 20-02-2019 15:33:08


www.tntextbooks.org

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

13.7 Writing Data Into Different Types in Csv Files


www.tntextbooks.org

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

Chapter 13.indd 253 20-02-2019 15:33:08


www.tntextbooks.org

Creating A New Normal CSV File


1

Modifying An Existing File


2

Writing On A CSV File with Quotes


3

Writing On A CSV File with Custom Delimiters


4

Writing On A CSV File with Lineterminator


5

Writing On A CSV File with Quotechars


6

Writing CSV File Into A Dictionary


7

Getting Data At Runtime And Writing In a File


8

13.7.1 Creating A New Normal CSV File


When you have a set of data that you would like to store inside a CSV file, it’s time to do
the opposite and use the write function.

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.

XII Std Computer Science 254


254

Chapter 13.indd 254 20-02-2019 15:33:08


www.tntextbooks.org

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.

13.7.2 Modifying An Existing File


Making some changes in the data of the existing file or adding more data is called
modification .For example the “student.csv” file contains the following data.
Roll No Name City
1 Harshini, Chennai
2 Adhith, Mumbai
3 Dhuruv, Bengaluru
4 egiste, Tiruchy
5 Venkat, Madurai

The following program modify the “student.csv” file by modifying the value of an
existing row in student.csv
www.tntextbooks.org

255 Python and CSV files

Chapter 13.indd 255 20-02-2019 15:33:08


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:

Roll No Name City

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.

(i) ADDING NEW ROW


Sometimes, you may need to add new rows in the existing CSVfile. Adding a new row
at the end of the file is called appending a row.
The following program add a new row to the existing “student.csv” file.
www.tntextbooks.org

XII Std Computer Science 256


256

Chapter 13.indd 256 20-02-2019 15:33:08


www.tntextbooks.org

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

When “student.csv” file is opened with a text editor, it displays as follows

Roll No Name City

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.

13.7.3 CSV Files With Quotes


You can write the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module. The following program explains this.
www.tntextbooks.org

257 Python and CSV files

Chapter 13.indd 257 20-02-2019 15:33:08


www.tntextbooks.org

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”

In above program, a dialect named myDialect is registered(declared). Quoting=csv.


QUOTE_ALL allows to write the double quote on all the values.
13.7.4 CSV Files With Custom Delimiters
A delimiter is a string used to separate fields. The default value is comma(,).
You can have custom delimiter in CSV files by registering a new dialect with the help of
csv.register_dialect().This example Program is written using the custom delimiter pipe(|)

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

for row in info:


writer.writerow(row)

f.close()

XII Std Computer Science 258


258

Chapter 13.indd 258 20-02-2019 15:33:08


www.tntextbooks.org

When we open “dob.csv” file, we get the following output:

Roll No Name City


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
In the above program, a dialect with delimiter as pipe(|)is registered. Then the list “info”
is written into the CSV file “dob.csv”.

Note
The dialect parameter skipinitialspace when it is True, whitespace immediately following
the delimiter is ignored. The default is False.

13.7.5 CSV File With A Line Terminator


A Line Terminator is a string used to terminate lines produced by writer. The default
value is \r or \n. We can write csv file with a line terminator in Python by registering new
dialects using csv.register_dialect() class of csv module. For Example

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

the data after every two lines.

259 Python and CSV files

Chapter 13.indd 259 20-02-2019 15:33:08


www.tntextbooks.org

Note
Python’s CSV module only accepts \r\n, \n or \r as line terminator.

13.7.6 CSV File with quote characters


You can write the CSV file with custom quote characters, by registering new dialects
using csv.register_dialect() class of csv module.

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

XII Std Computer Science 260


260

Chapter 13.indd 260 20-02-2019 15:33:08


www.tntextbooks.org

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

When we open grade.csv file, it will contain following output:

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

13.7.8 Getting Data At Runtime And Writing It In a CSV File


You can even accept the data through keyboard and write in to a CSV file. For example
the following program accept data from the user through key board and stores it in the file
called “dynamicfile.csv”. It also displays the content of the file.
www.tntextbooks.org

261 Python and CSV files

Chapter 13.indd 261 20-02-2019 15:33:08


www.tntextbooks.org

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

XII Std Computer Science 262


262

Chapter 13.indd 262 20-02-2019 15:33:08


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

263 Python and CSV files

Chapter 13.indd 263 20-02-2019 15:33:08


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

Choose the best answer (1 Marks)


1. A CSV file is also known as a ….
(A) Flat File (B) 3D File
(C) String File (D) Random File
2. The expansion of CRLF is
(A) Control Return and Line Feed
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed
3. Which of the following module is provided by Python to do several operations on the
CSV files?
(A) py (B) xls
(C) csv (D) os
www.tntextbooks.org

XII Std Computer Science 264


264

Chapter 13.indd 264 20-02-2019 15:33:08


www.tntextbooks.org

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

A) chennai,mylapore (B) mumbai,andheri


(C) chennai (D) chennai,mylapore
mumba mumbai,andheri
8. Which of the following creates an object which maps data to a dictionary?
(A) listreader() (B) reader()
(C) tuplereader() (D) DicReader ()
9. Making some changes in the data of the existing file or adding more data is called
(A)Editing (B) Appending
(C)Modification (D) Alteration
10. What will be written inside the file test.csv using the following program
www.tntextbooks.org

import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')

265 Python and CSV files

Chapter 13.indd 265 20-02-2019 15:33:08


www.tntextbooks.org

with open('c:\pyprg\ch13\line2.csv', 'w') as f:


wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly

Part - II

Answer the following questions (2 Marks)


1. What is CSV File?
2. Mention the two ways to read a CSV file using Python.
3. Mention the default modes of the File.
4. What is use of next() function?
5. How will you sort more than one column from a csv file?Give an example statement.

Part - III

Answer the following questions (3 Marks)


1. Write a note on open() function of python. What is the difference between the two
methods?
2. Write a Python program to modify an existing file.
3. Write a Python program to read a CSV file with default delimiter comma (,).
4. What is the difference between the write mode and append mode.
5. What is the difference between reader() and DictReader() function?

Part - IV

Answer the following questions (5 Marks)


1. Differentiate Excel file and CSV file.
2. Tabulate the different mode with its meaning.
3. Write the different methods to read a File in Python.
4. Write a Python program to write a CSV File with custom quotes.
5. Write the rules to be followed to format the data in a CSV file.
REFERENCES

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 13.indd 266 20-02-2019 15:33:08


www.tntextbooks.org

CHAPTER 14
Unit V
IMPORTING C++ PROGRAMS IN PYTHON

Learning Objectives

After the completion of this chapter, the student will be able to


• Understand what is wrapping.
• Able to import C++ functions and classes in to Python programs.
• Create environment to work with both languages.
• Execute and debug Python programs.

14.1 Introduction
Python and C++ are general-purpose programming language. However, Python is
quite different from C++.

S.NO PYTHON C++

1 Python is typically an "interpreted" C++ is typically a "compiled"


language language

2 Python is a dynamic-typed C++ is compiled statically typed


language language

3 Data type is not required while Data type is required while


declaring variable declaring variable

4 It can act both as scripting and general It is a general purpose language


purpose language

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

Chapter 14.indd 267 20-02-2019 15:36:06


www.tntextbooks.org

14.2 Scripting Language


A scripting language is a programming language designed for integrating and
communicating with other programming languages. Some of the most widely used scripting
languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl. Since a scripting
language is normally used in conjunction with another programming language, they are often
found alongside HTML, Java or C++.
14.2.1 Difference between Scripting and Programming Languages
Scripting Language and Programming Language looks like the following picture.

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.

14.3 Applications of Scripting Languages

1. To automate certain tasks in a program


2. Extracting information from a data set
3. Less code intensive as compared to traditional programming language
4. can bring new functions to applications and glue complex systems together
Python is actually an interpreted, high-level, general-purpose programming language
that can be used on any modern computer operating system. It can be used for processing text,
www.tntextbooks.org

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.

XII Std Computer Science 268

Chapter 14.indd 268 20-02-2019 15:36:07


www.tntextbooks.org

14.4 Features of Python over C++

• Python uses Automatic Garbage Collection whereas C++ does not.


• C++ is a statically typed language, while Python is a dynamically typed language.
• Python runs through an interpreter, while C++ is pre-compiled.
• Python code tends to be 5 to 10 times shorter than that written in C++.
• In Python, there is no need to declare types explicitly where as it should be done in C++
• In Python, a function may accept an argument of any type, and return multiple values
without any kind of declaration beforehand. Whereas in C++ return statement can return
only one value.

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.

14.5 Importing C++ Files in Pythona

Importing C++ program in a Python program is called wrapping up of C++ in Python.


Wrapping or creating Python interfaces for C++ programs are done in many ways. The
commonly used interfaces are
• Python-C-API (API-Application Programming Interface for interfacing with C
programs)
• Ctypes (for interfacing with c programs)
• SWIG (Simplified Wrapper Interface Generator- Both C and C++)
• Cython (Cython is both a Python-like language for writing
C-extensions)
• Boost. Python (a framework for interfacing Python and C++)
• MinGW (Minimalist GNU for Windows)

14.5.1 MinGW Interface


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.
www.tntextbooks.org

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

Chapter 14.indd 269 20-02-2019 15:36:07


www.tntextbooks.org

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.

Refer installation of MinGW in Annexure -3


14.5.2 Executing C++ Program through Python
1. Double click the run terminal of MinGW
2. Go to the folder where the Python software is located (Python.exe) is located. In this
example “Python folder” is located in
For example here “Python” is located in
C:\Program Files\OpenOffiice 4\Python.
The syntax to change from c:\> to the folder where Python is located is

cd <absolute path>

where “cd” command refers to change directory and absolute path refers to the complete
path where Python is installed.

c:\>cd c:\ program files \ openoffice 4 \ program


c:\ Program Files\OpenOffice 4\program>python
Python 2. 7. 6 <default. Dec 11 2017 16:54:32> [Msc v.1500 32 bit <Intel>] On win 32
Type "help", "copyright", "credits" or "license" for more information
>>>

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.

XII Std Computer Science 270

Chapter 14.indd 270 20-02-2019 15:36:07


www.tntextbooks.org

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,

Python keyword to execute the Python program from command-


line

filename.py Name of the Python program to executed

-i input mode

C++ filename without name of C++ file to be compiled and executed


cpp extension

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

C:\Program Files\migw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0>echo off


Microsoft windows [Version 6.1.7601]
copy right <c> 2009 Microsoft Corporation. All rights reserved.

C:\>cd program files\openoffice 4 program

C:\Program Files\openoffice 4\program> Python c:\pyprg\pycpp.py-i c:\pyprg\pali


compailing c:\pyprg\pali.cpp
Running c:\pyprg\pali.exe
-----------------------
Enter apositive number:232
The reverse of the number is:232
The number is a palindrome
C:\Program jFiles\Openoffice 4\program>Python c:\pyprg\pycpp.py -i c:\pyprg\pali
Compiling c:\pyprg\pali.cpp
Running c:\pyprg\pali.exe
-----------------------
Enter a positive number:234
The reverse of the number is:432
The number is not a palindrome
C:\Program Files\Openoffice 4\program>_
www.tntextbooks.org

Fig 14.2

271
Importing C++ programs in Python

Chapter 14.indd 271 20-02-2019 15:36:07


www.tntextbooks.org

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

The above example is named as factorial.py

XII Std Computer Science 272

Chapter 14.indd 272 20-02-2019 15:36:07


www.tntextbooks.org

14.6.2 How to import modules in Python?


We can import the definitions inside a module to another module. We use the import
keyword to do this. To import our previously defined module factorial we type the following
in the Python prompt.
>>> import factorial
Using the module name we can access the functions defined inside the module. The
dot (.) operator is used to access the functions. The syntax for accessing the functions from
the module is
<module name> . <function name>

For example:
>>> factorial.fact(5)
120

factorial . fact (5)

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

Chapter 14.indd 273 20-02-2019 15:36:07


www.tntextbooks.org

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.

(ii) Python's OS Module


The OS module in Python provides a way of using operating system dependent
functionality.
The functions that the OS module allows you to interface with the Windows operating
system where Python is running on.
os.system(): Execute the C++ compiling command (a string contains Unix, C command
which also supports C++ command) in the shell (Here it is Command Window). For Example
to compile C++ program g++ compiler should be invoked. To do so the following command
is used.

os.system (‘g++’ + <varaiable_name1> ‘-<mode>’ + <variable_name2>

where,

os.system :- function system() defined in os module

General compiler to compile C++ program under Windows


g++ :-
Operating system.

variable_name1:- Name of the C++ file without extension .cpp in string format

To specify input or output mode. Here it is o prefixed with


mode :-
hyphen.

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

g++ compiler compiles the file cpp_file and –o


os.system('g++ ' + cpp_file + ' -o ' + exe_file)
(output) send to exe_file

Note
‘+’ in os.system() indicates that all strings are concatenated as a single string
www.tntextbooks.org

and send that as a List.

XII Std Computer Science 274

Chapter 14.indd 274 20-02-2019 15:36:07


www.tntextbooks.org

(iii) Python getopt module


The getopt module of Python helps you to parse (split) command-line options and
arguments. This module provides two functions to enable command-line argument parsing.
getopt.getopt method
This method parses command-line options and parameter list. Following is the syntax
for this method −
<opts>,<args>=getopt.getopt(argv, options, [long_options])

Here is the detail of the parameters −


argv − This is the argument list of values to be parsed (splited). In our program the complete
command will be passed as a list.
options − This is string of option letters that the Python program recognize as, for input or for
output, with options (like ‘i’ or ‘o’) that followed by a colon (:). Here colon is used
to denote the mode.
long_options −This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('='). In our program the C++ file name
will be passed as string and ‘i’ also will be passed along with to indicate it as
the input file.
getopt() method returns value consisting of two elements. Each of these values are
stored separately in two different list (arrays) opts and args .Opts contains list of splitted
strings like mode, path and args contains any string if at all not splitted because of wrong path
or mode. args will be an empty array if there is no error in splitting strings by getopt().
For example The Python code which is going to execute the C++ file p4 in command
line will have the getopt() method like the following one.
opts, args = getopt.getopt (argv, "i:",['ifile='])

where opts contains [('-i', 'c:\\pyprg\\p4')]

-i :- option nothing but mode should be followed by :

'c:\\pyprg\\p4' value nothing but the absolute path of C++ file.

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

Chapter 14.indd 275 20-02-2019 15:36:07


www.tntextbooks.org

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.

Some more command for wrapping C++ code

if __name__=='__main__':
main(sys.argv[1:])

__name__ (A Special variable) in Python


Since there is no main() function in Python, when the command to run a Python
program is given to the interpreter, the code that is at level 0 indentation is to be executed.
However, before doing that, interpreter will define a few special variables. __name__ is
one such special variable which by default stores the name of the file. If the source file is
executed as the main program, the interpreter sets the __name__ variable to have a value as
“__main__”.
__name__ is a built-in variable which evaluates to the name of the current module.
Thus it can be used to check whether the current script is being run on its own.
For example consider the following

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.

14.7 Python program Executing C++ Program using control statement


www.tntextbooks.org

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

XII Std Computer Science 276

Chapter 14.indd 276 20-02-2019 15:36:07


www.tntextbooks.org

Type the C++ program to check whether the input number is


Step 1 palindrome or not in notepad and save it as “pali_cpp.cpp”.

Type the Python program and save it as pali.py


Step 2

Click the Run Terminal and open the command window


Step 3

Go to the folder of Python using cd command.


Step 4

Type the command Python pali.py -i pali_cpp


Step 5

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

Chapter 14.indd 277 20-02-2019 15:36:07


www.tntextbooks.org

#Now select File→New in Notepad and type the Python program


# Save the File as pali.py . Program that compiles and executes a .cpp file
# Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):

cpp_file = a + '.cpp'

exe_file = a + '.exe'

run(cpp_file, exe_file)

def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-----------------------")
print
os.system(exe_file)
print
if __name__ =='__main__': #program starts executing from here

main(sys.argv[1:])
www.tntextbooks.org

XII Std Computer Science 278

Chapter 14.indd 278 20-02-2019 15:36:07


www.tntextbooks.org

Output of the above program


C:\Program Files\OpenOffice 4\program>Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
Compiling c:\pyprg\pali_cpp.cpp
Running c:\pyprg\pali_cpp.exe
--------------------------------------
Enter a positive number: 56765
The reverse of the number is: 56765
The number is a palindrome
-----------------------------------------------
C:\Program Files\OpenOffice 4\program>Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
Compiling c:\pyprg\pali_cpp.cpp
Running c:\pyprg\pali_cpp.exe
--------------------------------------
Enter a positive number: 56756
The reverse of the number is: 65765
The number is not a palindrome
-----------------------------------------------

14.8 How Python is handling the errors in C++

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

Chapter 14.indd 279 20-02-2019 15:36:07


www.tntextbooks.org

#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

import sys, os, getopt


def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):

cpp_file = a + '.cpp'

exe_file = a + '.exe'

run(cpp_file, exe_file)

def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-------------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])
Output of the above program
C:\Program Files\OpenOffice 4\program>Python c:\pyprg\main.py -i c:\pyprg\hello
[('-i', 'c:\\pyprg\\hello')]
Compiling c:\pyprg\hello.cpp
c:\pyprg\hello.cpp: In function 'int main()':
c:\pyprg\hello.cpp:6:21: error: expected ';' before 'return'
std::cout<<"hello"
^

;

return 0;
~~~~~~
Running c:\pyprg\ch14\cpp_file.exe
-------------------
'c:\pyprg\hello.exe' is not recognized as an internal or external command, operable
www.tntextbooks.org

program or batch file.


C:\Program Files\OpenOffice 4\program>

XII Std Computer Science 280

Chapter 14.indd 280 20-02-2019 15:36:07


www.tntextbooks.org

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.

14.9 Python program Executing C++ Program Containing Arrays

In our previous program to check whether a number is a palindrome number or not


you have used only control structure statements. Now you are going to execute a C++ program
containing array.
Example :- 14.9.1
Write a C++ program to print Transpose of a matrix(2 D array).*/
//Now select File->New in Notepad and type the C++ program
#include <iostream>
using namespace std;
int main()
{
int a[3][3], i, j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{ cout<<"enter the value for array["<<i+1<<"]"<<"["<<j+1<<"] :";
cin>>a[i][j];

}
}
system("cls");
cout<<"\n\nOriginal Array\n";
for(i=0; i<3; i++) {
for(j=0; j<3; j++)
cout<<a[i][j]<<' ';
cout<<endl; }
cout<<"\n\n The Transpose of Matrix\n";
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cout<<a[j][i]<<' ';

cout<<endl ;
www.tntextbooks.org

}
return 0;
}

281
Importing C++ programs in Python

Chapter 14.indd 281 20-02-2019 15:36:07


www.tntextbooks.org

// Save this file as trans_cpp.cpp


//Now select File→New in Notepad and type the Python program
# Save the File as transpose.py.Program that compiles and executes a .cpp file
# Python tanspose.py -i trans_cpp
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):

cpp_file = a + '.cpp'

exe_file = a + '.exe'

run(cpp_file, exe_file)

def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])

Output of the above program


Original Array
123
456
789
The Transpose of Matrix
147
258
369
www.tntextbooks.org

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?

XII Std Computer Science 282

Chapter 14.indd 282 20-02-2019 15:36:07


www.tntextbooks.org

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.

14.10 Python program Executing C++ Program Containing Functions

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

Chapter 14.indd 283 20-02-2019 15:36:07


www.tntextbooks.org

// Save this file as cube_file.cpp


#Now select File→New in Notepad and type the Python program
# Save the File as fun.py
# Program that compiles and executes a .cpp file
# Python fun.py -i c:\pyprg\cube_file.cpp
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):

cpp_file = a + '.cpp'

exe_file = a + '.exe'

run(cpp_file, exe_file)

def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-------------------")
print
os.system(exe_file)
print
if __name__ =='__main__':
main(sys.argv[1:])

Output of the above program


Compiling c:\pyprg\cube_file.cpp
Running c:\pyprg\cube_file.exe
-------------------
Enter any number:
5
Cube of 5 is 125 www.tntextbooks.org

XII Std Computer Science 284

Chapter 14.indd 284 20-02-2019 15:36:07


www.tntextbooks.org

14.11 Python program to Illustrate the inheritance of a Class

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

// C++ program to implement Multilevel Inheritance


//Now select File→New in Notepad and type the C++ program
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout<< "This is a Vehicle" <<endl;

}
};
class threeWheeler: public Vehicle
{ public:
threeWheeler()
{
cout<<"Objects with 3 wheels are vehicles"<<endl;

}
};
// sub class derived from two base classes
class Auto: public threeWheeler{
public:
Auto()

{
cout<<"Auto has 3 Wheels"<<endl;

}
};
// main function
int main()
{
//creating object of sub class will invoke the constructor of base classes
Auto obj;
return 0;
www.tntextbooks.org

285
Importing C++ programs in Python

Chapter 14.indd 285 20-02-2019 15:36:08


www.tntextbooks.org

// Save this file as inheri_cpp.cpp


//Now select File → New in Notepad and type the Python program
# Save the File as classpy.py
# Python classpy.py -i inheri_cpp command to execute c++ program
import sys, os, getopt
def main (argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt (argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):

cpp_file = a + '.cpp'

exe_file = a + '.exe'

run (cpp_file, exe_file)

def run(cpp_file, exe_file):
print ("Compiling " + cpp_file)
os.system ('g++ ' + cpp_file + ' -o ' + exe_file)
print ("Running " + exe_file)
print ("-------------------")
print
os.system (exe_file)
print
if __name__ =='__main__':
main (sys.argv[1:])

Output of the above program


Compiling c:\pyprg\class_file.cpp
Running c:\pyprg\class_file.exe
-------------------
This is a Vehicle
Objects with 3 wheels are vehicles
Auto has 3 Wheels

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.

XII Std Computer Science 286

Chapter 14.indd 286 20-02-2019 15:36:08


www.tntextbooks.org

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

void Writemark(); To display the marks


Create a class called Sports with the following detail
Protected members
287
Importing C++ programs in Python

Chapter 14.indd 287 20-02-2019 15:36:08


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

Choose the best answer (1 Marks)


1. Which of the following is not a scripting language?
(A) JavaScript (B) PHP (C) Perl (D) HTML
2. Importing C++ program in a Python program is called
(A) wrapping (B) Downloading
(C) Interconnecting (D) Parsing
3. The expansion of API is
(A) Application Programming Interpreter
(B) Application Programming Interface
(C) Application Performing Interface
(D) Application Programming Interlink
www.tntextbooks.org

4. A framework for interfacing Python and C++ is

XII Std Computer Science 288

Chapter 14.indd 288 20-02-2019 15:36:08


www.tntextbooks.org

(A) Ctypes (B) SWIG (C) Cython (D) Boost


5. Which of the following is a software design technique to split your code into separate

parts?
(A) Object oriented Programming
(B) Modular programming
(C) Low Level Programming
(D) Procedure oriented Programming
6. The module which allows you to interface with the Windows operating system is
(A) OS module (B) sys module (c) csv module (d) getopt module
7. getopt() will return an empty array if there is no error in splitting strings to
(A) argv variable (B) opt variable (c)args variable (d) ifile variable
8. Identify the function call statement in the following snippet.
if __name__ =='__main__':
main(sys.argv[1:])
(A) main(sys.argv[1:]) (B) __name__ (C) __main__ (D) argv


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

Answer the following questions (2 Marks)


1. What is the theoretical difference between Scripting language and other programming
language?
2. Differentiate compiler and interpreter.
3. Write the expansion of (i) SWIG (ii) MinGW

4. What is the use of modules?
5. What is the use of cd command. Give an example.
www.tntextbooks.org

289
Importing C++ programs in Python

Chapter 14.indd 289 20-02-2019 15:36:08


www.tntextbooks.org

Part - III

Answer the following questions (3 Marks)


1. Differentiate PYTHON and C++
2. What are the applications of scripting language?
3. What is MinGW? What is its use?
4. Identify the module ,operator, definition name for the following
welcome.display()
5. What is sys.argv? What does it contain?

Part - IV

Answer the following questions (5 Marks)


1 Write any 5 features of Python.
2. Explain each word of the following command.
Python <filename.py> -<i> <C++ filename without cpp extension>
3. What is the purpose of sys,os,getopt module in Python.Explain
4. Write the syntax for getopt() and explain its arguments and return values
5. Write a Python program to execute the following c++ coding
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file welcome.cpp

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

XII Std Computer Science 290

Chapter 14.indd 290 20-02-2019 15:36:08


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

Chapter 15.indd 291 20-02-2019 15:40:09


www.tntextbooks.org

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

15.3.1 Creating a Table


After having created an empty database, you will most probably add one or more tables
to this database. The SQL syntax for creating a table "Student" in the database "Academy" looks
like as follows :

CREATE TABLE Student (

RollnoINTEGER, SnameVARCHAR(20), GradeCHAR(1), gender CHAR(1),


www.tntextbooks.org

Average float(5.2), birth_date DATE, PRIMARY KEY (Rollno) );


This is the way, somebody might do it on a SQL command shell. Of course, we want to
do this directly from Python. To be capable to send a command to "SQL", or SQLite, we need a

XII Std Computer Science 292

Chapter 15.indd 292 20-02-2019 15:40:09


www.tntextbooks.org

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.

15.3.2 Adding Records


To populate (add record) the table "INSERT" command is passed to SQLite. “execute”
method executes the SQL command to perform some action. The following example 15.3.2
is a complete working example. To run the program you will either have to remove the file
Academy. db or uncomment the "DROP TABLE" line in the SQL command:
www.tntextbooks.org

293
Data Manipulation through SQL

Chapter 15.indd 293 20-02-2019 15:40:09


www.tntextbooks.org

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:

XII Std Computer Science 294

Chapter 15.indd 294 20-02-2019 15:40:09


www.tntextbooks.org

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

15.4 SQL Query Using Python

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.

15.4.1 SELECT Query


“Select” is the most commonly used statement in SQL. The SELECT Statement in SQL
www.tntextbooks.org

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

Chapter 15.indd 295 20-02-2019 15:40:09


www.tntextbooks.org

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

#save the file as “sql_Academy_query.py”


# cursor object
crsr = connection.cursor()
# execute the command to fetch all the data from the table Student
crsr.execute("SELECT * FROM Student")
# store all the fetched data in the ans variable
ans= crsr.fetchall()
# loop to print all the data
for i in ans:
print(i)

(i) Displaying all records using fetchall()


The fetchall() method is used to fetch all rows from the database table

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

(6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')


(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')

XII Std Computer Science 296

Chapter 15.indd 296 20-02-2019 15:40:10


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

(ii) Displaying A record using fetchone()


The fetchone() method returns the next row of a query result set or None in case there
is no row left.

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

(iii) Displaying all records using fetchone()


Using while loop and fetchone() method we can display all the records from a table.

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

print(result) (6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')


result = cursor.fetchone() (7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')

297
Data Manipulation through SQL

Chapter 15.indd 297 20-02-2019 15:40:10


www.tntextbooks.org

(iv) Displayingusing fetchmany()


Displaying specified number of records is done by using fetchmany(). This method
returns the next number of rows (n) of the result set.

Example : Program to display the content of tuples using fetchmany()

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.

XII Std Computer Science 298

Chapter 15.indd 298 20-02-2019 15:40:10


www.tntextbooks.org

15.4.2 CLAUSES IN SQL


SQL provides various clauses that can be used in the SELECT statements. This clauses
can be called through python script. Almost all clauses will work with SQLite. The following
frequently used clauses are discussed here
• DISTINCT
• WHERE
• GROUP BY
• ORDER BY.
• HAVING

(i) SQL DISTINCT CLAUSE


The distinct clause is helpful when there is need of avoiding the duplicate values present
in any specific columns/table. When we use distinct keyword only the unique values are
fetched. In this example we are going to display the different grades scored by students from
“student table”.

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.

(ii) SQL WHERE CLAUSE


The WHERE clause is used to extract only those records that fulfill a specified condition.
In this example we are going to display the different grades scored by male students from
“student table”
www.tntextbooks.org

299
Data Manipulation through SQL

Chapter 15.indd 299 20-02-2019 15:40:10


www.tntextbooks.org

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',)

(iii) SQL Group By Clause


The SELECT statement can be used along with GROUP BY clause. The GROUP BY
clause groups records into summary rows. It returns one records for each group. It is often
used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by
one or more columns. The following example count the number of male and female from the
student table and display the result.

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)

(iv) SQL ORDER BY Clause


The ORDER BY Clause can be used along with the SELECT statement to sort the data
of specific fields in an ordered way. It is used to sort the result-set in ascending or descending
www.tntextbooks.org

order. In this example name and Rollno of the students are displayed in alphabetical order of
names

XII Std Computer Science 300

Chapter 15.indd 300 20-02-2019 15:40:10


www.tntextbooks.org

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

(v) SQL HAVING Clause


Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but can be used only with group functions. Group functions cannot be
used in WHERE Clause but can be used in HAVING clause.
Example
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY
GENDER HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)
OUTPUT
['gender', 'COUNT(GENDER)']
[('M', 5)]

15.5 The SQL AND, OR and NOT Operators

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

Chapter 15.indd 301 20-02-2019 15:40:10


www.tntextbooks.org

Example for WHERE WITH NOT Operator


Example

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

Example for WHERE WITH AND Operator


In this example we are going to display the name, Rollno and Average of students who
have scored an average between 80 to 90% (both limits are inclusive)
Example

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 for WHERE WITH OR Operator


In this example we are going to display the name and Rollno of students who have not
scored an average between 60 to 70%
www.tntextbooks.org

XII Std Computer Science 302

Chapter 15.indd 302 20-02-2019 15:40:10


www.tntextbooks.org

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

15.6 Querying A Date Column

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

Chapter 15.indd 303 20-02-2019 15:40:10


www.tntextbooks.org

15.7 Aggregate Functions

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 1 : In this example we are going to count the number of records(rows)


import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*) FROM student ")
result = cursor.fetchall()
print(result)
Output:
[(7,)]

EXAMPLE

Example 2 : In this example we are going to count the number of records by


specifying a column
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT COUNT(AVERAGE) FROM student ")
result = cursor.fetchall()
print(result)
Output:
[(7,)]
www.tntextbooks.org

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.

XII Std Computer Science 304

Chapter 15.indd 304 20-02-2019 15:40:10


www.tntextbooks.org

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

NULL values are ignored.

305
Data Manipulation through SQL

Chapter 15.indd 305 20-02-2019 15:40:10


www.tntextbooks.org

15.7.4 MAX() AND MIN() FUNCTIONS


The MAX() function returns the largest value of the selected column.
The MIN() function returns the smallest value of the selected column.
The following example show the highest and least average student’s name.

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

15.8 Updating A Record


You can even update a record (tuple) in a table through python script. The following
example change the name “Priya” to “Priyanka” in a record in “student table”
www.tntextbooks.org

XII Std Computer Science 306

Chapter 15.indd 306 20-02-2019 15:40:10


www.tntextbooks.org

Example

# code for update operation


import sqlite3
# database name to be passed as parameter
conn = sqlite3.connect("Academy.db")
# update the student record
conn.execute("UPDATE Student SET sname ='Priyanka' where Rollno='6'")
conn.commit()
print ("Total number of rows updated :", conn.total_changes)
cursor = conn.execute("SELECT * FROM Student")
for row in cursor:
print (row)
conn.close()
OUTPUT
Total number of rows updated : 1
(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')

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

Chapter 15.indd 307 20-02-2019 15:40:10


www.tntextbooks.org

15.9 Deletion Operation


Similar to Sql command to delete a record, Python also allows to delete a record. The
following example delete the content of Rollno 2 from "student table"

Example

# code for delete operation


import sqlite3
# database name to be passed as parameter
conn = sqlite3.connect("Academy.db")
# delete student record from database
conn.execute("DELETE from Student where Rollno='2'")
conn.commit()
print("Total number of rows deleted :", conn.total_changes)
cursor =conn.execute("SELECT * FROM Student")
for row in cursor:
print(row)
conn.close()

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

XII Std Computer Science 308

Chapter 15.indd 308 20-02-2019 15:40:10


www.tntextbooks.org

15.10 Data input by User

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

# code for executing query using input data


import sqlite3
# creates a database in RAM
con =sqlite3.connect("Academy.db")
cur =con.cursor()
cur.execute("DROP Table person")
cur.execute("create table person (name, age, id)")
print("Enter 5 students names:")
who =[input() for i in range(5)]
print("Enter their ages respectively:")
age =[int(input()) for i in range(5)]
print("Enter their ids respectively:")
p_id =[int(input())for i in range(5)]
n =len(who)
for i in range(n):
# This is the q-mark style:
cur.execute("insert into person values (?, ?, ?)", (who[i], age[i], p_id[i]))
# And this is the named style:
cur.execute("select * from person")
# Fetches all entries from table
print("Displaying All the Records From Person Table")
print (*cur.fetchall(), sep='\n' )
www.tntextbooks.org

309
Data Manipulation through SQL

Chapter 15.indd 309 20-02-2019 15:40:10


www.tntextbooks.org

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

XII Std Computer Science 310

Chapter 15.indd 310 20-02-2019 15:40:10


www.tntextbooks.org

15.11 Using Multiple Table for Querying

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

Chapter 15.indd 311 20-02-2019 15:40:10


www.tntextbooks.org

15.12 Integrating Query With Csv File

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

5, VARUN, B, M, 80.6, 2001-03-14


6, PRIYA, A, F, 98.6, 2002-01-01
4, SAJINI, A, F, 95.6, 2002-11-01

XII Std Computer Science 312

Chapter 15.indd 312 20-02-2019 15:40:10


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

Chapter 15.indd 313 20-02-2019 15:40:10


www.tntextbooks.org

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

15.13 Table List

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',)]

XII Std Computer Science 314

Chapter 15.indd 314 20-02-2019 15:40:10


www.tntextbooks.org

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

Chapter 15.indd 315 20-02-2019 15:40:10


www.tntextbooks.org

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

Cust_Id Cust_Name Address Phone_no City

C008 Sandeep 14/1 Pritam Pura 41206819 Delhi

C010 Anurag Basu 15A, Park Road 61281921 Kolkata

C012 Hrithik 7/2 Vasant Nagar 26121949 Delhi

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

Gcode Name GameName Number PrizeMoney ScheduleDate

101 Padmaja Carom Board 2 5000 01-23-2014

102 Vidhya Badminton 2 12000 12-12-2013

103 Guru Table Tennis 4 8000 02-14-2014

105 Keerthana Carom Board 2 9000 01-01-2014

108 Krishna Table Tennis 4 25000 03-19-2014

(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

XII Std Computer Science 316

Chapter 15.indd 316 20-02-2019 15:40:11


www.tntextbooks.org

Evaluation

Part - I

Choose the best answer (1 Marks)


1. Which of the following is an organized collection of data?
(A) Database (B) DBMS (C) Information (D) Records
2. SQLite falls under which database system?
(A) Flat file database system (B) Relational Database system
(C) Hierarchical database system (D) Object oriented Database system
3. Which of the following is a control structure used to traverse and fetch the records of the
database?
(A) Pointer (B) Key

(C) Cursor (D) Insertion point

4. Any changes made in the values of the record should be saved by the command
(A) Save (B) Save As (C) Commit (D) Oblige
5. Which of the following executes the SQL command to perform some action?
(A) Execute() (B) Key() (C) Cursor() (D) run()
6. Which of the following function retrieves the average of a selected column of rows in a
table?
(A) Add() (B) SUM() (C) AVG() (D) AVERAGE()
7. The function that returns the largest value of the selected column is
(A) MAX() (B) LARGE()

(C) HIGH() (D) MAXIMUM()

8. Which of the following is called the master table?
(A) sqlite_master (B) sql_master

(C) main_master (D) master_main

9. The most commonly used statement in SQL is
(A) cursor (B) select (C) execute (D) commit
www.tntextbooks.org

10. Which of the following clause avoide the duplicate?


(A) Distinct (B) Remove (C) Where (D) GroupBy

317
Data Manipulation through SQL

Chapter 15.indd 317 20-02-2019 15:40:11


www.tntextbooks.org

Part - II

Answer the following questions (2 Marks)


1. Mention the users who uses the Database.
2. Which method is used to connect a database? Give an example.
3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”
4. Write the command to populate record in a table. Give an example.
5. Which method is used to fetch all rows from the database table?

Part - III

Answer the following questions (3 Marks)


1. What is SQLite?What is it advantage?
2. Mention the difference between fetchone() and fetchmany()
3. What is the use of Where Clause.Give a python statement Using the where clause.
4. Read the following details.Based on that write a python script to display department wise
records
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
5. Read the following details.Based on that write a python script to display records in
desending order of
Eno
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept

Part - IV

Answer the following questions (5 Marks)


1. Write in brief about SQLite and the steps used to use it.
2. Write the Python script to display all the records of the following table using fetchmany()

Icode ItemName Rate


www.tntextbooks.org

1003 Scanner 10500

1004 Speaker 3000

XII Std Computer Science 318

Chapter 15.indd 318 20-02-2019 15:40:11


www.tntextbooks.org

1005 Printer 8000

1008 Monitor 15000

1010 Mouse 700

3. hat is the use of HAVING clause. Give an example python script


4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-

Icode :- integer and act as primary key

Item Name :- Character with length 25

Rate :- Integer

Record to be added :- 1008, Monitor,15000

5. Consider the following table Supplier and item .Write a python script for (i) to (ii)

SUPPLIER

Suppno Name City Icode SuppQty

S001 Prasad Delhi 1008 100

S002 Anu Bangalore 1010 200

S003 Shahid Bangalore 1008 175

S004 Akila Hydrabad 1005 195

S005 Girish Hydrabad 1003 25

S006 Shylaja Chennai 1008 180

S007 Lavanya Mumbai 1005 325

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

1. The Definitive Guide to SQLite by Michael Owens


2. Programming for Beginners: 2 Manuscripts: SQL & Python by Byron Francis
3. Tutorialspoint.com
319
Data Manipulation through SQL

Chapter 15.indd 319 20-02-2019 15:40:11


www.tntextbooks.org

CHAPTER 16
Unit V DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART

Learning Objectives

After learning this chapter, the learners will be able to


• Define the term Data Visualization.
• List the types of Data Visualization.
• List the uses of Data Visualization.
• List the types of Visualizations in Matplotlib.
• Practice installing Matplotlib.
• Explore importing Matplotlib.
• Classify the types of Data Visualization plots.
• Practice creating various types of plots using Matplotlib.

16.1 Data Visualization Definition

Data Visualization is the graphical representation of information and data. The


objective of Data Visualization is to communicate information visually to users. For this, data
visualization uses statistical graphics. Numerical data may be encoded using dots, lines, or
bars, to visually communicate a quantitative message.
General types of Data Visualization
• Charts
• Tables
• Graphs
• Maps
• Infographics
• Dashboards
www.tntextbooks.org

Data visualization - Uses


• Data Visualization help users to analyze and interpret the data easily.

320
XII Std Computer Science

Chapter 16.indd 320 20-02-2019 15:43:23


www.tntextbooks.org

• It makes complex data understandable and usable.


• Various Charts in Data Visualization helps to show relationship in the data for one or more
variables.

Infographics → An infographic (information graphic) is the representation of


information in a graphic format.
Dashboard → A dashboard is a collection of resources assembled to create a single unified
visual display. Data visualizations and dashboards translate complex ideas and concepts
into a simple visual format. Patterns and relationships that are undetectable in text are
detectable at a glance using dashboard.

Introduction to Matplotlib — Data Visualization in Python


Matplotlib is the most popular data visualization library in Python. It allows you to
create charts in few lines of code.
Types of Visualizations in Matplotlib
There are many types of Visualizations under Matplotlib. Some of them are:
• Line plot
• Scatter plot
• Histogram
• Box plot
• Bar chart and
• Pie chart

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

Chapter 16.indd 321 20-02-2019 15:43:23


www.tntextbooks.org

Note
Detailed installation procedures given in Annexure

16.2 Getting Started

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

Chapter 16.indd 322 20-02-2019 15:43:24


www.tntextbooks.org

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

For example, to plot x versus y, you can issue the command:


import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16])
plt.show()

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

1.0 1.5 2.0 2.5 3.0 3.5 4.0


www.tntextbooks.org

Figure 16.2

323
Data Visualization using Pyplot

Chapter 16.indd 323 20-02-2019 15:43:24


www.tntextbooks.org

Plotting Two Lines


To plot two lines, use the following code:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x, y, label='Line 1')
plt.plot(x2, y2, label='Line 2')
plt.xlabel('X-Axis')
plt.ylabel('Y-Axis')
plt.title('LINE GRAPH')
plt.legend()
plt.show()
Output
With plt.xlabel and plt.ylabel, you can assign labels to those respective axis. Next, you
can assign the plot's title with plt.title, and then you can invoke the default legend with plt.
legend().

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

Chapter 16.indd 324 20-02-2019 15:43:24


www.tntextbooks.org

Buttons in the output


In the output figure, you can see few buttons at the bottom left corner. Let us see the use
of these buttons.

Configure
Subplots
Home Button Pan Axis Button Button

Forward / Back Buttons Zoom Save the


Button Figure 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.

16.3 Special Plot Types

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

Chapter 16.indd 325 20-02-2019 15:43:24


www.tntextbooks.org

Example: Line plot


import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018]
total_populations = [8939007, 8954518, 8960387, 8956741, 8943721]
plt.plot (years, total_populations)
plt.title ("Year vs Population in India")
plt.xlabel ("Year")
plt.ylabel ("Total Population")
plt.show()
In this program,
Plt.title() → specifies title to the graph
Plt.xlabel() → specifies label for X-axis
Plt.ylabel() → specifies label for Y-axis
Output

Year vs Population in India


8960000

8955000

8950000

8945000

8940000

2014.4 2014.5 2015.0 2015.5 2016.0 2016.6 2017.0 2017.7 2018.0


Year

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

Chapter 16.indd 326 20-02-2019 15:43:24


www.tntextbooks.org

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

The above code represents the following:


Labels → Specifies labels for the bars.
Usgae → Assign values to the labels specified.
www.tntextbooks.org

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

Chapter 16.indd 327 20-02-2019 15:43:24


www.tntextbooks.org

Bar Graph and Histogram are the two ways to display data in the form of a diagram.

Key Differences Between Histogram and Bar Graph


The differences between Histogram and bar graph are as follows
1. Histogram refers to a graphical representation; that displays data by way of bars to
show the frequency of numerical data. A bar graph is a pictorial representation of data
that uses bars to compare different categories of data.
2. A histogram represents the frequency distribution of continuous variables. Conversely,
a bar graph is a diagrammatic comparison of discrete variables.
3. Histogram presents numerical data whereas bar graph shows categorical data.
4. The histogram is drawn in such a way that there is no gap between the bars. On the ot her
hand, there is proper spacing between bars in a bar graph that indicates discontinuity.
5. Items of the histogram are numbers, which are categorised together, to represent ranges
of data. As opposed to the bar graph, items are considered as individual entities.
6. In the case of a bar graph, it is quite common to rearrange the blocks, from highest to
lowest. But with histogram, this cannot be done, as they are shown in the sequence of
classes.
7. The width of rectangular blocks in a histogram may or may not be same while the
width of the bars in a bar graph is always same.
Pie Chart
Pie Chart is probably one of the most common type of chart. It is a circular graphic
which is divided into slices to illustrate numerical proportion. The point of a pie chart is
to show the relationship of parts out of a whole.
To make a Pie Chart with Matplotlib, we can use the plt.pie() function. The autopct
parameter allows us to display the percentage value using the Python string formatting.

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

Chapter 16.indd 328 20-02-2019 15:43:24


www.tntextbooks.org

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.

2. Plot a pie chart for your marks in the recent examination.

3. Plot a line chart on the academic performance of Class 12 students in Computer


Science for the past 10 years.

4. Plot a bar chart for the number of computer science periods in a week.
www.tntextbooks.org

329
Data Visualization using Pyplot

Chapter 16.indd 329 20-02-2019 15:43:25


www.tntextbooks.org

Evaluation

Part - I

Choose the best answer (1 Marks)


1. Which is a python package used for 2D graphics?
a. matplotlib.pyplot b. matplotlib.pip
c. matplotlib.numpy d. matplotlib.plt
2. Identify the package manager for Python packages, or modules.
a. Matplotlib b. PIP c. plt.show() d. python package



3. Read the following code: Identify the purpose of this code and choose the right
option from the following.
C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip –
version
a. Check if PIP is Installed b. Install PIP
c. Download a Package d. Check PIP version
4. Read the following code: Identify the purpose of this code and choose the right
option from the following.
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip
list
a. List installed packages b. list command
c. Install PIP d. packages installed
5. To install matplotlib, the following function will be typed in your command prompt.
What does “-U”represents?
Python –m pip install –U pip
a. downloading pip to the latest version
b. upgrading pip to the latest version
c. removing pip
d. upgrading matplotlib to the latest version
6. Observe the output figure. Identify the coding for obtaining this output.
www.tntextbooks.org

330
XII Std Computer Science

Chapter 16.indd 330 20-02-2019 15:43:25


www.tntextbooks.org

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

a. import matplotlib.pyplot as plt


plt.plot([1,2,3],[4,5,1])

plt.show()

b. import matplotlib.pyplot as plt
plt.plot([1,2],[4,5])

plt.show()

c. import matplotlib.pyplot as plt
plt.plot([2,3],[5,1])

plt.show()

d. import matplotlib.pyplot as plt
plt.plot([1,3],[4,1])

plt.show()

7. Read the code:
a. import matplotlib.pyplot as plt
b. plt.plot(3,2)
c. plt.show()
Identify the output for the above coding.
www.tntextbooks.org

331
Data Visualization using Pyplot

Chapter 16.indd 331 20-02-2019 15:43:25


www.tntextbooks.org

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

8. Which key is used to run the module?


a. F6 b. F4 c. F3 d. F5
9. Identify the right type of chart using the following hints.
Hint 1: This chart is often used to visualize a trend in data over intervals of time.
Hint 2: The line in this type of chart is often drawn chronologically.
a. Line chart b. Bar chart c. Pie chart d. Scatter plot
10. Read the statements given below. Identify the right option from the following for pie
chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using
the Python string formatting.
a. Statement A is correct b. Statement B is correct
c. Both the statements are correct d. Both the statements are wrong

Part - II

Answer the following questions (2 Marks)


www.tntextbooks.org

1. Define: Data Visualization.


2. List the general types of data visualization.
3. List the types of Visualizations in Matplotlib.
332
XII Std Computer Science

Chapter 16.indd 332 20-02-2019 15:43:25


www.tntextbooks.org

4. How will you install Matplotlib?


5. Write the difference between the following functions: plt.plot([1,2,3,4]), plt.
plot([1,2,3,4], [1,4,9,16]).
Part - III

Answer the following questions (3 Marks)


1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()
2. Write any three uses of data visualization.
3. Write the coding for the following:
a. To check if PIP is Installed in your PC.
b. To Check the version of PIP installed in your PC.
c. To list the packages in matplotlib.
4. Write the plot for the following pie chart output.

29.2%

54.2%
8.3%
8.3%
www.tntextbooks.org

333
Data Visualization using Pyplot

Chapter 16.indd 333 20-02-2019 15:43:25


www.tntextbooks.org

Part - IV

Answer the following questions (5 Marks)


1. Explain in detail the types of pyplots using Matplotlib.
2. Explain the various buttons in a matplotlib window.
3. Explain the purpose of the following functions:
a. plt.xlabel
b. plt.ylabel
c. plt.title
d. plt.legend()
e. plt.show()

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

Chapter 16.indd 334 20-02-2019 15:43:25


www.tntextbooks.org

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

Glossary.indd 335 20-02-2019 15:44:16


www.tntextbooks.org

Scans the entire program and translates it as a whole


into machine code. It generates the error message only
compiler after scanning the whole program. Hence debugging is
comparatively hard.
Conjunction Concurrence, coincidence
Constraint Restriction or limitation
Constructor A special function get execution automatically when
an object enter into scope.
continue To skip the remaining part and start with next iteration.
CRUD Create, Read, Update and Delete
csv.reader() The reader function is designed to take each line of the
file and make a list of all columns
csv.register_dialect() A dialect describes the format of the csv file that is to
be read
CsvQuote All If quoting is set to csvquote all, then writerow() will
quote all fields.
cur = c.cursor() Creating cursor object
cur.fetchall() method to get a list of the matching rows.
cur.fetchmany() method that returns the next number of rows (n) of the
result set
cur.fetchone() method to retrieve a single matching row
CWI Centrum Wiskunde & Informatica
DBA DataBase Adminstrator
DBMS Database Management System
def This keyword is used to define function.
Destructor A special function get execution automatically when
an object exit from its scope.
dict() It is used to print the data in dictionary format without
orderdict
Dictionary Collection of Key-Value pairs
Works by reading in the first line of the CSV and using
each column comma separated value in this line as a
DictReader() dictionary key.
Dictwriter() Write dictionary data into a CSV file
www.tntextbooks.org

elif else…if
Embedded Firmly attached
Enter key Enter key or newline is used to create rows in a csv file

336

Glossary.indd 336 20-02-2019 15:44:17


www.tntextbooks.org

eval() This function is used to evaluate the value of a string.


Father of Relational Database Dr. Edgar Frank Codd
g++ compiler to compile c++ program
GIS Geographic Information System
global Scope A variable, with global scope can be used anywhere in
the program.
You do not write the complete application in the
language, but rather, you use the language to
orchestrate(organize) modules written in (possibly
many different) other languages, making them work
together to form the application. A glue language
makes it easy to do that (convenient syntax, good
Glue language support for inter-process communication and data
managing, no compilation step etc).
id () It returns the memory address of the given object.
IDLE Integrated Development Environment
immutable unchangeable
Implementation Implementation carries out the operation declared in
the interfac
Import in python is similar to #include header_file
in C++. Python modules can get access to code from
import another module by importing the file/function using
“import” statement.
Any function that changes the internal state of one of
its arguments or the value of some external variable is
Impure Functions an impure function.
Instantiation Process of creating an object
Integrity Whole and undivided
Interactive Mode A way of using the Python interpreter by typing
command and expressions at the prompt.
Interface Interface defines what an object can do, but doesn't
actually do it
Translates program one statement at a time. It
continues translating the program until the first error
interpreter is met, in which case it stops. Hence debugging is easy.
Intersection Intersection defines a relation consisting of a set of all
www.tntextbooks.org

tuple that are in both A and B.


Key Data that is mapped to a value in a dictionary

337

Glossary.indd 337 20-02-2019 15:44:17


www.tntextbooks.org

lambda Lambda function is mostly used for creating small and


one- time anonymous function.
LEGB rule Local → Enclosed → Global → Built-in scope
List Mutable ordered collection of values
local Scope A variable declared inside the function's body or in a
block is called local scope.
Looping Repetition
Mapping The process of binding a variable name with an object
Method A function declared and defined inside a class.
A module is a file containing Python definitions and
module statements. The file name is the module name with the
suffix .py appended. Within a module, the module’s
name (as a string) is available as the value of the global
variable name .
Namespaces containers for mapping names of variables to objects
Nested Block A block within a block is called nested block.
next() The next() function returns the next item from the
iterator. It can also be used to skip a row of the csv file
Object Collection of Data and Functions.
Object Oriented Computer Programming concept based on real world
Programming objects.
operator.itemgetter(col_ no) To sort by more than one column from a csv file
Used to execute system command and here in our
os.system() python program is used to compile the c++ program
using g++
Parameter Parameter is variable in the declaration of function
definition.
parse To split an input into pieces of data that can be easily
stored or manipulated.
pass Can be used as placeholder in functions and loops.
Projection ( π ) The projection eliminates all attributes of the input
relation but those mentioned in the projection list
Prompt Character (<<<) displayed by the interpreter to
indicate that it is ready to take input from the user.
Pure Functions Pure functions always returns the same result if the
www.tntextbooks.org

same arguments are passed in


Python prompt >>>

338

Glossary.indd 338 20-02-2019 15:44:17


www.tntextbooks.org

Queue is an abstract data structure, somewhat similar


to Stacks. Unlike stacks, a queue is open at both its
Queue ends. One end is always used to insert data(enqueue)
and the other is used to remove data(dequeue). Queue
follows First-In-First-Out methodology, i.e., the data
item stored first will be accessed first.
RDBMS Relational Database Management System
recursion When a function calls itself is known as recursion.
Redundant Duplication of data
Routines routines are otherwise called as functions or methods.
In Python it is also called as definition
Schema Structure or model
Visibility of variables, parameters and functions in
Scope one part of a program to another part of the same
program.
Script A Python program stored in a file.
Script Mode A way of using the Python interpreter by typing
command and expressions at the prompt.
Select ( σ ) The SELECT operation is used for selecting a subset of
the tuples according to a given selection condition
Selectors Functions that retrieve information from the data
type.
Sequential One after another
Set difference(-) (-) symbol denotes it. The result of A-B is a relation
which includes all tuples that are in A but not in B.
skipinitialspace=true When true, whitespace immediately following the
delimeter is ignored. The default is false
slicing cut
A stack (sometimes called a “push-down stack”) is an
ordered collection of items where the addition of new
Stack items and the removal of existing items always takes
place at the same end. This end is commonly referred
to as the “top.” The end opposite the top is known as
the “base.This ordering principle is sometimes called
LIFO, last- in first-out.
stride a long step
www.tntextbooks.org

string sequence of letters, numbers or symbols


subscript an index number

339

Glossary.indd 339 20-02-2019 15:44:17


www.tntextbooks.org

Syntax The structure of a program


Syntax Error An error in a program that makes it impossible to
parse.
Token One of the basic elements of the syntactic structure
of a program.
It is a sequence of immutable(not changeable) objects.
Tuple Tuples are sequences, just like lists.Tuples are defined
by having values between parentheses ( ).
Union operation(U) Union is symbolized by symbol. It includes all tuples
that are in tables A or in B.
variable Memory box to store values
writer ow() Method to write a single row of data in a file
writer ows() Method to write multiple rows of data in a file
FALSE Logical value 0
TRUE Logical value 1

www.tntextbooks.org

340

Glossary.indd 340 20-02-2019 15:44:17


www.tntextbooks.org

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

next() Retrieves Next Element from Iterator


object() Creates a Featureless Object
oct() converts integer to octal

341

Annexure I & 2.indd 341 20-02-2019 14:35:27


www.tntextbooks.org

open() Returns a File object


ord() returns Unicode code point for Unicode character
pow() returns x to the power of y
print() Prints the Given Object
property() returns a property attribute
range() return sequence of integers between start and stop
repr() returns printable representation of an object
reversed() returns reversed iterator of a sequence
round() rounds a floating point number to ndigits places.
set() returns a Python set
setattr() sets value of an attribute of object
slice() creates a slice object specified by range()
sorted() returns sorted list from a given iterable
staticmethod() creates static method from a function
str() returns informal representation of an object
sum() Add items of an Iterable
super() Allow you to Refer Parent Class by super
type() Returns Type of an Object
vars() Returns __dict__ attribute of a class
__import__() Advanced Function Called by import

II. String Functions


Function Description
capitalize() Converts first character to Capital Letter
casefold() converts to casefolded strings
center() Pads string with specified character
count() returns occurrences of substring in string
encode() returns encoded string of given string
endswith() Checks if String Ends with the Specified Suffix
expandtabs() Replaces Tab character With Spaces
find() Returns the index of first occurrence of substring
format() formats string into nicer output
format_map() Formats the String Using Dictionary
index() Returns Index of Substring
input() reads and returns a line of string
int() returns integer from a number or string
isalnum() Checks Alphanumeric Character
isalpha() Checks if All Characters are Alphabets
isdecimal() Checks Decimal Characters
isdigit() Checks Digit Characters
isidentifier() Checks for Valid Identifier
www.tntextbooks.org

islower() Checks if all Alphabets in a String are Lowercase


isnumeric() Checks Numeric Characters
isprintable() Checks Printable Character
isspace() Checks Whitespace Characters
342

Annexure I & 2.indd 342 20-02-2019 14:35:27


www.tntextbooks.org

istitle() Checks for Titlecased String


isupper() returns if all characters are uppercase characters
join() Returns a Concatenated String
ljust() returns left-justified string of given width
lower() returns lowercased string
lstrip() Removes Leading Characters
maketrans() returns a translation table
partition() Returns a Tuple
replace() Replaces Substring Inside
rfind() Returns the Highest Index of Substring
rindex() Returns Highest Index of Substring
rjust() returns right-justified string of given width
rpartition() Returns a Tuple
rsplit() Splits String From Right
rstrip() Removes Trailing Characters
slice() creates a slice object specified by range()
split() Splits String from Left
splitlines() Splits String at Line Boundaries
startswith() Checks if String Starts with the Specified String
strip() Removes Both Leading and Trailing Characters
swapcase() swap uppercase characters to lowercase; vice versa
title() Returns a Title Cased String
translate() returns mapped charactered string
upper() returns uppercased string
zfill() Returns a Copy of The String Padded With Zeros

III. List Functions


Function Description
append() Add Single Element to The List
clear() Removes all Items from the List
copy() Returns Shallow Copy of a List
count() returns occurrences of element in a list
extend() Add Elements of a List to Another List
index() returns smallest index of element in list
insert() Inserts Element to The List
list() Function creates list in Python
pop() Removes Element at Given Index
remove() Removes Element from the List
www.tntextbooks.org

reverse() Reverses a List


slice() creates a slice object specified by range()
sort() sorts elements of a list

343

Annexure I & 2.indd 343 20-02-2019 14:35:27


www.tntextbooks.org

IV. Tuple Functions


Function Description
count() returns occurrences of element in a tuple
index() returns smallest index of element in tuple
slice() creates a slice object specified by range()
tuple() Function Creates a Tuple
zip() Returns an Iterator of Tuples

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.

VI. Dictionary Functions


Function Description
clear() Removes all Items
copy() Returns Shallow Copy of a Dictionary
dict() Creates a Dictionary
fromkeys() creates dictionary from given sequence
get() Returns Value of The Key
items() returns view of dictionary's (key, value) pair
keys() Returns View Object of All Keys
pop() removes and returns element having given key
popitem() Returns & Removes Element From Dictionary
www.tntextbooks.org

setdefault() Inserts Key With a Value if Key is not Present


update() Updates the Dictionary
values() returns view of all values in dictionary

344

Annexure I & 2.indd 344 20-02-2019 14:35:27


www.tntextbooks.org

ANNEXURE - II

Installation of MySQL and Creating a database

• Download WAMP based on system configuration and install it in your computer.

• log on to MySQL console as user (root).


• Enter password appears (No need to enter password), press Enter key.
• MySQL prompt appears from where you can enter the SQL commands.

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 I & 2.indd 345 20-02-2019 14:35:27


www.tntextbooks.org

ANNEXURE 3
Installation of MinGW
STEPS TO INSTALL MinGW-w64 - for 32 and 64 bit Windows

STEP1: Type https://sourceforge.net/projects/mingw-w64 in any search engine(www.


google.in) and double click it.

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

Annexure III.indd 346 20-02-2019 14:34:38


www.tntextbooks.org

step 4: Start the Installation as per the instructions given bellow.

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

Welcome to the MinGW-W64


Intallation!

Welcome to the MinGW-W64 online installer.

www.tntextbooks.org

3. The following pop-up window will appear, which specify the Setup settings

347

Annexure III.indd 347 20-02-2019 14:34:38


www.tntextbooks.org

Settings
Specify setup settings.

Version 8.1.0
Architecture i686
Threads posix
Exception dwarf
Build revision 0

< Back Cancel

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.

Setup will install files in the following folder.


In you would like to install i686-8.1.0-posix-dwarf-rt_v6-rev0 in to different
folder, click Browser and select another folder.

Destination folder

C:\Program Files (x86)\mingw-w6-i686-8.1.0-posix-dw Browser ...

Space available: 96.80 GB


Create shortcuts in Start Menu

5. Select the destination folder in the following window to install MinGW-W64.

www.tntextbooks.org

348

Annexure III.indd 348 20-02-2019 14:34:38


www.tntextbooks.org

6. Wait for the completion of installation

Installing Files
Copying i686-8.1.0-posix-dwarf-rt_v6-rev0 files to your computer.

To stop or pause the installation process, click Cancel.

Downloading file...
File: i686-8.1.0-release-posix-dwarf-rt_v6-rev0.7z

7 Click the button once it gets highlighted.

Installing Files
Copying i686-8.1.0-posix-dwarf-rt_v6-rev0 files to your computer.

Click Next to continue the installation.

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

Annexure III.indd 349 20-02-2019 14:34:38


www.tntextbooks.org

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

c:\Program Files <x86>\migw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0>echo off


Microsoft windows [Version 6.1.7601]
Copyright <c> 2009 Microsoft Corporation. All rights reserved.
c:\>

www.tntextbooks.org

350

Annexure III.indd 350 20-02-2019 14:34:39


www.tntextbooks.org

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.

Check if pip is Installed


To check if pip is already installed in your system, navigate your command line to the
location of Python's script directory.

You can install the latest version of pip from your command prompt using the following
command:

Python –m pip install –U pip


-U represents upgrading pip to the latest version.

To Check pip version:

To check the version of pip in your system, type the following command:
www.tntextbooks.org

C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

The output in command prompt will look like this:

351

Annexure IV.indd 351 20-02-2019 15:49:00


www.tntextbooks.org

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:

C:\Users\YourName\AppData\Local\Programs\Python\Python36-32\Scripts>pip list The


352

Annexure IV.indd 352 20-02-2019 15:49:00


www.tntextbooks.org

screen will display the list of all the packages installed on your system.

www.tntextbooks.org

353

Annexure IV.indd 353 20-02-2019 15:49:00


www.tntextbooks.org

COMPUTER SCIENCE – XII


List of Authors and Reviewers

Domain Expert Authors


Dr. T.V.Gopal Mr. Kannan K
Professor, Dept of Computer Science and Technology, Post Graduate Teacher, Chennai Girls Hr Sec School,
College of Engineering, Guindy, Anna University, Chennai. Rotler street , Chennai

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.

Mr. Malaiarasu P Mr. Sreenivasan R


Associate Professor, Dept of Computer Science, Post Graduate Teacher, Santhome Hr Sec School, Mylapore, Chennai
Govt. Arts College, Perumpakkam, Chennai
Mr. Gowrisankar N.V
Dr. Ramesh Kumar M Post Graduate Teacher, Chennai Girls Hr Sec School,
Assistent Professor and Head of the Department, Nungambakkam, Chennai
Dept of Computer Science,
Govt. Arts College, Nandhanam, Chennai Mr. Lenin K
Post Graduate Teacher, Chennai Girls Hr Sec School, Saidapet, Chennai
Dr. Radha P
Assistant Professor, Dept of Information Technology, Mrs. Bindhu Mohandas
Govt. Arts & Science College (A), Coimbatore Post Graduate Teacher, Vijayanta Model Hr Sec School,
H.V.F Estate , Avadi, Chennai
Dr. Nester Jeyakumar M
Associate Professor and Head of the Department, Mrs. Gajalakshmi R
Dept of Computer Science, Loyola College, Chennai Post Graduate Teacher, Jaigopal Garodia Hindu Vidyalaya Hr Sec School,
West Mambalam, Chennai

Experts Co-ordinator Dr. Valarmathi K E


Post Graduate Teacher, Velammal Vidhyashram, Surapet, Chennai
Mr. Ravikumar Arumugam
Principal, District Institute of Education and Training,
Mayannur, Karur Dt.

Academic Coordinators QR Code Management Team


Mrs. Tamil Selvi R R. Jaganathan,
B.T. Assistant, SGT, PUMS - Ganesapuram,
Government High School, Poonampalayam, Trichy District Polur , Thiruvannamalai.

J.F. Paul Edwin Roy,


B.T.Asst. PUMS -Rakkipatty, Salem.

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

Annexure IV.indd 354 20-02-2019 15:49:00


www.tntextbooks.org

GOVERNMENT OF TAMIL NADU

HIGHER SECONDARY SECOND YEAR

COMPUTER APPLICATIONS
Theory & Practical

A Publication Under Free Textbook Programme of Government of Tamil Nadu


DEPARTMENT OF SCHOOL EDUCATION

UNTOUCHABILITY IS INHUMAN AND A CRIME


www.tntextbooks.org

Government of TamilNadu
First Edition - 2019

(Published under New Syllabus)

NOT FOR SALE

Content Creation

The wise
possess all

State Council of Educational


Research and Training
© SCERT 2019

Printing & Publishing

Tamil NaduTextbook and


Educational Services Corporation
www.textbooksonline.tn.nic.in

ii
www.tntextbooks.org

PREFACE

Human civilization achieved the highest peak


with the development of computer known as
“Computer era”. Literate are those who have
the knowledge in using the computerwhereas
others are considered illiterate inspite of the
other degrees obtained. The growth of the
nation at present lies in the hands of the youth,
hence the content of this book is prepared in
such a way so as to attain utmost knowledge
considering the future needs of the youth.

iii
www.tntextbooks.org

Career Guidance List of job opportunities on successful completion of course

Learning objectives briefly describe the contents of the


Learning Objectives unit. It also outlines the knowledge gained by the students.

Interesting facts to motivate students to gain more infor-


mation regarding the unit.

Infographics Visual representations of the unit for better understanding.

HOW TO USE Concept Figures


Conceptual diagrams that potrays the technique of draft-
ing and sewing.
THE BOOK

To facilitate reading at anytime, anywhere.

Skill oriented activities based on the units for better


Activity understanding.

Access students under the category of understanding,


Evaluation reproducing and application oriented.

Glossary Explanation of significant terms.

A model question paper to help students to face


Model Question Paper examinations.

References List of related books for further reading.

iv
CAREER GUIDANCE
www.tntextbooks.org

COURSES COLLEGES/ PROFESSION


UNIVERSITIES
B.E / B.Tech All University and their affiliated Software Engineer, Hardware
Colleges and Self financing Colleges Engineer, Software Development,
in India and Abroad. Healthcare Section, IT & ITEs

Science and Humanities


B.Sc (Computer Science) All University and their affiliated Government Job and Private
BCA Colleges and Self financing Company BPO, Geologist,
B.Sc ( Maths, Physics, Chemistry, Colleges in India and Abroad. Journalist
Bio-Chemistry, Geography,
journalism, Library Sciences,
Political Science, Travel and
Tourism)

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

CA The Institute of Chartered Accountant CA, Private Organization,


CA-Chartered Accountant of India (ICAI) Government ,Banking sectors and
CMA-Cost Management Accountant. prospects for self – employment.
CS-Company Secretary (Foundation)

Diploma Government Polytechnic and Junior Engineer (Government and


Selffinancing colleges Private)

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

COURSES COLLEGES/ PROFESSION


UNIVERSITIES

Commerce Courses (Con’t)


Certified Financial Analyst,
Certified Financial Planner,
Certified Investment Banker

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

Science and Humanities


B.Sc.Botany All University and their affiliated Government Job and Private
B.Sc.Zoology Colleges and Self financing Company BPO, Geologist,
B.Sc.Dietician & Nutritionist Colleges in India and Abroad. Journalist
B.Sc.Home Science
B.Sc.Food Technology
B.Sc.Dairy Technology
B.Sc. Hotel Management
B.Sc. Fashion Design
B.Sc. Mass Communication
B.Sc. Multimedia
B.Sc. -3D Animation

vi
CONTENTS
www.tntextbooks.org

CHAPTER 01 Multimedia and Desktop Publishing ������������������������������������ 01


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

Multimedia and Desktop Publishing

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.1 Introduction to plays vital role in terms of presenting



Multimedia information to the users.
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
become the latest enriching experience
in the field of information sector. The
fast growing of multimedia technology
over the last decade has brought a lot of
changes to computing, entertainment and
education.
The phenomenal growth of Figure: 1.1 Introduction to Multimedia
multimedia technologies and applications
has presented the computerized field 1.2 Multimedia Definition
with great challenges and opportunities.
The word multimedia consists of two
Multimedia is becoming more popular
words “multi” and “media” which means
among the user in the terms of its uses
that multiple forms of media are combined
and applications. Multimedia application
to gather and provide services like storage,
1
www.tntextbooks.org

communication, presentation and Input/ Static Text


output interactions of text, video, image, Static text, the text or the words will
graphics and audio. remain static as a heading or in a line,
The term multimedia comprises of or in a paragraph. The words are given
two words, “multi” and “medium”. Multi along with the images to explain about the
refers to many i.e. at least two. Media is the images. In static text the words will either
plural of medium. Therefore multimedia is give information or support an image or
an integration of many types of media like an video.
text, graphics, images, audio, animation,
video etc on a single medium in the same
information unit.

1.3 Components of

Multimedia
Multimedia has five major components
like text, images, sound, video and
animation. They are explained in detail
below:

Figure: 1.4 Static Text

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

2 Chapter 1 Multimedia and Desktop Publishing


www.tntextbooks.org

Figure: 1.5 Hyper Text

1.3.2 Image transmission for networked application.


Images acts as an vital component in various Compression formats used for
multimedia. These images are generated this purpose are GIF, TIFF and JPEG.
by the computer in two ways, as bitmap or
raster images and as vector images.

Raster or Bitmap Images


The common and comprehensive form of
storing images in a computer is raster or
bitmap image. Bitmap is a simple matrix
of the tiny dots called pixel that forms a
raster or bitmap image. Each pixel consists
of two or more colors. Based on how
much data, in bits is used to determine Figure: 1.6 Images
the number of colors, the color depth
is determined. Eg. one bit is two colors,
1.3.3 Animation
four bits means sixteen colors, eight bits Animation is the process displaying still
indicates 256 colors, and so on. images so quickly so that they give the
impression of continuous movement. In
Vector Images animation the screen object is a vector
Drawing elements or objects such as lines, image in animation. Using numerical
rectangles, circles and so on to create an transformations the movement of that
images are based on Vector images. The image along its paths is calculated for their
advantage of vector image is relatively defining coordinates. The least frame rate
small amount of data is required to of at least 16 frames per second gives the
represent the image and thereby only less impression of smoothness and for natural
memory is needed to store. Compression looking it should be at least 25 frames
techniques are used to reduce the file per second. Animations may be in two or
size of images that is useful for storing three dimensional. The two dimensional
large number of images and speeding animation, bring an image alive, that occur
Chapter 1 Multimedia and Desktop Publishing 3
www.tntextbooks.org

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.

DIB (Device Independent Bitmap)


1.4 File Formats for This format which is similar to BMP,

Multimedia allows the files to be displayed on a variety
The following is an outline of current of devices.
file formats used for the production and
GIF (Graphics Interchange Format)
delivery of multimedia data.
GIF is a compressed image format.
1.4.1 Text Formats Most of the computer color images and
backgrounds are GIF files. This file format
RTF
is best suitable for graphics that uses only
Rich Text Format is the primary file format limited colors, and it is the most popular
introduced in 1987 by Microsoft with the format used for online color photos.
specification of their published products 13-bit Color look up table is used by the
and for cross-platform documents GIF format to identify its color values.
interchange. This format is supported widely.
Plain text JPEG (Joint Photographic
Plain text files can be opened, read, and Experts Group)
edited with most text editors. commonly JPEG was designed to attain maximum
used are Notepad (Windows), Gedit or image compression. It uses lossy
nano (Unix, Linux), TextEdit (Mac OS compression technique, where a
X) and so on. Other computer programs compression method is referred that
are also capable of reading and importing loses some of the data required for the
plain text. Plain text is the original and image reconstruction. It works good with
popular way of conveying an e-mail. photographs, naturalistic artwork, and
similar material but functions less on
1.4.2 Image Formats lettering, live drawings or simple cartoons.
TIFF (Tagged Image File Format)
TGA (Tagra)
This format is common in desktop
publishing world (high quality output), It is the first popular format for high-
and is supported by almost all software resolution images. TGA is supported by
packages. Recent versions of TIFF allows Most of the video-capture boards.

Chapter 1 Multimedia and Desktop Publishing 5


www.tntextbooks.org

PNG (Portable Network Graphics) AIFF (Audio Interchange File


An extensible file format for the less loss, Format)

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.

RA (Real Audio Format)


Real Audio format is designed for
streaming audio over the Internet. The
digital audio resources are usually stored
as a computer file in computer’s hard drive
or CD/DVD. Besides the variety of audio
file formats available, the most common
formats are wave files (.WAV) and MPEG
Layer-3 files (.MP3), WMA and RA.
Figure: 1.9 Image file Formats

1.4.3 Digital Audio File Formats


WAV (Waveform Audio File Format)
It is the most popular audio file format in
windows for storing uncompressed sound
files. In order to attain the reduced file
size it can also be converted to other file
formats like MP3.
Figure: 1.10 Digital Audio File Formats
MP3 (MPEG Layer-3 Format)
MPEG Layer-3 format is the most popular 1.4.4 Digital Video File Formats
format for storing and downloading music.
AVI (Audio/Video Interleave)
The MP3 files are roughly compressed to
one-tenth the size of an equivalent WAV file. AVI is the video file format for Windows.
Here sound and picture elements are
OGG stored in alternate interleaved chunks in
A free, open source container format that the file.
is designed for obtaining better streaming
MPEG (Moving Picture
and evolving at high end quality digital
Experts Group)
multimedia. It can be compared to MP3
files in terms of quality. MPEG is a standard for generating digital
video and audio compression under the
6 Chapter 1 Multimedia and Desktop Publishing
www.tntextbooks.org

International Standards Organization 1. Conceptual Analysis and Planning


(ISO) by the group of people. The group The process of multimedia making
has developed MPEG-1, the standard begins with a conceptual ignition
on which Video CD and MP3 are based, point. Conceptual analysis identifies
MPEG-2, the standard that supports a appropriate theme, budget and
products as Digital Television set top content availability on that selected
boxes and DVD, MPEG-4, the standard theme. Additional criteria like
for multimedia and mobile web.MPEG- copyright issues also are considered
7, the standard for search of audio and in this phase.
visual content. Research on MPEG-21 2. Project design
“Multimedia Framework” has started in
Once the theme is finalized
2000. Simply MPEG is the standards for
objectives, goals, and activities are
digital video and audio compression.
drawn for the multimedia project.
General statements are termed
as goals. The specific statements
in the project is known as the
objectives. Activities are series of
actions performed to implement an
objective. These activities contribute
to the Project design phase.
3. Pre-production
Based on the planning and design, it
is necessary to develop the project.
The following are the steps involved
in pre-production:
4. Budgeting
Figure: 1.11 Digital Video File Formats
Budgeting for each phases like
consultants, hardware, software,
1.5 Multimedia Production travel, communication and
1.5.1 Steps in Multimedia publishing is estimated for all the
Production multimedia projects.
Adequate time and efficient planning 5. Multimedia Production Team
is required for multimedia production, The production team for a high-
which assures that the project will be end multimedia project requires a
proceed smoothly and certainly ensures team efforts. The team comprises
that the information reaches the target of members playing various roles
audience. Following are the phases for and responsibilities like Script
development of complex multimedia writer, Production manager, Editor,
projects. Graphics Architect, Multimedia
Architect and Web Master.

Chapter 1 Multimedia and Desktop Publishing 7


www.tntextbooks.org

6. Hardware/Software Selection action. This structure defines the


All multimedia Application requires activities, responsible person for
appropriate tools to develop and each activity and the start/end time
playback the application. Hardware for each activity.
includes the selection of fastest 9. Production
CPU, RAM and huge monitors, In the multimedia application,
sufficient disc for storing the after the pre-production activities,
records. Selection of the suitable the production phase starts. This
software and file formats depends phase includes the activities like
on the funds available for the project background music selection,
being developed. sound recording and so on. Text is
7. Defining the Content incorporated using OCR software,
Content is the “stuff ” provided by Pictures shot by digital camera,
content specialist to the multimedia Video clips are shot, edited and
architect with which the application compressed. A pilot project is ready
is developed, who prepares the by this time.
narration, bullets, charts and tables 10. Testing
etc. The complete testing of the pilot
8. Preparing the structure product is done before the mass
A detailed structure must have production to ensure that everything
information about all the steps is in place, thereby avoiding the failure
along with the timeline of the future after launch. If it’s an web based product,

Conceptual Analysis and


Defining the Content
Planning

Project Design Preparing the Structure

Pre Production Production

Budgeting Testing

Documentation & Delivering the


Multimedia Production Team
Multimedia Product

Conceptual Analysis and


Hardware/Software Selection
Planning

Figure 1.12 Steps in Multimedia Production

8 Chapter 1 Multimedia and Desktop Publishing


www.tntextbooks.org

its functioning is tested with different multimedia production application


browsers like Internet Explorer, requires a specialize team comprises of
Chrome, Mozilla and Netscape the following members:
Navigator. If it is a local multimedia 1. Production Manager
application on a LAN it must be
In a multimedia production, the role
deployed in the server for testing
of production manager is to define,
purpose. After the testing process are
and coordinate, the production of
over, the product is incorporated with
the multimedia project in time and
valid suggested changes.
with full quality. The production
11. Documentation manager should be an expertise in the
User documentation is a mandatory technology expert, good at proposal
feature of all multimedia projects. writing, good communication skills
The documentation has all the and budget management skills. Also
valuable information’s starting must have experience in human
from the system requirement till resource management and act as an
the completion of testing. Contact efficient team leader.
details, e-mail address and phone 2. Content Specialist
numbers are provided for technical
Content specialist is responsible
support and sending suggestions
for performing all research
and comments.
activities concerned with the
12. Delivering the Multimedia Product proposed application’s content.
Multimedia applications are Program content refers to projects
best delivered on CD/DVD or in information, graphics, data or facts
the website . In reality various presented through the multimedia
challenges are faced while delivering production.
through internet, like bandwidth 3. Script Writer
problems, huge number of plug-
Video and film scripts represents
ins required to play audio and
a linear sequence of events. The
video and long downloading time.
script writer visualizes the concepts
Finally, a multimedia application
in three dimensional environments
is delivered in a more effective way
and if needed uses the virtual reality
by the integration of two mediums
integration into the program.
CD-ROM/DVD and Internet.
4. Text Editor
1.5.2 Multimedia Production The content of a multimedia
Team production always must flow
Managing team members in a way to get logically and the text should
maximum outcome with high degree of always be structured and correct
efficiency is mandatory in multimedia grammatically. Text and narration is
production. The fine quality high-end an integrated part of the application.

Chapter 1 Multimedia and Desktop Publishing 9


www.tntextbooks.org

Production manager Content specialist Script writer Text editor

Multimedia architect Computer graphic artist Audio and video specialist Web master
computer programmer

Figure: 1.13 Multimedia Production Team

5. Multimedia Architect 9. Web Master


The multimedia architect integrates The responsibility of the web
all the multimedia building blocks master is to create and maintain an
like graphics, text, audio, music, Internet web page. They converts
video, photos and animation by a multimedia presentation into a
using an authoring software. web page. Final multimedia product
6. Computer Graphic Artist is ready for consultation is a joint
The role of Computer Graphic Artist effort of the entire team. Initially,
is to deal with the graphic elements the production manager identifies
of the programs like backgrounds, the project content, while the
bullets, buttons, pictures editing, web master provides access to a
3-D objects, animation, and logos wide range of community through
etc. web-services.
7. Audio and Video Specialist
1.6 Multimedia on Internet
The roles of these specialists are
Major applications have been developed
needed for dealing with narration
with the integration of internet and
and digitized videos to be added in
multimedia like maps, media rich blogs
a multimedia presentation. They are
etc. A comprehensive study on use of
responsible for recording, editing
internet and multimedia in USA says that
sound effects and digitizing.
an estimated 55 million consumers use
8. Computer Programmer
Internet radio and video services each
The computer programmer writes month. Image is the most widely used
the lines of code or scripts in the multimedia resource on internet. Social
appropriate language. These scripts networking sites like Facebook (www.
usually develops special functions facebook.com) also enables multimedia
like developing the software to give rich contents to be exchanged online.
the size and shape of video windows,
controlling peripherals and so on.

10 Chapter 1 Multimedia and Desktop Publishing


www.tntextbooks.org

Figure: 1.14 Multimedia on Internet

1.7 Applications of provide students with flexible and



Multimedia decentralized learning environment
based on their educational
Multimedia is the most fast growing area
background.
in the field of information technology. A
Multimedia is an application which has In India, multimedia is used
  
in its use collection of multiple media in different ways for teaching and
sources like text, images, sound/audio, learning like e-learning, distance
animation and video on a single platform. learning, virtual learning and so
Predominantly, Entertainment and on. EDUSAT (Education Satellite)
Education are the fields where multimedia is launched in India for serving the
is used in majority. educational sector of the country for
emulating virtual classroom in an
1. Education effective manner.
Multimedia plays an vital role in 2. Entertainment
offering an excellent alternative
The remarkable advancement in the
method to traditional teaching by
entertainment industry is due to the
allowing the students to explore
Multimedia Technology mainly. This
and learn various concepts through
technology is needed in all mode of
animation. Students, teachers and
entertainment like radio, TV, online
the parents enjoy this multimedia
gaming, video on demand etc.
mode of learning and multimedia
learning materials. Many educators Video on demand or movies
  
accepts multimedia introduces new on demand is a service that
ways of thinking in the classroom. provides movies to television sets
Multimedia based teaching and on an individual basis at homes.
learning system named as MODULO Movies are stored in a central
at GMU in Germany developed is a server and transmitted through
web-based environment that aims to a communication network. A

Chapter 1 Multimedia and Desktop Publishing 11


www.tntextbooks.org

set-top box connected to the enriched with animation, video, still


communication network converts pictures, graphics, diagrams, maps,
the digital information to analog audio and text. Banks uses kiosks in
signals and inputs it to the television the form of ATM machines.
set. 6. Multimedia Conferencing
3. Business Systems Multimedia conferencing or video-
Business applications for conferencing is a system that
multimedia include presentations, performs face-to-face interactions
training, internet protocols and so among participating users, located
on. The marketing and advertising far from each other, as if they were
agencies are using animation sitting and discussing in a single
techniques for sales promotion. room.
Multimedia is used very commonly
for building employee ID. High 1.8 Libraries, Information


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

2. Webcasting and Video parent organization. Introduction


Conferencing of CD/DVD and their writers
The live telecast of real time programs has solved few of the problems of
through internet is known as libraries in storing or achieving
Webcasting. Video conferencing is the materials. Multimedia tools
the process of conducting conference along with CD-writers is made
between more than two participants possible to publish information
at different sites by using computer from different sources in a most
networks to transmit audio and video easy to use and acceptable form to
data. library users.
3. User Orientation Program 5. Digital Multimedia Libraries
The role of multimedia plays an Information’s are available in
vital role in training the librarians digital formats that include digital
in schools, colleges and universities books, scanned images, graphics
due to its interactivity. Hence, it is and digitized audio-visual clips etc.
used in depth subject training to Initially digital library projects were
their faculties. based only on textual data, later it
4. In-house Production of Multimedia was on all other media elements like
Resources and E-publishing images, audio and video recordings
Many libraries produce multimedia were also integrated under the
resources in-house, to serve the collection of digital library.

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.

Chapter 1 Multimedia and Desktop Publishing 13


www.tntextbooks.org

Multimedia Multimedia allows the users to combine and


change data from various sources like image,
text, graphics, video, audio and video to a single
platform.

Raster or Bitmap Images The common and comprehensive form of


storing images in a computer is raster or bitmap
image.

Vector Images I is relatively small amount of data is required


to represent the image and thereby only less
memory is needed to store.

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

Path Animation Path animation involves moving an object on


a screen that has a constant background e.g. a
cartoon character may move across the screen
regardless of any change in the background or the
character.

Musical Instrument Digital Musical Instrument Digital Identifier (MIDI) is


Identifier (MIDI) a standard communication tool developed for
computers and electronic instruments.

14 Chapter 1 Multimedia and Desktop Publishing


www.tntextbooks.org

EVALUATION

Part - I 3. Sound – MPEG


Choose the correct answer 4. Video – RTF
1. ________ refers to any type of a. 1, 2, 3, 4 b. 2, 3, 4, 1
application that involves more than c. 4, 1, 2, 3 d. 3, 4, 1, 2
one type of media such as text, 6. find the odd one on the following
graphics video animation and sound which is not an image format
a) an executable file a) TIFF b) BMP
b) desktop publishing c) RTF d) JPEG
c) multimedia 7. ___ is the process displaying
d) hypertext still images they give continuous
2. one of the disadvantages of the movement
multimedia is its __ a) Text formats
a) cost b) Sound
b) adaptability c) MP3
c) usability d) Animation
d) relativity 8. The live telecasting of real time
3. expand JPEG program through Internet is known
a) joint photo experts gross as ____
b) joint photographic experts group a) web casting
c) joint processor experts group b) web hosting
d) joint photographic expression c) data manipulation

group d) none of the above
4. you need hardware, software and __ 9. GIF use _______ color look up table
to make multimedia a) 8 bit
a) network b) 8 KB
b) compact disk drive c) 8 MB
c) good idea d) 8 GB
d) programming knowledge 10. RTF file format was introduced by
5. match the following by choosing the ______
right one a) TCS
1. Text – TGA b) Microsoft
2. Image – MIDI c) Apple
d) IBM

Chapter 1 Multimedia and Desktop Publishing 15


www.tntextbooks.org

Part - II 3. Write roles and responsibilities of


Short Answers Production team members
1. Define Multimedia and their features 4. Describe the various file formats in
2. List out Multimedia Components multimedia
3. Classify the TEXT component in 5. Explain animation industry and
multimedia their scope
4. Classify the IMAGE component in
Part - IV
multimedia
Explain in detail
5. Define Animation and their features
1. Explain in detail Process of
6. List out image file formats
Multimedia
7. List out audio file formats
2. Explain in detail Techniques of
8. List out video file formats Animation
9. Define Multimedia Production 3. Explore the opportunities Animation
10. List out Multimedia Production filed movie industry
team members 4. Explain in detail about production
team Roles and Responsibilities
Part - III
Explain in Brief Answer 5. Explain about different file formats
1. Briefly explain about Multimedia in multimedia files
Components
2. Describe the features and techniques
of animation

16 Chapter 1 Multimedia and Desktop Publishing


www.tntextbooks.org

02
CHAPTER

An Introduction to Adobe Pagemaker

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

2.1 Desktop Publishing 2.2 Introduction to Adobe



We hear and see the term ‘Desktop PageMaker
publishing’ a lot these days. What Adobe PageMaker is a page layout software.
exactly is it? What does it mean? Desktop It is used to design and produce documents
publishing (abbreviated DTP) is the that can be printed. You can create anything
creation of page layouts for documents from a simple business card to a large book.
using DTP software.
Page layout software includes tools
Today, there are several Desktop that allow you to easily position text
Publishing (DTP) software available in and graphics on document pages. For
the market. Some of the popular DTP example, using PageMaker, you could
software are Adobe PageMaker, Adobe create a newsletter that includes articles
InDesign, QuarkXPress, etc. and pictures on each page. You can place

Figure 2.1 Various page layout softwares


17
www.tntextbooks.org

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

2.3 Opening PageMaker


In the Windows 7 operating system, we can open Adobe PageMaker using the command
sequence Start→All Programs → Adobe → Pagemaker 7.0 → Adobe PageMaker 7.0.
The Adobe PageMaker window will be opened as shown in Figure 2.2

Figure 2.2 Adobe PageMaker window

2.4 Creating a New Document



To create a new document,
1. Choose File > New in the menu bar. (or) Press Ctrl + N in the keyboard. Now
Document Setup dialog box appears.(Figure 2.3)
2. Enter the appropriate settings for your new document in the Document Setup dialog
box.
3. Click on OK.
18 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org

Now a new document


called Untitled - 1 opens
on the screen as shown in
Figure 2.4.
A document page
is displayed within a dark
border. The area outside of
the dark border is referred to
as the pasteboard. Anything
that is placed completely
in the pasteboard is not
visible when you print the
document. You can use the
pasteboard to temporarily hold
elements while designing your
document.

Figure 2.3 Creating a New Document

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

Pages Horizontal scroll bar

Figure 2.4 Workspace

Chapter 2 An Introduction to Adobe Pagemaker 19


www.tntextbooks.org

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

Figure 2.5 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

Figure 2.6 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

Figure 2.7 Toolbar

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

Pointer Tool Text Tool

Rotating Tool Cropping Tool

Line Tool Constrained Line Tool

Rectangle Tool Rectangle Frame Tool

Ellipse Tool Ellipse Frame Tool

Polygon Tool Polygon Frame Tool

Hand Tool Zoom Tool

Figure 2.8 Toolbox

1. Click on Window. The Window menu will appear.


2. Click on Show tools.
The toolbox appears in front of your document window. If you want to hide the
toolbar, you can perform these steps to hide the toolbox.
1. Click on Window. The Window menu will appear.
2. Click on Hide tools to hide the toolbox.
Table 2.1 Keyboard Shortcuts
S. No. Tools Keyboard Short Cut
1 Pointer Tool F9
2 Rotating Tool Shift + F2
3 Line Tool Shift + F3
4 Rectangle Tool Shift + F4
5 Ellipse Tool Shift + F5
6 Polygon Tool Shift + F6
7 Hand Tool Shift + Alt + Drag Left mouse button
8 Text Tool Shift + Alt + F1
9 Cropping Tool Shift + Alt + F2
10 Constrained Line Tool Shift + Alt + F3
11 Rectangle Frame Tool Shift + Alt + F4

Chapter 2 An Introduction to Adobe Pagemaker 21


www.tntextbooks.org

Table 2.2 Tool Box Usage


Tool Toolbox Cursor Use

Used to select, move, and resize text objects


Pointer Tool
and graphics.

Text tool Used to type, select, and edit text.

Rotating tool Used to select and rotate objects.

Cropping tool Used to trim imported graphics.

Line tool Used to draw straight lines in any direction.

Constrained line
Used to draw vertical or horizontal lines.
tool

Rectangle tool Used to draw squares and rectangles.

Rectangle frame Used to create rectangular placeholders for


tool text and graphics.

Ellipse tool Used to draw circles and ellipses.

Used to create elliptical placeholders for


Ellipse frame tool
text and graphics.

Polygon tool Used to draw polygons.

Used to create polygonal placeholders for


Polygon frame tool
text and graphics.

Used to scroll the page (an alternative to


Hand tool
the scroll bar)

Used to magnify or reduce an area of the


Zoom tool
page.

22 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

Scroll bars 2.6 Editing Text in the


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

To Select Press 2.6.4 Copying and Moving Text


The Copy and Paste commands of
One character to the left Shift + ← PageMaker can be used to copy text from
One character to the right Shift + → one location in a document and paste it
at another location. The Copy command
One line up Shift + ↑ creates a duplicate of the selected text,
One line down Shift + ↓ leaving the original text unchanged. The
Paste command pastes the copied text at the
To the end of the current Shift +End position where the insertion point is placed.
line
The Cut and Paste commands can
To the beginning of the Shift + be used to move text from one position
current line Home in a document to the other. The Cut
Entire Document Ctrl + A command deletes the selected text from
its original position. The Paste command
then places this text at the position where
2.6.2 Deleting Text
the insertion point is placed.
You can easily delete a character, or word,
or block of text. Moving the Text
To delete a character, do the following : The selected text can be easily cut and
1. Position the insertion point to the pasted in the required location.
left of the character to be deleted.
To cut and paste text .
2. Press Delete key on the keyboard.
1. Select the text to be moved.
(or)
2. Choose Edit > Cut in the menu bar.
3. Position the insertion point to the
(or) Press Ctrl + X in the keyboard
right of the character to be deleted.
(or) Click the right mouse button and
4. Press Backspace key on the choose cut from the pop-up menu.
keyboard. 3. Insertion point is moved to the place
To delete a block of text, do the following : where the text is to be pasted.
1. Select the text to be deleted. 4. Choose Edit > Paste in the menu bar.
2. Press Delete or Backspace in (or) Press Ctrl + V in the keyboard.
the keyboard (or) Edit > Clear (or) Click the right mouse button and
command. choose Paste from the pop-up menu.
The text can also be pasted in this way
2.6.3 Undo Command to another or another type of document.
The Undo command is used to reverse the
action of the last command. To reverse The following keyboard shortcuts
the last command, click on Edit>Undo in can be used to move text
the menu bar (or) press Ctrl + Z in the Ctrl + X → to Cut
keyboard.
Ctrl + V → to Paste

24 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

Copying the Text


Keyboard shortcuts for copy and paste:
The selected text can be easily copied and
pasted in the required location. Ctrl + C → to Copy
Ctrl + V → to Paste
To copy and paste text .
1. Select the text to be coped.
2.7 Text Block
2. Choose Edit > Copy in the menu bar
(or) Press Ctrl + C in the keyboard A text block contains text you type, paste,
(or) Click the right mouse button or import. You can’t see the borders of a text
and choose Copy from the pop-up block until you select it with the pointer tool.
menu. You create text blocks in two ways:
3. Insertion point is moved to the place 1. Click or drag the text tool on the page
or pasteboard, and then type.
where the text is to be pasted.
2. Click a loaded text icon in an empty
4. Choose Edit > Paste in the menu bar column or page.
(or) Press Ctrl + V in the keyboard
(or) Click the right mouse button 2.7.1 Creating a Text Block with
and choose Paste from the pop-up the Text tool
menu. To create a text block with the text tool:
The text can also be pasted in this way to 1. Select the text tool (T) from the
another location. toolbox. The pointer turns into an
I-beam. Refer Figure 2.9

Figure 2.9 Text creation using text tool

Chapter 2 An Introduction to Adobe Pagemaker 25


www.tntextbooks.org

2. On an empty area of the page or pasteboard, do one of the following:


Click the I-beam where you want to insert text. (Refer Figure 2.10) This creates a text
block the width of the column or page. By default, the insertion point jumps to the left
side of the text block.

Figure 2.10

3. Type the text you want.


Unlike with a text frame, you do not see the borders of a text block until you click the
text with the pointer tool. Refer 2.11

Figure 2.11 Text borders


26 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org

2.7.2 Moving a Text Block


To move a block without changing its shape, place the cursor anywhere inside the block,
and click and drag it to the required position. Refer 2.12

Figure 2.12 Moving a text block

2.7.3 Resizing a Text Block


When you select a text block with the Pointer tool, the block’s boundaries become
visible. Two handles are seen above and below the text block. These handles are called
Windowshades. There is a dark square on both ends of the handle. These are used to
change the size of the text block. Refer Figure 2.13 to Figure 2.15

Figure 2.13 Resizing text block-Step 1

Chapter 2 An Introduction to Adobe Pagemaker 27


www.tntextbooks.org

To resize a Text block


1. Click on the Pointer tool.
2. Click either the left or right corner handle on the bottom of the text block and drag.
When you release the mouse button, the text in the text block will reflow to fit the
new size of the text block.

Figure 2.14 Resizing text block-Step 2

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.

Figure 2.15 Resizing text block-Step 3

28 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

2.7.4 Splitting a Text Block into two


To split a text block into two
1. Place the cursor on the bottom handle, click and drag upwards.
When you release the bottom handle will contain a red triangle. Refer Figure 2.17-18

Figure 2.16 Splitting a Text block–Step 1

2. Click once on this, and the cursor changes to a loaded text icon.

Figure 2.17 Splitting a Text block–Step 2

Chapter 2 An Introduction to Adobe Pagemaker 29


www.tntextbooks.org

3. Position this where the second part of the text is to be, and click.

Figure 2.18 Splitting a Text block–Step 3

2.7.5 Rejoining split blocks


To rejoin the two text blocks
1. Place the cursor on the bottom handle of the second text block, click and drag the bottom
handle up to the top.
2. Then place the cursor on the bottom handle of the first text block, and click and drag
the bottom handle down if necessary.

2.7.6 Placing (Importing) Text


You can insert text from other software program like MS-Word in the PageMaker
documents. Refer Figure 2.19 to Figure 2.22
1. Choose File > Place. The Place dialog box will appear.

Figure 2.19 Importing Text


30 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org

2. Locate the document that contains the text you want to place and select it.

Figure 2.20 Document selection during import

3. Click on Open in the Place dialog box. Manual text flow


The pointer changes to the loaded text ●● Position the loaded text icon at a corner
icon ( ). of the area where you want to place
4. Make a text block to place the text. text, hold down the mouse button, and
(Or) Click in the page to place the drag to define the text block. Release
text. The text will be placed in the the mouse button.
page.
●● Text flows into the defined area. If there
If the text to be placed is too big to fit is more text than fits in the text block
on one page, PageMaker allows you you defined, a red triangle appears in
to place it on several pages. This can the bottom windowshade handle.
be done manually or automatically.

Chapter 2 An Introduction to Adobe Pagemaker 31


www.tntextbooks.org

Figure 2.21 Load Text

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

Figure 2.22 Continue loading text

32 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

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.

2.8 Understanding story


A PageMaker story is similar to a newspaper
article. The front page of a newspaper Figure 2.23 Unthreaded text
may contain several independent articles,
some of which continue on other pages. In
PageMaker, several stories may appear on
the same publication page and continue
elsewhere in the publication.

2.9 Threading text blocks


All text in PageMaker resides inside
containers called text blocks.
A Text block can be connected to
other text block so that the text in one text
block can flow into another text block. Figure 2.24 Threaded text-1

Chapter 2 An Introduction to Adobe Pagemaker 33


www.tntextbooks.org

Figure 2.25 Threaded text-2

2.9.1 To unthread a threaded Method - 2:


block Select the block that you wish to unthread
Method - 1: with the pointer tool. Then choose the
Select the block that you wish to unthread Text tool and select all the text in the
with the pointer tool. Click on Edit > Cut block. Then click on Edit > Cut in the
in the menu bar.(the block disappear). Now menu bar.(the block disappear). Now
click on the Edit > Paste in the menu bar. The click the insertion point within an existing
block will reappear in the same position, but threaded block. Then click on Edit > Paste
it is now an unthreaded block. in the menu bar. The text will be added in
this block.
BEWARE: if the block is in the
middle of a story, say the second 2.10 Placing Text in a Frame
of the three, the first block is now You can also use frames to hold text in
threaded directly to the third. place of using text blocks. Refer Figure 2.26

34 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

To place text in a Frame 4. Click on Place. The Place dialog box


1. Click on one of a Frame tool from will appear.
the Toolbox. 5. Locate the document that contains
2. Draw a frame with one of PageMaker’s the text you want to place, select it.
Frame tools (Rectangle frame tool or 6. Click on Open.
Ellipse Frame Tool or Polygon frame
7. Click in a frame to place the text in
Tool). Make sure the object remains
it.
selected.
3. Click on File. The File menu will The text will be placed in the frame.
appear.

Figure 2.26 Place text in a Frame

 In PageMaker, text and graphics that you draw or import are called objects.

 An object can be on a page or on the pasteboard.

 Text can be contained either in text blocks or text frames.

Chapter 2 An Introduction to Adobe Pagemaker 35


www.tntextbooks.org

2.10.1 Linking Frames containing 1. Draw a second frame with the


Text Frame tool of your choice.
A single frame may not be large enough to 2. Click the first frame to select it.
hold an entire story when you are using a 3. Click on the red triangle to load the
large amount of text, you can link frames text icon.
together so that an entire story is visible.
4. Click the second frame. PageMaker
To link Frames containing text flows the text into the second frame.

Figure 2.27 To link Frames containing text

2.10.2 Converting text in a Text block to a Frame


After created text in a text block, if you 3. Click the frame while pressing the
want to convert it to a frame. You can do Shift key. Now both elements will be
this by using these steps. selected.
1. Draw the frame of your choice using 4. Choose Element > Frame > Attach
one of the PageMaker’s Frame tool. Content on the Menu bar.
2. Select the text block you want to 5. Now the text appears in the frame.
insert in the frame. Refer Figure 2.28

36 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

Figure 2.28 Converting text in a Text block to a Frame

2.10.3 Separating Text from the


Frame Click on the Save icon( ) in the
Tool bar. (or)
Once text has been attached to a frame or
flowed inside it, you can separate the text Press Ctrl + S in the Keyboard.
and frame. A Save Publication dialog box as
To separate text from a frame shown in the Figure 2.29 appears on
the screen.
1. Click the frame with the Pointer tool.
2. Choose Element > Frame > Delete
Content in the menu bar. The text
will not appear in the frame.

2.11 Saving, Closing and



Opening Documents
The below section explains about various
operations with the documents.
2.11.1 Saving a Document
You can save your document for future
Figure 2.29 Saving a Document
use. Saving a document allows you to
review later and edit the document. Saved 2. The file name is given in the File
file can be used on other computer also. name list box.
To save a document for a first time 3. Then click on the Save button to
following steps are used: save the document. The document
1. (a) Choose File > Save in the menu is now saved and a file name appears
bar. (or) in the title bar.
Chapter 2 An Introduction to Adobe Pagemaker 37
www.tntextbooks.org

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.

Figure 2.30 Saving a Document with a new name or in a different location

2.12 Closing a Document 2.13 Opening an existing



After a document is saved, it is not closed. It Document
remains open so that the user can continue To open a document that has been saved
working. When the work is finished, the and closed the following steps are used:
user should save and close the document.
1. (a) Choose File > Open in the menu
After saving, the document can be bar (or)
closed using the File > Close command in Click on the Open icon ( ) in the
the menu bar (or) Ctrl +W in the keyboard. Tool bar (or)
38 Chapter 2 An Introduction to Adobe Pagemaker
www.tntextbooks.org

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

One character to the Right Arrow


right

One word to the left Ctrl + Left Arrow

One word to the right Ctrl + Right Arrow

Up one line Up Arrow


Figure 2.31 Opening an existing Document
Down one line Down Arrow
2. The file name is given in the File
To the end of a line End
name list box.
The name of the file to be opened To the beginning of a Home
line
can be chosen from the list, which is
displayed. Up one paragraph Ctrl + Up Arrow
3. Then click on the Open button. Down one paragraph Ctrl + Down
Now the required file is opened. Arrow

2.14 Moving Around the 2.15 Scrolling the Document



Document
In PageMaker, there are two sets of scroll
We can move the insertion point to bars; one for up and down movement and
anywhere in the document by using the the other for the left and right movement
mouse or the Keyboard. of the document.
To move the insertion point with PageMaker’s scroll bars work differently
the mouse, the mouse pointer is moved to than those in a word processor. Note that
the required spot and the mouse button is they are set to the center of each bar. Also,
clicked. The insertion point jumps to that they scroll only the page you are currently
spot. It is to note that mouse pointer is on. Use the scroll bar on the right side to
different from the insertion point. move up and down. Use the scroll bar at
To move the insertion point with the bottom to move left and right.
the keyboard the arrow keys and other key The scrolling procedure is as follows:
combination can be used.
1. To scroll left and right the left and
The below Table 1.1 lists the right arrow respectively should be
common movement keys. If the key clicked.
Chapter 2 An Introduction to Adobe Pagemaker 39
www.tntextbooks.org

2. To scroll up and down the up and To magnify part of a page by


down arrow respectively should be dragging:
clicked. 1. Select the zoom tool.
3. To scroll a relative distance in the 2. Drag to draw a marquee around the
document the scroll box should be area you want to magnify.
drawn up or down.
To zoom in or out while using
another tool:
2.16 Magnifying and
Press Ctrl+Spacebar to zoom in. Press

reducing with the zoom
Ctrl+Alt+Spacebar to zoom out.
tool
Use the zoom tool to magnify or reduce
the display of any area in your publication.
You can also double-click the zoom tool
to jump to Actual Size, or press Alt as
you double-click the tool to go to Fit in
Window view. Refer Figure 2.32

To magnify or reduce with the zoom


tool:
1. Select the zoom tool.
The pointer becomes a magnifying
glass with a plus sign in its center,
indicating that the zoom tool will
magnify your view of the image.
(The magnifying glass shows a
minus sign in its center when in
reduction mode.) To toggle between
magnification and reduction, press
the Ctrl key.
2. Position the magnifying glass at Figure 2.32 To magnify or reduce with the zoom

the center of the area you want to tool
magnify or reduce, and then click to
zoom in or out. 2.17 Formatting a Document
Continue clicking until the Formatting is the process of changing
publication is at the magnification the general arrangement of text, i.e.,
level you want. When the publication improving the appearance of the text by
has reached its maximum using various fonts, fonts colors, and font
magnification or reduction level, styles. A font is a set of letters, numbers or
the center of the magnifying glass symbols in a certain style. Each font looks
appears blank. different from other fonts.

40 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

2.17.1 Character Formatting 3. Make the appropriate changes in the


using Character dialog box.
Specifications Dialog Box
●● Click the drop-down menu
Character formatting means displaying arrow of the Font box and
text in a certain way. Character formatting select the desired font.
consists of text properties - bold, italic, ●● Click the drop-down menu
underline, font type, font size, font colour, arrow of the Font Size box and
etc. Refer Figure 2.33, 2.34 and 2.35 select the font size.
The steps to apply character ●● Click the drop-down menu
formatting to text are as follows : arrow of the Font Color box
1. Select the text to be formatted. and select the desired colour.
2. Choose Type > Character in menu ●● Click the Bold, Italic, or
bar (or) Press Ctrl + T on the Underline buttons to make the
keyboard. text bold, italic, or underlined
The Character Specifications dialog respectively.
box appears. 4. Click on OK.

Figure 2.33 Character Formatting using Character Specifications


Dialog Box

2.17.2 Character Formatting If the Control palette is not showing then


using the use the following steps:
Control Palette
1. Click on Window > Show Control
The Control Palette is especially useful Palette sequence in the menu bar.
when you are doing lot of formatting. (or)
Its features change based on the 2. Press Ctrl + ‘ in the keyboard.
object that is selected on your layout. Now the Control Palette appears on
the window.

Chapter 2 An Introduction to Adobe Pagemaker 41


www.tntextbooks.org

To modify character attributes using the Character Control Palette:


1. Select the text you want to modify.
2. Make the appropriate changes in the Control palette. Refer Figure 2.34

Font Font Size Tracking

Small Caps
Leading Horizontal Baseline
Bold
Italic Scale Shift
Underline
Figure 2.34 Character Control Palette

Font:
Arial Black
Bold

Underlined

Font Size: 60pt

Small
Caps

Italic

Figure 2.35 Modify character attributes using the Character Control Palette

42 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

2.17.3 Changing Text Colour


You can change the colour of the text.
Your design may look beautiful if you
choose a text colour other than black.
To color characters
1. Select the text you want to colour.
2. Choose Window > Show Colors
in Menu bar. The Colors palette
appears. Refer Figure 2.36
Click the color you want to apply
to the selected text.
The characters change to the
colour you selected in the palette.

Figure 2.36 Colors palette

2.18 Drawing Line tool that draws only at increments of


45 degrees. You can change the property
There are so many drawing tools in
of tools by double-clicking on them. Refer
PageMaker. Line tool, Rectangle tool,
Figure 2.37 to Figure 2.40
Ellipse tool and Polygon tool are four
main drawing tools. To draw a line
2.18.1 Drawing Lines 1. Select the Line tool from the toolbox.
The cursor changes to a crosshair.
PageMaker has two Line tools. The
first one creates a straight line at any 2. Click and drag on the screen to draw
orientation. The second is a constrained your line. As you drag, a line appears.

Chapter 2 An Introduction to Adobe Pagemaker 43


www.tntextbooks.org

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.37 Drawing Lines

To draw a Dotted line


Figure 2.40 Dotted line
1. Double click the Line tool from the
toolbox. A Custom Stroke dialogue 2.18.2 Drawing Rectangles or
box appears. Ellipses
You can also draw rectangles and ellipses
shapes by using the same technique as used
in line drawing. Refer Figure 2.41 and 2.42
1. To draw a rectangle or ellipse:
Click on the Rectangle or Ellipse
Figure 2.38 Custom Stroke tool from the toolbox.
The cursor changes to a crosshair.
2. Select the required Stroke style in
2. Click and drag anywhere on the
the drop-down list box.
screen. As you drag, a rectangle or
ellipse appears.
3. Release the mouse button when the
rectangle or ellipse is of the desired
size.
Press the Shift key while you’re
drawing to constrain the shape to a
square or circle.
Figure 2.39 Stroke style

44 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

Figure 2.41 Draw a Rectangle or Ellipse

Drawing a Rounded Corner 2.18.3 Drawing Polygon


Rectangle To draw a Polygon
To draw a rounded-corner rectangle: 1. Click on the Polygon tool from the
1. Double-click the Rectangle tool in toolbox.
the toolbox. The cursor changes to a crosshair.
The Rounded Corners dialog box
2. Click and drag anywhere on the
appears.
screen. As you drag, a Polygon
2. Choose a corner setting from the
appears.
preset shapes.
3. Click on OK. The cursor changes to 3. Release the mouse button when the
a crosshair. Polygon is of the desired size. Refer
4. Click and drag anywhere on the Figure 2.43
screen.
5. Release the mouse button when the
rectangle is the desired size.
Press the Shift key as you draw to
constrain the shape to a rounded-
corner square.

Figure 2.42 Draw a Rounded Corner Rectangle Figure 2.43 draw a Polygon

Chapter 2 An Introduction to Adobe Pagemaker 45


www.tntextbooks.org

2.18.4 Drawing a Star using


Polygon tool
To draw a Star
1. Click on the Polygon tool from the
toolbox.
The cursor changes to a crosshair.
2. Click and drag anywhere on the
Figure 2.45 Polygon tool setting
screen. As you drag, a Polygon
appears.
3. Release the mouse button when the
Polygon is of the desired size.
4. Choose Element > Polygon Settings
in the menu bar.
Now Polygon Settings dialogue box
appears.
5. Type 5 in the Number of sides text
box.
6. Type 50% in Star inset textbox. Figure 2.46 Polygon
7. Click OK. Now the required star
appears on the screen. Refer Star Inset percentage bends the
Figure 2.44 - 2.46 polygon lines inwards to form a
star-shaped object.

Drawing a star with given number of


sides and required inset
1. The value of ‘Star inset’ is 50%
The number of sides is 15
The result of the star shape is shown
Figure 2.47.

Figure 2.44 Drawing a Star using Polygon tool


Figure 2.47 Drawing a star-1

46 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

2. The value of ‘Star inset’ is 25%


The number of sides is 25
The result of the star shape is shown
Figure 2.48.

Figure 2.50 Show colors

Figure 2.48 Drawing a star-2

3. The value of ‘Star inset’ is 35%


The number of sides is 70
The result of the star shape is shown
Figure 2.49.

Figure 2.49 Drawing a star-3 Figure 2.51 Filling Shapes with Colors and

Patterns

2.18.5 Filling Shapes with 2.19 Working with pages


Colors and Patterns
The main purpose of PageMaker is
Filling Rectangle with colour
composing pages. You can insert new
1. Draw a rectangle using Rectangle tool.
pages into a document, remove existing
2. Select the rectangle. pages, move between pages, and sort pages
3. Choose Window > Show colors in in a large document.
the menu bar. (or) Press Ctrl + J
Now Colors palette appears. 2.19.1 Going to a
specific Page
4. Click on the required colour from
the Colors Palette. Pagemaker provides several methods
for navigating the pages in your
5. The rectangle has been filled with the
publication.
colour. Refer Figure 2.50 and 2.51
Chapter 2 An Introduction to Adobe Pagemaker 47
www.tntextbooks.org

Method 1: 2.19.2 Inserting Pages


You can move from one page to another You can add more pages to a document. You
by using the Page up and Page down keys can insert pages before, after, or between
on your keyboard. This is probably the the pages you’re currently viewing. When
navigation methods you will use most often. you insert pages, PageMaker automatically
renumbers the pages in your publication.
Method 2:
Refer Figure 2.54 and 2.55
You can move from one page to another
by using the page icons at the left bottom To insert pages
of the screen. Click on the page icon that 1. Go to the page immediately before
corresponds to the page that you want to the page you want to insert.
view. The page is displayed.
2. Choose Layout > Insert Pages in the
Method 3: menu bar. The Insert Pages dialog
Using the Go to Page dialog box. Refer box appears.
Figure 2.52 and 2.53
To go to a specific page in a document
1. Choose Layout > Go to Page in the
menu bar (or) Press Alt + Ctrl + G
in the keyboard. Now the Go to Page
dialog box appears.

Figure 2.54 Insert Page

3. Type the number of pages you want


to insert.
4. To insert pages after the current
page, choose ‘after’ from the pop-up
menu.
5. Click on Insert.
Figure 2.52 Go to page

2. In the dialogue box, type the page


number that you want to view.

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

2.19.3 Removing Pages Master Pages commonly contain


You can remove the unused pages from your repeating logos, page numbers, headers,
document with a Remove Pages dialog box. and footers. They also contain nonprinting
layout guides, such as column guides,
1. Choose Layout > Remove Pages in
ruler guides, and margin guides.
the menu bar. The Remove Pages
dialog box appears. Refer Figure 2.56 A master item cannot be selected
and 2.57 on a document page.
You can create, modify, and delete
objects on master pages just like any other
objects, but you must do so from the
master pages themselves.
At the lower left corner of a
document (publication) window you can
find an icon which represents the master
pages. The letters L and R (L denotes left
and R denotes right) mark the master
page icon for facing pages. A single-sided
publication icon is marked by an R alone.
Figure 2.56 Remove pages
Refer Figure 2.58

2. Type the page range you want to


remove.

Figure 2.57 Remove pages settings Figure 2.58 Master Pages

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

4. Press Ctrl + Alt + P.


5. The page number displays as ‘LM’ on the left master page.
6. Similarly click on the right Master page where you want to put the page number.
7. Press Ctrl + Alt + P.
8. The page number displays as ‘RM’ on the right master page, but will appear correctly
on the actual pages. Refer Figure 2.59

Figure 2.59 Inserting Page Numbers in Mater Pages

2.20.2 Hiding Master Items 2.20.3 Showing Master Page


To make the master items invisible on a Palette
particular page, switch to the appropriate Master Pages palette organize all the
page, then choose View > Display Master command you will need to work with
items (which is usually ticked). Refer Fig 2.60 Master Pages. Refer Figure 2.61 and 2.62
To show Master Page Palette
1. Choose Windows> Show Master
Pages in the menu bar. The Master
Pages Palette appears.

Figure 2.60 Hiding maser page items Figure 2.61 Master page palette

50 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

When you create a new Master


Page, you will be asked to name the new
Master page and set its margins and
column guides.

To create a new Master Page


1. Click the New Master Page icon in
the Master Pages palette. The New
Master Page dialog box appears.
2. Enter the name of the new master
page in the Name field.
Master Pages tab Master Pages List
3. Make the appropriate changes in the
Margins and Column Guides fields.
4. Click on OK. A new Master Page
appears in the Master Pages palette.
Refer Figure 2.63 and 2.64

Pop-up Menu

Figure 2.63 Create master pages

New Master Page Delete


Pages icon Icon

Figure 2.62 Master page

2.20.4 Creating Master Pages


By default, all Pagemaker documents have
a Master Page already created ‘Document
Master’. But sometimes you will require
more than one Master Page.
You can set up multiple master pages
for any publication, each page containing
a specific combination of headers, footers,
page numbers, frames, and other elements
that you want to use over and over. Figure 2.64 Master page setting

Chapter 2 An Introduction to Adobe Pagemaker 51


www.tntextbooks.org

2.21 Print a document You can use commas to separate the


page numbers
1. Choose File > Print in the menu bar
(or) Press Ctrl + P in the keyboard. (e.g., 5,7,19).
The Print Document dialog box Use a hyphen to print page
appears. ranges(e.g., 10-17; this will print all
2. Choose the settings in the Print pages from page numbers 10 to 17).
Document dialog box as To print from a particular page to
●● Select the printer from the the end of the document, enter the
Printer drop-down list box. starting page number followed by a
hyphen (e.g., 5 - ).
●● Choose the pages to be printed
in the Pages group box by You may also combine individual
selecting one of the following page numbers and a range of pages
available options : (e.g., 5, 9, 15-26).
All: This option prints the whole Print : You can also print only odd-
document. numbered or even-numbered pages.
Select the Odd pages or Even pages
Ranges: This option prints individual
option from the Print drop-down
pages by the page number or a range
list box. Refer Figure 2.65
of pages.

Figure 2.65 Print Document setting

52 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

●● Type the number of copies you If the Collate option is selected,


want in the Copies text box. PageMaker will print a complete set
●● You can choose whether to of pages 1 to 5, then a second set,
collate the pages or not. Suppose and so on.
you want to print 4 copies of a 5 4. After choosing from the options in
pages document. the Print Document dialog box,
If the Collate option is not selected. click Print button to print the
PageMaker will first print 4 copies of document. Make sure the printer is
page 1, then 4 copies of page 2, and switched on.
so on.

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.

Chapter 2 An Introduction to Adobe Pagemaker 53


www.tntextbooks.org

Header Text that is repeated at the top of each page


Footer Text that is repeated at the bottom of each page
Symbol A sign or a special character that can be inserted in a PageMaker
document
Margins The amount of space between the text and the edge of the page on all
four sides
Orientation The direction(along the height or along the width) in which the page is
being printed
Menu A list of commands
Editing Making changes to the text
Undo Reversing the last command
Redo Reversing the Undo command

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

7. _________ tool is used for drawing 13. Adobe PageMaker is a ___________


boxes. software.
(a) Line 14. ________ Bar is the topmost part of
(b) Ellipse the PageMaker window.
15. _________ is the process of moving
(c) Rectangle
up and down or left and right
(d) Text
through the document window.
8. Place option is present in 16. ________ tool is used to draw a
_____________ menu. circle.
(a) File 17. The Insert pages option is available
(b) Edit on clicking the _________ menu.
(c) Layout
18. Match the following.
(d) Window
Cut - (i) Ctrl + Z
9. To select an entire document using
the keyboard, press ___________ Copy - (ii) Ctrl + V
(a) Ctrl + A Paste - (iii) Ctrl + X
(b) Ctrl + B Undo - (v) Ctrl + C
(c) Ctrl + C 19 Choose the odd man out.
(d) Ctrl + D i. Adobe PageMaker, QuarkXPress,
10. Character formatting consists Adobe InDesign, Audacity
of which of the following text ii. File, Edit, Layout, Type, Zip
properties? iii. Pointer Tool, Line tool, Hide Tool,
(a) Bold Hand Tool
(b) Italic iv. Bold, Italic, Portrait, Underline
(c) Underline 20. Choose the correct statement.
(d) All of these i. (a) Text can be selected using mouse

11. Which tool lets you edit text? only.
(a) Text tool (b) Text can be selected using mouse

(b) Type tool or the keyboard.
(c) Crop tool ii. (a) DTP is an abbreviation for

Desktop publishing.
(d) Hand tool
(b) DTP is an abbreviation for
12. Shortcut to print a document in

Desktop publication.
Pagemaker is ___________
(a) Ctrl + A 21 Choose the correct pair
(b) Ctrl + P (a) Edit and Cut
(c) Ctrl + C (b) Edit and New
(d) Ctrl + V (c) Undo and Copy
(d) Undo and Redo
Chapter 2 An Introduction to Adobe Pagemaker 55
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?

56 Chapter 2 An Introduction to Adobe Pagemaker


www.tntextbooks.org

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

3.1 Introduction to Database managing databases. The DBMS provides



Management System users and programmers with a systematic way
to create, retrieve, update and manage data.”
DBMS stands for Database Management
System, so let us break down the words what What type of data is stored in a
they really mean. A database is a place where database?
we store, retrieve and manage data. So what’s In a database, we would be grouping only
a data then? Meaningful information like related data together and storing them
your name, your favorite color etc to complex under one group name called table. This
data like astronomical data that scientist helps in identifying which data is stored
handle, everything comes under database. The where and under what name.
management system refers to a set of programs
to manage the data, we have with various 3.1.2 Evolution of DBMS
actions like storing, retrieving, filtering etc. The concept of storing the data started
Some of the popular Database Management before 40 years in various formats. In
System is MySQL, Oracle etc. Giving protection earlier days they have used punched card
to data, user-friendly for users etc, are some of technology to store the data. Then files
the notable features of good DBMS. were used. The file systems were known as
predecessor of database system. Various
3.1.1 Introduction to DBMS access methods in file system were
Definition: “A database management system indexed, random and sequential access.
(DBMS) is system software for creating and The file system had more limitations like
57
www.tntextbooks.org

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

Users Machines Devices Applications

Marketing Personnel
= Container

= Object
Figure: 3.1 Hierarchical database model

58 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

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.

3.2.3 Relational model


3.2.2 Network model
Oracle and DB2 are few commercial
The first developed network data model relational models in use. Relational model
was IDS (Integrated Data Store) at is defined with two terminologies Instance
Honeywell. Network model is similar to and Schema. See Figure 3.3
Hierarchical model except that in this
model each member can have more than Relational Database

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

identified the three database components surname:string


email:string
...

Network schema, Sub schema and


Language for data management. See
Figure 3.2
Figure: 3.3 Relational database model

Instance – A table consisting of rows and


ABC college columns
1:n Schema – Specifies the structure including
name and type of each column.
A relation (table) consists of unique
Department A College library attributes (columns) and tuples (rows).

3.2.4 Object-oriented database


n:1 model
It has two parents
This model incorporates the combination
Student of Object Oriented Programming(OOP’s)
concepts and database technologies.
Practically, this model serves as the base of
Figure: 3.2 Network Model Relational model. Object oriented model
Chapter 3 Introduction to Database Management System 59
www.tntextbooks.org

Age DeptName Budget


Name Salary

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

Figure: 3.4 Object-oriented database model

uses small, reusable software known 3.4 RDBMS Jargons


as Objects. These are stored in object
3.4.1 Database
oriented database. This model efficiently
manages large number of different data The most popular Relational Database
types. Moreover complex behaviors are is MySQL. It is an open source SQL
handled efficiently using OOP’s concepts. database supporting different platforms
See Figure 3.4 like Windows, Linux and MAC Operating
Systems. The other relational databases
available are Oracle, MS SQL Server and
3.3 Relational Database
MS Access. The features of RDBMS are
 
Management System
●● High Availability
Basic RDBMS concepts
●● High Performance
Any database whose logical organization
is based on relational data model is known ●● Robust Transactions and support
as Relational Database. A DBMS that ●● Ease of management
manages the relational database is known ●● Less cost
as Relational Data Base Management
System. RDBMS is basis for SQL and for 3.4.2 Table
all modern database systems like MySQL, In relational database model, table is
oracle and Microsoft Access. The basic defined as the collection of data organized
RDBMS concept includes Database, in terms of rows and columns. Table is the
Tables, Tuple, Attribute, Schema and Key simple representation of relations. The
which are discussed in RDBMS Jargons. true relations cannot have duplicate rows

60 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

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

Chapter 3 Introduction to Database Management System 61


www.tntextbooks.org

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.

1. Entity or Entity type Weak Entity


2. Attributes A weak entity is dependent on other
3. Relationship entities and it doesn’t have any primary
key like the Strong entity. It is represented
These are the general concepts which help
by double rectangle.
to create an ER diagram and produce an ER
model. With the help of these any database For Example:
design can be created and viewed to know Here the marks is the weak entity and
the concept in that database design. there are no unique id or primary key for
that entity. So they are dependent on the
3.5.2 Entity or Entity type
existence of the other entity. See Table 3.3
An Entity can be anything a real-world
object or animation which is easily
identifiable by anyone even by a common
man. Exam Subject Pass/Fail

Eg: In a company’s database Employee, HR,


Manager are considered as entities, where
each of these entity will be having their Marks
own attributes. An entity is represented by
a rectangular box. See Figure 3.5. Figure: 3.6 Weak Entity

Employee Manager 3.5.3 Entity Instance


Instances are the values for the entity
Figure 3.5 Entity
if we consider animals as the entity their
Types of Entity: instances will be dog, cat, cow… Etc. So
1. Strong Entity an Entity Instance denotes the category
values for the given entity.
2. Weak Entity
3. Entity Instance Table: 3.3 Entity Instances
Strong Entity Entities Instances
A Strong entity is the one which doesn’t
Human Male , Female
depend on any other entity on the schema
or database and a strong entity will have Animals Dog, cats, lion
a primary key with it (i.e. a unique id
Jobs Engineer, Doctor, Lawyer
which other entities will not have in
their attributes).It is represented by one Actors Ajith, Vijay, Vikram
rectangle.In the above example it is a
Electronics Laptop, Mobile
strong entity because it has a primary
62 Chapter 3 Introduction to Database Management System
www.tntextbooks.org

3.5.4 Attributes 3.5.4.4 Single Valued Attributes:


An attribute is the information about that A single valued attribute contains only
entity and it will describe, quantify, qualify, one value for the attribute and they don’t
classify, and specify an entity. An attribute have multiple numbers of values. For
will always have a single value, that value Example:Age- It is a single value for a
can be a number or character or string. person as we cannot give n number of ages
Types of attributes:
for a single person,therefore it is a single
valued attribute. See Table 3.4
1. Key Attribute
2. Simple Attributes Table: 3.4 Single Valued Attributes
3. Composite Attributes Attribute Values
4. Single Valued Attribute
Age 3
5. Multi Valued Attribute
Roll no 85
3.5.4.1 Key Attribute
Generally a key attribute describes a In the above table are the some examples
unique characteristic of an entity. for single valued attributes. See Figure 3.8

3.5.4.2 Simple Attribute


Degree
First name Last name

Name

Person
Employee

Figure 3.8 Single Valued Attributes


Figure 3.7 Simple Attribute
3.5.4.5 Multi Valued Attributes:
The simple attributes cannot be separated
A multi valued attribute has more than
it will be having a single value for their
one value for that particular attribute.For
entity. For Example: Let us consider
Example:Degree - A person can hold n
the name as the attribute for the entity
number of degrees so it is a multi-valued
employee and here the value for that
attribute.
attribute is a single value. See Figure 3.7
In Table 3.5 are some examples for
3.5.4.3 Composite Attributes
Multi valued attributes.
The composite attributes can be sub-
divided into simple attributes without Table: 3.5 Attributes and Values
change in the meaning of that attribute. Attribute Values
For Example: In the above diagram the
employee is the entity with the composite Degree B.Tech, MBA
attribute Name which are sub-divided into Bank_Account SBI, HDFC
two simple attributes first and last name.
Chapter 3 Introduction to Database Management System 63
www.tntextbooks.org

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

Here the customer can place multiple 3.6 ER-Diagram


orders and the order is related to only one
ER Diagram presents data visually on
customer. See Figure 3.11
how they are related to each other. This
n
Student register Course model follows separate notations for
representing data into entities, attributes
Figure: 3.11 Cardinality Relation n to n and relationship between the entities.
The example of many-to-many
3.6.1 ER-Modeling Diagram
relationship is Students registering the Notations
Courses. A student can register more
Entities, Attributes and Relationship
than one courses and A course can be
forms the components of ER Diagram
registered by many students. Hence it is
and the defined symbols and shapes are
many-to-many.
summarized below in Table 3.6.

Table 3.6 ER diagram Notations


ER Component Description (how it is represented) Notation
Entity - Strong Simple rectangular box
Student

Entity – Weak Double rectangular boxes

Relationships Rhombus symbol - Strong

between Entities Rhombus within rhombus


– Weak

Attributes Ellipse Symbol connected to the Age


entity
Student

Key Attribute for Underline the attribute name


Key Attribute
Entity inside Ellipse
Derived Attribute for Dotted ellipse inside main ellipse
Entity

Multivalued Double Ellipse


Attribute for Entity

Chapter 3 Introduction to Database Management System 65


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

Fname Lname Takes

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

Figure: 3.12 ER-Diagram

3.6.2 Example is named after his daughter name My.


Given below is an example of ER Diagram Clear definition of database and SQL
for the scenario of School Management is mandatory to understand MySQL.
System. We have many entities like In simple, a database is defined as the
Parent, student, Admin, Teacher, class structured collection of data. Ex. Photo
and subjects. The attributes of few entity gallery is a database which has collection
is given below: of photos (data). SQL - structured
query language is not a database. It is a
Parent – Name, Id, Fname, Lname.
standardized language used to access the
Student – Id, Name, Fname, Lname.
database and the data’s are processed to
Teacher – Name, Id, Phone#, Address.
turn into efficient information. The SQL
The relationships that exist between the standard always refers to the current
entities are as follows: version and the current version is 2003.
●● Parent HAVE Student MySQL is open source software that
●● Admin ENROLLS Student allows managing relational databases. It
also provides the flexibility of changing
●● Admin HIRES Teacher
the source code as per the needs. It runs
●● Admin ADDS Subject
on multiple platforms like Windows,
●● Teacher TEACHES Subject Linux and is scalable, reliable and fast.
●● Teacher IS ASSIGNED TO Class
Key Attributes are listed with underline. 3.7.2 Overview of Web Database
Many databases are in existence to meet
3.7 Introduction to MYSQL out the needs of the application. These
3.7.1 About MYSQL databases are broadly divided into Heavy
and Light databases. Heavy databases
MySQL is a database management
support all the desktop applications
system founded by Monty Widenius and
whereas the web applications are
66 Chapter 3 Introduction to Database Management System
www.tntextbooks.org

MySQL 44.3%

SQL server 30.8%

SQLite 21.2%

PostgreSQL 21.2%

MongoDB 16.8%

Oracle 13.2%

Redis 11.2%

Cassandra 2.5%

Figure: 3.13 Most Popular databases - Statistics

supported by Light databases. Below are 3.8 MySQL - Administration


the lists of commonly used databases.
3.8.1 MySQL – Administration
●● DB2 Responsibilities
●● MySQL In general there exists a role known as
●● Oracle Database Administrators (DBA’s) who
●● PostgreSQL takes care of configuration, installation,
performance, security and data backup.
●● SQLite
DBA’s posses the skills on database
●● SQL Server design, database queries, RDMS, SQL
●● Sybase and networking. The primary task is the
Due to the rapid growth in the web domain, creation of new user and providing them
most of the desktop applications are being with access rights.
converted into web applications. These
Creating New User
transformations to the web results in the
Account to MySQL
availability of many web applications in
In the MySQL database, there exists a
the network. Heavy databases did not
table named user. The newly created
meet out the network issues efficiently.
account must have an entry in this user
Light databases were able to handle all
table. Consider the admin creates an
the issues raised by the network. So all
account with username and password.
the light databases that supports the
The user account is activated with various
web applications are also known as Web
access rights like INSERT, SELECT and
Databases. See Figure 3.13
UPDATE. Consider the user table has the
MySQL is the most commonly used following fields host, name, password,
database in the world due to its ease of use. select_priv, insert_priv and update_priv.
Chapter 3 Introduction to Database Management System 67
www.tntextbooks.org

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.

VALUES (‘localhost’, ‘guest’, Insert_priv User can insert rows into


PASSWORD(‘guest123’), ‘Y’, ‘Y’, ‘Y’); 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

2. SHOW Databases – Lists all the Table 3.11 Column List


databases available in the database
Field Type Null Key Default Extra
server. See Table 3.9
Team_id int(5) yes null
Syntax:
Team_name varchar yes null
mysql > show databases; (10)
Team_size int(5) yes null

Table 3.9 Database List Team_rank int(5) yes null

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

Figure: 3.15 XAMPP Server Welcome Wizard

Select the Required component along with MYSQL component and click next button

Figure: 3.16 XAMPP Server Component Wizard

70 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

Choose The Installation Folder and click Next

Figure: 3.17 XAMPP Server install path

Click Next Button in Setup ready page

Figure: 3.18 XAMPP Server setup completion

Chapter 3 Introduction to Database Management System 71


www.tntextbooks.org

Installation get started

Figure: 3.19 XAMPP Server setup Progress window

After installing Click finish button and open the XAMMP Control panel

Figure: 3.20 XAMPP Server setup completion

In the Control Panel start the Apache and MySQL Services one by one

72 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

Figure: 3.21 XAMPP Server Control panel

The two services get started one by one

Figure: 3.22 XAMPP Server Services start option

Chapter 3 Introduction to Database Management System 73


www.tntextbooks.org

Open the URL http://localhost/phpmyadmin URL in a browser to access MySQL database.

Figure: 3.23 PHP Myadmin Mysql Database server User interface

3.9 MYSQL Administration memory usage. It also helps in making the



open source software complex queries easier.
tools MySQL Workbench (Desktop
Types of software tools Application)
Many open source tools are available in the It is a database tool used by developers and
market to design the database in a better DBA’s mainly for visualization. This tool
and efficient manner. PhpMyAdmin is helps in data modeling, development of SQL,
most popular for Web Administration. server configuration and backup for MySQL
The popular Desktop Application tools in a better way. Its basic release version is 5.0
are MySQL Workbench and HeidiSQL. and is now in 8.0 supporting all Operating
Systems. The SQL editor of this tool is very
PHPMYADMIN (Web Admin) flexible and comfortable in dealing multiple
This administrative tool of MySQL is a results set.
web application written in PHP. They are HeidiSQL (Desktop Application)
used predominantly in web hosting. The
This open source tools helps in the
main feature is providing web interface,
administration of better database systems.
importing data from CSV and exporting
It supports GUI (Graphical User Interface)
data to various formats. It generates live
features for monitoring server host, server
charts for monitoring MySQL server
connection, Databases, Tables, Views,
activities like connections, processes and
Triggers and Events.

74 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

3.10 Designing Databases Database changed.


The process of creating, implementing The created database is listed using SHOW
and maintaining the enterprise data in a command. See Table 3.12
system isknown as Designing of databases. mysql> show databases;
Better understanding of the application is
necessary before Table 3.12 Database List
Designing the database. The Database
performance and success of an application employee
depends on good database design. MySQL personaldetails
provides performance dashboard, reports
sports
and statistics regarding the design of
database.
●● Create Table
Create Conceptual Design In an application, each page reveals
It is the primary phase in database design, some functionality. Each such functions
where detailed discussion about the are designed to a table. For example, in
creation of databases, tables, columns an online shopping site like Amazon,
and data types is discussed based on the multiple pages are maintained like
requirement of the application. As an end customer profile, products, orders in
result the model is framed to attain the cart and payment page. All these can be
expectation of the application’s end user. created as tables like Customer, Products,
Order and Payment respectively.
●● Create Database ●● Create Columns
The three major parts that forms a database Each table will have many columns related
are Tables, Queries and Views. to the functionality of the table. This
Tables - similar to an excel sheet, column determines what values are stored
containing multiple rows and columns. in the table. For example, the Customer
Where each row is a record and each table contains the columns like firstname,
column is an attribute. lastname, phone, email, age, address
and pincode. These columns hold the
Queries – It is a question with multiple
Customers information in the table. Each
conditions posted to the database. The
column is assigned with appropriate value
records in the database that satisfies the
type. The efficiency and performance of
passed conditions are retrieved.
the table purely depends on the data types
Views – A set of stored queries. assigned to the columns.
Example: create a database to store the
Insert Rows

●●
personaldetails.
Once the database is created, tables and
mysql> create database personaldetails; the columns with the appropriate value
Query Ok, 1 row affected type are defined. Then records are inserted
mysql> USE personaldetails; to the table.
Chapter 3 Introduction to Database Management System 75
www.tntextbooks.org

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

Transaction Control Language (TCL) 3.12 Basic SQL


These SQL commands manage the Create/Drop /Selecting Database
transactions in SQL databases. It also
Create Database – used to create new
helps to save the change into database
SQL Database. The Syntax and example to
permanently. COMMIT, ROLLBACK,
create studentDB is given below.
SET TRANSACTION and SAVEPOINT
commands belongs to this category. See Syntax: CREATE database
Table 3.16 databasename;
Table: 3.16 SQL TCL COMMANDS List Example: mysql>create database
 
studentDB;
Commands Description
COMMIT Permanent save into The database created now can be viewed
database. using the following Syntax,
ROLLBACK Restore database to
mysql>Show databases;
original form since the
last COMMIT. As a result, the newly created studentDB
SET SET TRANSACTION will be listed.
TRANSACTION command set the
transaction properties Drop Database – used to remove any of
such as read-write or read the existing SQL Database. The Syntax
only access. and example to delete student DB is given
SAVE POINT used to temporarily save below.
a transaction so that we Syntax: DROP database
can rollback to that point databasename;
whenever required.
Example: mysql>DROP database
studentDB;
Data Control Language (DCL)
The deleted database will not be
The SQL commands that implement
viewed,when we list all databases using
security on database objects like table, view,
the Syntax, Show databases;
stored procedure etc. GRANT and REVOKE
commands belongs to this category. See
Select Database – Many
Table 3.17
databasesareavailable in the repository,
Table: 3.17 SQL DCL COMMANDS List from which the suitable database is
 
Commands Description selected using the below command.
Grant used to give permission to Syntax: USE databasename;
specific users on specific Example: mysql>USE studentDB;
database objects like table,
view etc Once the database is selected, multiple
Revoke used to take out permission operations are performed as per the needs
from specific users on specific of the application.
database objects like table,
view etc.
Chapter 3 Introduction to Database Management System 77
www.tntextbooks.org

●● Insert Record SELECT Syntax given below in Table 3.18


Database will have multiple tables. and 3.19
Tables are created using the create Syntax1: SELECT * from tablename;
command with various fields added
Example: mysql>SELECT * from Biodata;
to it as per their need. Any table is
complete only with the record available Table:3.18 SQL Select Record List
in it. So new row are added to the table Firstname Lastname Age
using the Insert command. The Syntax
Krishna S 10
and example for inserting new record
Sugal S 14
into the table is given below:
Arun J 15
Syntax 1:
Mani K 18
INSERT INTO tablename (column1,
column2, column3) Syntax2: SELECT column1, column2
from tablename;
VALUES (value1, value2, value3);
Example: mysql>SELECT firstname, age
Syntax 2: from Biodata;
INSERT INTO tablename VALUES
(value1, value2, value3); Table:3.19 SQL Select Record List
Firstname Age
Consider we have a table named Biodata,
which has three columns namely Krishna 10
firstname, lastname and age. Now the new Sugal 14
record is added to the table using either Arun 15
Syntax1 or Syntax2 as shown below.
Mani 18
mysql>INSERT INTO Biodata (firstname,
lastname, age) Deleting Record
VALUES (Krishna, Sam, 10); The existing record in a table is removed
(or) from the table using DELETE command.
Entire record or specified columns in
mysql>INSERT INTO Biodata VALUES the table can be deleted. If we want to
(Krishna, Sam, 10); perform delete operation on specific
columns, then that condition is given in
●● Select Record
the WHERE condition. If the condition is
From the multiple records available in the
not specified, then the entire data will be
table, the enquired data are retrieved from
deleted. See Table 3.20 and 3.21
the table-using the SELECT command
with some conditions specified in it. We Syntax1: DELETE from tablename
can retrieve all the fields of a record or WHERE columnname=”value”;
specify the necessary fields in a table. The Example: mysql>DELETE from Biodata
records of any table are retrieved using the WHERE firstname=”Mani”;

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

Table:3.22 MySQL Operators


Syntax2: DELETE from tablename;
Operator Type Operator
Example: mysql>DELETE from Biodata ;
Arithmetic Operator +, -, *, /, %
Table:3.21 SQL Delete Record List Comparison Operator =, !=, <, >, <>, >=,
firstname lastname age <=,
Logical Operator AND, ANY,
Modifying Record BETWEEN,
SQL provides us with modifying and EXISTS, IN,
updating the existing records in a table LIKE, NOT, OR,
using UPDATE command. The age of UNIQUE
Krishna in Biodata table is changed using
the below Syntax. Sorting Records
The Query results are listed in Ascending
or Descending order using the command
Syntax1: UPDATE tablename
ORDER BY. In some databases the results
SET column1=”new value” are sorted by default in Ascending order
Where column2=”value2”; and is given in Syntax1. The results are
displayed in descending order as per
Example: mysql>UPDATE Biodata SET
Syntax2. See Table 3.23 and 3.24
age=13 WHERE firstname=”Krishna”;
Syntax1: select * from tablename ORDER
BY columnname;
WHERE Clause
In SQL command WHERE clause is used Example: select * from Biodata ORDER
to specify the selection criteria Based on BY firstname;
that data’s are retrieved or modified as
per the query. In the WHERE conditions, Table:3.23 Select Record List
operations like =, !=, >, >=, < , <= are used
firstname lastname age
to frame the query statement. WHERE
clause is used in SELECT and UPDATE Arun J 15
query statement for the condition. The Krishna S 13
number of records updated in a table Sugal S 14
depends on the WHERE condition.

Chapter 3 Introduction to Database Management System 79


www.tntextbooks.org

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.24 Select Record List 201901 177


firstname lastname age
201902 158
Sugal S 14
Krishna S 13 201903 173
Arun J 15 201904 158

Grouping Records, Having Clause 201905 179


In SQL we can have identical data in a group.
Consider a table named Exams with fields Joining Tables
Rollno, Subject and Marks. In the below When we have to select data from more
table multiple rows of records are available than 2 tables SQL JOIN clause is used.
for different subjects. Using the GROUP Consider two tables Exams and Profile.
BY command, the rollno’s are grouped and The Exams table has the fields Rollno,
marks are added up against the Rollno with Subject and Marks. The data of Profile
SUM( marks). See Table 3.25 and 3.26. table is shown below in Table 3.27 & 3.28.

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

201902 Tamil 78 201904 Venilla Singing

201904 Tamil 83 201905 Pragathi Painting

201903 English 81 SELECT Profile.Name, Profile.Hobby,


SUM(Exams.Marks)As Total
201905 Tamil 89
FROM Profile, Exams
201902 English 80
WHERE Profile.Rollno = Exams.Rollno
201905 English 90
GROUP BY Profile.Name, Profile.Hobby;

80 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

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

Consider the Employee table


with the fields EmpID, Name, Age and
Salary. The sample data is given below in Similarly the subqueries are used
Table 3.29. with INSERT, UPDATE and DELETE.

Chapter 3 Introduction to Database Management System 81


www.tntextbooks.org

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

82 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

5. Which type of below DBMS is Part - II


MySQL? Short Answers
a) Object Oriented 1. Define Data Model and list the types
b) Hierarchical of data model used.
c) Relational 2. List few disadvantages of file
d) Network processing system.
6. MySQL is freely available and is 3. Define Single and multi valued
open source. attributes.
a) True 4. List any two DDL and DML
b) False commands with its Syntax.
7. ---------- represents a “tuple” in a 5. What are the ACID properties?
relational database?
6. Which command is used to make
a) Table
permanent changes done by a
b) Row transaction?
c) Column
7. What is view in SQL?
d) Object
8. Communication is established with 8. Write the difference between SQL
MySQL using and MySQL.
a) SQL 9. What is Relationship and List its
b) Network calls types.
c) Java 10. State few advantages of Relational
d) API’s databases.
9. Which is the MySQL instance
Part - III
responsible for data processing?
Explain in Brief Answer
a) MySQL Client
1. Explain on Evolution of DBMS.
b) MySQL Server
c) SQL 2. What is relationship in databases?
List its types.
d) Server Daemon Program
10. The structure representing the 3. Discuss on Cardinality in DBMS.
organizational view of entire 4. List any 5 privileges available in
database is known as -------- in MySQL for the User.
MySQL database.
5. Write few commands used by DBA
a) Schema b) View to control the entire database.
c) Instance d) Table

Chapter 3 Introduction to Database Management System 83


www.tntextbooks.org

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.

84 Chapter 3 Introduction to Database Management System


www.tntextbooks.org

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

4.1 Introduction to Hypertext of Internet and World Wide Web (WWW).



Pre-Processor (PHP) These concepts required a new set of
programming languages over the network
Internet and Web based
communication. These programming
online applications
languages are recently called as Web
are performing
scripting languages.
very important role
in business and The Web scripting languages has
entertainment industry. many policies which is easy to handle
Two decades back, a famous quote and solve the critical business problems
around the world. In Later 1990’s many
“If your business establishment is not on
Web scripting languages was introduced
the Internet (online based), then your
business will be out of business context.”
to support the Internet online business.
Founder of Microsoft- Bill Gates PHP is one of the most widely used
and recognizable technologies in use
on the internet. Originally PHP stood
The Web based Internet application for "Personal Home Page", though
ensures the success of critical business in real more recently it has been changed to stand for
world competitions. The legacy programing "PHP: Hypertext Preprocessor". However, no
languages didn’t meet out the expectations matter what it is called, PHP is a fundamental
part of any dynamic web page.
of latest Internet concepts and executions.
In earlier 1990’s British scientist PHP (Hypertext Pre-processor)
Tim Berners-Lee introduced the concept is a one of the important server side Web
85
www.tntextbooks.org

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

Information server) supports the PHP


interpreter module. Refer Figure 4.1
PHP is an open source community
Client
development initiation. It has many Client

versions to ensure quality and ease of Figure 4.2 Client Server Architecture Model

86 Chapter 4 Introduction to PHP


www.tntextbooks.org

Client Server Architecture Model Multi/Three Tier Architecture:


Client server architecture shown above in This architecture is used for the server,
Figure 4.2 is classified into three types, as accessed by client through more than one
follows layer interaction. The programmer could
●● Single Tier Architecture decide the count of business logic layers
●● Two Tier Architecture according to the software requirement
●● N/Multi/Three tire architecture that is the reason this model is also known
as Multi Three Tire Architecture as shown
Single Tier Architecture in Figure 4.5.
This architecture is used for the server,
3-Tier Architecture
accessed by client. The client application
runs inside the server machine itself. This Client Tier

acts as a single layer interaction as in


Figure 4.3.
Business Logic
1-Tier Architecture Tier
Application Server
Client computers

Database Tier Database


Server

Figure 4.5 Multi/Three- Tier Architecture

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

Chapter 4 Introduction to PHP 87


www.tntextbooks.org

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%

Tomcat 0.4% Step 4:


Apache Traffic Server 0.4% Administrator user can start, stop and
IdeaWebServer 0.3% restart the Web server service at any
Tengine 0.1% time via windows Control panel. Once
Cowboy 0.1% the services stops, the client machine
Lighttpd 0.1%
will not receive the response message
from server machine.
Figure 4.7 Webserver global usage
88 Chapter 4 Introduction to PHP
www.tntextbooks.org

Step 5: From client side, the end user opens


Webserver’s configuration setting file a browser, types the URL of the Website
“httpd.conf ” is located in the conf or Webpage and initiates the request to
directory under the apache installation remote server machine over the network.
directory. Edit this file and enable the After receiving the request from
PHP module to run PHP scripting client machine the Web server tries to
language. compile and interpret the PHP code which
is available in remote machine. Next a
4.6 Web Development response will be generated and sent back

Concept to the client machine over the network
Web development concept describes in detail from Webserver.
about Website development and hosting Finally the browser which is
through network (Internet/Intranet). The installed in the client machine receives
process of development also includes Web the response and displays the output to
content generation, Web page designing, user, as shown in Figure 4.8
Website security and so on.
4.6.2 PHP Syntax
4.6.1 How PHP Script Work Three types of PHP Syntax are available.
Website or Web page is developed by the They are as follows
programmer using PHP script. Finally the 1. Default Syntax
entire Website codes are moved to Web 2. Short open Tags
server path in a remote server machine. 3. HTML Script embed Tags

Server

Client browser
1
request
2

Php
Apache 3
Response Apache/IIS
4

MySQL/Microsoft SQL
Server/Oracle

= File System = Database

Figure 4.8 Client to server Request

Chapter 4 Introduction to PHP 89


www.tntextbooks.org

Default Syntax: HTML Script embed Tags:


The default Syntax begins with “<?php” HTML Script embed Tags looks just like
and closes with “?>”. Also refer Figure 4.9 HTML scripts tags. The syntax is shown
in Figure 4.11.
Opening PHP tag String Closing PHP tag

<? php echo “Hello world...” ; ?>

Figure 4.11 HTML Syntax


Ouput
End of statement
one or more string
The above syntax is created and saved
Figure 4.9 PHP Syntax in a file with extension of .php. This .php
file is ready to execute from Webserver and
Short open Tags
generate response to client machine.
The Short open Tags begins with “<?” and
closes with “?>”. But admin user has to 4.6.3 Embed PHP in HTML
enable Short style tags settings in php.ini file
PHP script can be written in side of HTML
on the server. Refer the syntax in Figure 4.10
code and save the file with extension of
Opening PHP tag String Closing PHP tag .php. The embedded PHP file get executed
in the Webserver, the browser receives
<?
only the HTML and other client side files.
echo “Hello world...” ; ?>
None of the raw PHP code is visible in
Ouput browser which means that PHP interpreter
End of statement
one or more string
produces raw HTML files to browsers in
Figure 4.10 PHP Short Syntax the client machine. Refer Figure 4.12 for
Web response

Figure 4.12 HTML Web Response

90 Chapter 4 Introduction to PHP


www.tntextbooks.org

4.6.4 Variable in PHP String:


PHP has variables like other programing String is a collection of characters within
languages such as C, C++ and Python the double or single quotes like
etc. Variables are the storage location, “Computer Application” or
which can store the values for the later ‘Computer Application’. Space is also
manipulations in the program. considered as a character.
The variable in PHP begins with a
dollar ($) symbol and the assignment activity Example:
implemented using “=” operator, finally <?php
the statement ends with semi colon “;” The $x = “Computer Application!”;
semicolon indicates the end of statement. $y = ‘Computer Application’;
The main advantage of the PHP echo $x;
variable declaration is, it does not requires echo “<br>”;
to specify the data type keyword separately echo $y;
such as int, char, float, double or string etc. ?>
Basic Rules for Variable Declaration
Integer:
●● Variable name must always begin with
a $ symbol. Integer is a data type which contains non
decimal numbers.
●● Variable name can never start with a
number. Example:
●● Variable names are case-sensitive. <?php
$x = 59135;
Example:
var_dump($x);
$a=5; $b=10;
?>
$a_1=”Computer Application”
$c=$a+$b;
The var_dump() system define
echo $c; function, returns structured information
(type and value) about variables in PHP.
4.6.5 PHP Data Type
Float:
PHP scripting language supports 13
primitive data types. Data Types plays Float is a data type which contains decimal
important role in all programing languages numbers.
to classify the data according to the logics.
PHP supports the following data types. Example:

1. String 5. Array <?php


2. Integer 6. Object $x = 19.15;
3. Float 7. NULL var_dump($x);
?>
4. Boolean 8. Resource

Chapter 4 Introduction to PHP 91


www.tntextbooks.org

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

92 Chapter 4 Introduction to PHP


www.tntextbooks.org

4.6.6. Operators in PHP


Operator is a symbol which is used to perform mathematical and logical operations in the
programing languages. Different types of operator in PHP are:
1. Arithmetic operators,
2. Assignment operators,
3. Comparison operators,
4. Increment/Decrement operators,
5. Logical operators, and
6. String operators.

Arithmetic operators
The arithmetic operators in PHP perform general arithmetical operations, such as
addition, subtraction, multiplication and division etc. Refer Table 4.1.

Table 4.1 PHP Arithmetic operators


Symbol Operator Name Purpose
+ Addition This operator performs the process of adding numbers

- Subtraction This operator performs the process of subtracting numbers

* Multiplication This operator performs the process of multiplying numbers

/ Division This operator performs the process of dividing numbers

% Modulus This operator performs the process of finding remainder in


division operation of two numbers

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.

Table 4.2 PHP Assignment operators


Assignment Similar to Description
x=y x=y This operator sets the left side operant value of
expression to right side variable
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus

Chapter 4 Introduction to PHP 93


www.tntextbooks.org

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.

Table 4.3 PHP Comparison operators


Symbol Operator Name Symbol Operator Name

== Equal > Greater than

=== Identical < Less than

!= Not equal >= Greater than or equal to

<> Not equal <= Less than or equal to

!== Not identical

Increment and Decrement Operators:


Increment and decrement operators are used to perform the task of increasing or
decreasing variable’s value. This operator is mostly used during iterations in the program
logics. Refer Table 4.4.

Table 4.4 PHP Increment and Decrement operators


Operator Name Description

++$x Pre-increment Increments $x value by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

Logical Operators:
Logical Operators are used to combine conditional statements. Refer Table 4.5.

Table 4.5 PHP Logical operators


Symbol Operator Name Example Result

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

xor Xor $x xor $y True if either $x or $y is true, but not both

94 Chapter 4 Introduction to PHP


www.tntextbooks.org

String Operators:
Two operators are used to perform string related operations such as Concatenation and
Concatenation assignment (Appends). Refer Table 4.6.

Table 4.6 PHP String operators

Operator Name Example Result

. Concatenation $text1 . $ text2 Concatenation of $txt1 and $txt2

.= Concatenation $text1 .= $ text2 Appends $txt2 to $txt1


assignment

points to remember

●● PHP is an Open Source


●● PHP is a Case Sensitive
●● PHP is a Simplicity Program language
●● PHP is a Efficiency Program language
●● PHP is a Platform Independent Program language
●● PHP is a Security Program language
●● PHP is a Flexibility Program language
●● PHP is a Real-Time Access Monitoring Program language

PHP PHP abbreviated as “HYPER TEXT PREPROCESSOR”. It is a server-side


scripting language

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

Chapter 4 Introduction to PHP 95


www.tntextbooks.org

Webserver A Web server is a Software that uses HTTP (Hypertext Transfer Protocol) to
serve the files that form Web pages to users

Web Browser A Web browser (commonly referred to as a browser) is a software application


for accessing information on the World Wide Web. Each individual Web
page, image, and video is identified by a distinct URL, enabling browsers to
retrieve and display them on the user’s device.

SERVER A server is a computer or a device that provides functionality for other


programs or devices, called “clients”. This architecture is called the client
server model, and a single overall computation is distributed across multiple
processes or devices.

EVALUATION
Part - I a) <php>
Choose the correct answer b) < ? php ?>
1. What does PHP stand for? c) < ? ? >
a) Personal Home Page d) < ?php ? >

b) Hypertext Preprocessor 4. Which of the following must be


c) Pretext Hypertext Processor installed on your computer so as to
d) Pre-processor Home Page run PHP script?
a) Adobe
2. What does PHP files have a default b) windows
file extension? c) Apache
a) .html d) IIS
b) .xml
5. We can use ___ to comment a single
c) .php line?
d) .ph i) /? ii) // iii) # iv) /* */
a) Only (ii)
3. A PHP script should start with ___ b) (i), (iii) and (iv)
and end with ___: c) (ii), (iii) and (iv)
d) Both (ii) and (iv)

96 Chapter 4 Introduction to PHP


www.tntextbooks.org

6. Which of the following PHP 10. Which of the below symbols is a


statement/statements will store 41 newline character?
in variable num?
a) \r
a) Both (i) and (ii)
b) \n
b) All of the mentioned.
c) Only (iii) c)/n
d) Only (i) d)/r
7. What will be the output of the
following PHP code? Part - II
< ?php Short Answers
$num = 1; 1. What are the common usages of
PHP?
$num1 = 2;
print $num . “+”. $num1 ; 2. What is Webserver?
?> 3. What are the types scripting
a) 3 language?
4. Difference between Client and
b) 1+2
Server?
c) 1.+.2
5. Give few examples of Web Browser?
d) Error 6. What is URL?
7. Is PHP a case sensitive language?
8. Which of the following PHP
statements will output Hello World 8. How to declare variables in PHP?
on the screen? 9 Define Client Server Architecture.
a) echo (“Hello World”); 10. Define Webserver.
b) print (“Hello World”);
Part - III
c) printf (“Hello World”);
Explain in Brief Answer
d) sprintf (“Hello World”);
1. Write the features of server side
scripting language.
9. Which statement will output $x on 2. Write is the purpose of Web servers?
the screen?
3. Differentiate Server side and Client
a) echo “\$x”; Side Scripting language.
b) echo “$$x”; 4. In how many ways you can embed
PHP code in an HTML page?
c) echo “/$x”;
5. Write short notes on PHP operator.
d) echo “$x;

Chapter 4 Introduction to PHP 97


www.tntextbooks.org

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

98 Chapter 4 Introduction to PHP


www.tntextbooks.org

05
CHAPTER

PHP Function and Array

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

PHP Function and Array The Function can be divided in to


three types as follows
In PHP server side scripting language
●● User defined Function,
Functions and array concepts are very
●● Pre-defined or System or built-in
important to solve the many complex
Function, and
problems in real world.
●● Parameterized Function.
PHP has over 700 functions built in
User Defined Function
that perform different tasks. Built in
functions are functions that exist in User Defined Function (UDF) in PHP gives
PHP installation package. a privilege to user to write own specific
operation inside of existing program module.
Functions in PHP Two important steps the Programmer has to
In most of the programming language, create for users define Functions are:
a block of segment in a program that Function Declaration
performs a specific operation tasks A user-defined Function declaration begins
(Insert, Execute, Delete, Calculate, etc.). with the keyword “function”. User can write
This segment is also known as Function. any custom logic inside the function block.
A Function is a type of sub routine or
SYNTAX:
procedure in a program. A Function will
be executed by a call to the Function and function functionName()
the Function returns any data type values {
or NULL value to called Function in the Custom Logic code to be executed;
part of respective program. }
99
www.tntextbooks.org

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

5.1 Parameterized Function


Required information can be shared between function declaration and function calling
part inside the program.
The parameter is also called as arguments, it is like variables.
The arguments are mentioned after the function name and inside of the parenthesis.
There is no limit for sending arguments, just separate them with a comma notation.
Example 1:
The following example has a function with one Argument ($sfname):
<?php
function School_Name($sname) {
echo $sname.”in Tamilnadu.<br>”;
}
School_Name (“Government Higher Secondary School Madurai”);
School_Name (“Government Higher Secondary School Trichy”);
School_Name (“Government Higher Secondary School Chennai”);
School_Name (“Government Higher Secondary School Kanchipuram”);
School_Name (“Government Higher Secondary School Tirunelveli”);
?>
Example 2:
The following example has a function with two arguments ($sname and $Strength):
<?php
function School_Name($sname,$Strength) {
echo $sname.”in Tamilnadu and Student Strength is”.$Strength;
}

100 Chapter 5 PHP Function and Array


www.tntextbooks.org

School_Name (“Government Higher Secondary School Madurai”,200);


School_Name (“Government Higher Secondary School Trichy”,300);
School_Name (“Government Higher Secondary School Chennai”,250);
School_Name (“Government Higher Secondary School Kanchipuram”,100);
School_Name (“Government Higher Secondary School Tirunelveli”,200);
?>
Example 3:
For a function to return a value, use the return statement
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

echo “5 + 10 = “ . sum(5, 10) . “<br>”;


echo “7 + 13 = “ . sum(7, 13) . “<br>”;
echo “2 + 4 = “ . sum(2, 4);
?>

5.2 Array in PHP


Array is a concept that stores more than one value of same data type (homogeneous) in
single array variable. They are 3 types of array concepts in PHP.
●● Indexed Arrays,
●● Associative Array and One of the most useful aspects
●● Multi-Dimensional Array. of using arrays in PHP is when
combined with the foreach statement.
5.2.1 SYNTAX: This allows you to quickly loop though
Array Syntax: an array with very little code.
Array defines with the keyword array()

Array defines with the keyword array()

$Array_Variable=array(“value1”,”value2”,”value2”);

Value Value Value


at 0th at 1st at 2nd
position position position

Figure 5.1 Indexed Arrays

Chapter 5 PHP Function and Array 101


www.tntextbooks.org

Associative Arrays Syntax


array(key=>value,key=>value,key=>value,etc.);
key = Specifies the key (numeric or string)
value = Specifies the value

5.2.2 Indexed Arrays


Arrays with numeric index for the available values in array variable which contains key
value pair as user / developer can take the values using keys. Refer Figure 5.1.
Example:
<?php
$teacher_name=array(“Iniyan”, “Kavin”, “Nilani”);
echo “The students name are “ . $teacher_name[0] . “, “ . $$teacher_name[1] . “ and “ .
$teacher_name[2] . “.”;
?>

5.2.3 Associative Arrays


Associative arrays are a key-value pair data structure. Instead of having storing data in a
linear array, with associative arrays you can store your data in a collection and assign it a
unique key which you may use for referencing your data.
Example:
<?php
$Marks=array(“Student1”=>“35”,“Student2”=>“17”,“Student3”=>“43”);
echo “Student1 mark is” . $Marks[‘Student1’] . “ is eligible for qualification”;
echo “Student2 mark is” . $Marks[‘Student2’] . “ is not eligible for qualification”;
?>

5.2.4 Multidimensional Arrays


A multidimensional array is an array containing one or more arrays.PHP understands
multidimensional arrays that are two, three, four, five, or more levels deep. However,
arrays more than three levels deep are hard to manage for most people.
Example:
<?php
// A two-dimensional array
$student=array
(
array(“Iniyan”,100,96),
array(“Kavin”,60,59),
array(“Nilani”,1313,139)

102 Chapter 5 PHP Function and Array


www.tntextbooks.org

);

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

●● PHP Functions areReducing duplication of code


●● PHP Functions areDecomposing complex problems into simpler pieces
●● PHP Functions areImproving clarity of the code
●● PHP Functions areReuse of code
●● PHP Functions areInformation hiding
●● PHP arrays are using Foreach looping concepts

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

Chapter 5 PHP Function and Array 103


www.tntextbooks.org

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

104 Chapter 5 PHP Function and Array


www.tntextbooks.org

a) is_array ( ) function 4. List out System defied Functions.


b) sizeof ( ) function 5. Write Syntax of the Function in PHP.
c) array_count ( ) function 6. Define Array in PHP.
d) count ( ) function 7. Usage of Array in PHP.
7. Indices of arrays can be either strings 8. List out the types of array in PHP.
or numbers and they are denoted as 9. Define associative array.
a) $my_array {4} 10. Write array Syntax in PHP.
b) $my_array [4]
c) $my_array| 4 | Part - III
Explain in Brief Answer
d) None of them
8. PHP arrays are also called as 1. Write the features System define
Functions.
a) Vector arrays
2. Write the purpose of parameterized
b) Perl arrays
Function.
c) Hashes
3. Differentiate user define and system
d) All of them define Functions.
9. As compared to associative arrays 4. Write Short notes on Array.
vector arrays are much
5. Differentiate Associate array and
a) Faster b) Slower Multidimensional array.
c) Stable d) None of them
10. What functions count elements in Part - IV
an array? Explain in detail
a) count b) Sizeof 1. Explain Function concepts in PHP.
c) Array_Count d) Count_array 2. Discuss in detail about User define
Functions.
Part - II 3. Explain the Multidimensional Array.
Short Answers
4. Explain Array concepts and their
1. Define Function in PHP. types.
2. Define User define Function. 5. Explain Indexed array and Associate
3. What is parameterized Function. array in PHP.

student activity

●● Create store the student details arrays and display the values.
●● List out real world Built-in string function usages in PHP

Chapter 5 PHP Function and Array 105


www.tntextbooks.org

06
CHAPTER

PHP Conditional Statements

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

PHP Conditional Statements:


Conditional statements are useful for writing decision making logics. It is most important
feature of many programming languages, including PHP. They are implemented by the
following types:
●● if Statement
●● if...else Statement
●● if...elseif....else Statement
●● switch Statement

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”;
}?>

If else statement in PHP:


If statement executes a statement or a group of statements if a specific condition is satisfied
by the user expectation. When the condition gets false (fail) the else block is executed.

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”;
} ?>

Chapter 6 PHP Conditional Statements 107


www.tntextbooks.org

If elseif else statement in PHP:


If-elseif-else statement is a combination of if-else statement. More than one statement can
execute the condition based on user needs.

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

Example: else executes the following


block of statements if the
<?php
condition in the corresponding if
$Pass_Mark=35; is false. After the else, if another
$first_class=60; condition is to be checked, then an if
$Student_Mark=70; statement follows the else. This is else
if and is called as if else ladder.
if ($Student_Mark>= $first_class){
echo “The Student is eligible for the promotion with First Class”;
}

elseif ($Student_Mark>= $Pass_Mark){


echo “The Student is eligible for the promotion”;
}
else {
echo “The Student is not eligible for the promotion”;
} ?>

108 Chapter 6 PHP Conditional Statements


www.tntextbooks.org

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

●● The if statement contains boolean expression inside brackets followed by a


single or multi line code block.
●● if-else Statement also provides for a second part to the if statement, that is else.
The else statement must follow if or else if statement.
●● else if Statement The ‘if ’ statement can also follow an ‘else’ statement, if you
want to check for another condition in the else part.

Conditional It performs different actions for different decisions in programing language


Statements
IF else Statement The If Statement is a way to make decisions based upon the result of a
condition.
Switch Statement Switch statements work the same as if statementsbut they can check for
multiple values at a time

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

110 Chapter 6 PHP Conditional Statements


www.tntextbooks.org

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

a) how are uhello print “some”;


b) hihello ?>
c) hi a) all
d) no output b) some
4. Statement which is used to make c) error
choice between two options and only d) no output
option is to be performed is written as
a. if statement 7. What will be the output of the
following PHP code ?
b. if else statement
<?php
c. then else statement
d. else one statement $x = 10;
5. What will be the output of the $y = 20;
following PHP code ? if ($x > $y + $y != 3)
<?php print “hi” ;
$a = “”;
if ($a) else
print “all”; print “how are u”;
if
?>
else
print “some”; a) how are u
?> b) hi
a) all
c) error
b) some
d) no output
c) error
d) no output

Chapter 6 PHP Conditional Statements 111


www.tntextbooks.org

8. What will be the output of the 4. List out Conditional Statements in


following PHP code ? PHP.
<?php 5. Write Syntax of the If else statement
$x = 10; in PHP.
$y = 20; 6. Define if...elseif....else Statement in
if ($x > $y && 1||1) PHP.
print “hi” ; 7. Usage of Switch Statement in PHP.
else 8. Write Syntax of Switch statement.
print “how are u”; 9. Compare if and if else statement.
?>
a) how are u Part - III
Explain in Brief Answer
b) hi
1. Write the features Conditional
c) error
Statements in PHP.
d) no output
2. Write is the purpose of if elseif else
9. What will be the output of the stament.
following PHP code ? 3. Differentiate Switch and if else
<?php statement.
if (-100) 4. Write Short notes on Switch
print “hi” ; statement.
else 5. Differentiate if statement and if
print “how are u”; elseif else stament.
?>
Part - IV
a) how are u b) hi
Explain in detail
c) error d) no output 1. Explain Function Conditional
Statements in PHP.
Part - II
2. Discuss in detail about Switch
Short Answers
statement with an example.
1. Define Conditional Statements in
3. Explain the process Conditional
PHP
Statements in PHP?
2. Define if statement in PHP.
4. Explain concepts of if elseif else
3. What is if else statement in PHP?
statement.
5. Explain if else statement in PHP.

student activity

●● Create simple decision making scenario using if else statement in student


management application
●● Explain real world usages in using Conditional Statements

112 Chapter 6 PHP Conditional Statements


www.tntextbooks.org

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:

for (init counter; test counter; increment counter) {


code to be executed;
}

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

Action after each iteration i++

Figure 7.1 For loop Structure and Flow chart

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:

for each ($array as $value) {


code to be executed;
}

seq = [18, 20, 32]


for each x of seq The foreach construct
print x provides an easy way to
end iterate over arrays. foreach works only
on arrays and objects, and will issue
18 20 32 an error when you try to use it on a
variable with a different data type or
an uninitialized variable.
print___
Figure 7.2 Foreach loop Structure and Flow

114 Chapter 7 Looping Structure


www.tntextbooks.org

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

{ True(3) False(3) Exit loop


Statement-1;
Statement-2;
-
-
Statement-n;
Updation; 4

Figure 7.3 While loop Structure and Flow

Syntax:

while (condition is true) {


code to be executed;
}

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?

Figure 7.4 DoWhile loop Structure and Flow Chart

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

116 Chapter 7 Looping Structure


www.tntextbooks.org

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

Looping In programming it is often necessary to repeat the same block of code a


Structure given number of times, or until a certain condition is met. This can be
accomplished using looping statements
for Loop For loops execute a block of code a specified number of times.
foreach Loop The foreach construct provides an easy way to iterate over arrays
While Loop PHP while loops execute a block of code while the specified condition is
true.

EVALUATION

Part - I 3. Which loop evaluates condition


Choose the correct answer expression as Boolean, if it is true,
1. Most complicated looping structure it executes statements and when it is
is false it will terminate?

a) While a) For loop b) For each loop

b) Do While c) While loop d) All of them

c) For 4. Which loop evaluates condition


expression as Boolean, if it is true,
d) None of them
it executes statements and when it is
2. Loops that iterate for fixed number false it will terminate?
of times is called
a) For loop
a) Unbounded loops
b) For each loop
b) Bounded loops
c) While loop
c) While loops
d) All of them
d) For loops
Chapter 7 Looping Structure 117
www.tntextbooks.org

5. What will be displayed in a browser 8. Consider the following code


when the following PHP code is <? php
executed: $count=12;
<?php do{
for ($counter = 20; $counter < 10; printf(“%d squared=%d<br/>”,
$counter++){ $count, pow($count,2));
} while($count<4);
echo “Welcome to Tamilnadu “;
?>
}
echo “Counter is: $counter”; What will be the output of the code.
?> a) 12 squared 141
b) 12 squared=141
a) Welcome to Tamilnadu
c) “12 squared=141”
b) Counter is: 20
d) Execution error
c) Welcome to Tamilnadu Counter
9. What will be the output of the

is: 22
following PHP code ?
d) Welcome to Tamilnadu Welcome
<?php

to Tamilnadu Counter is: 22
for ($x = 1; $x < 10;++$x)
6. What will be displayed in a browser {
when the following PHP code is
print “*\t”;
executed:
}
<?php
?>
for ($counter = 10; $counter < 10;
a) **********
$counter = $counter + 5){
b) *********
echo “Hello”;
} c) ***********
?> d) Infinite loop
a) Hello Hello Hello Hello Hello 10. What will be the output of the
b) Hello Hello Hello following PHP code ?
c) Hello <?php
d) None of the above for ($x = -1; $x < 10;--$x)
7. PHP supports four types of looping {
techniques; print $x;
a) for loop }
b) while loop ?>

c) foreach loop a) 123456713910412


d) all the above b) 123456713910
c) 1234567139104
d) Infinite loop
118 Chapter 7 Looping Structure
www.tntextbooks.org

Part - II 3. Differentiate For each and While


Short Answers loop.
1. Define Looping Structure in PHP. 4. Write short notes on Do while Loop.
2. Define for loop in PHP. 5. Differentiate While and Do while
loops.
3. What is For each loop in PHP?
4. List out Looping Structure in PHP. Part - IV
5. Write Syntax of For loop in PHP. Explain in detail
6. Write Syntax of For each loop in 1. Explain Looping Structure in PHP.
PHP.
2. Discuss in detail about For each
7. Write Syntax of while loop in PHP.
loop.
8. Write Syntax of Do while loop in
PHP. 3. Explain the process Do while loop.
9. Compare For loop and for each loop. 4. Explain concepts of for loop with
10. Usage of for each loop in PHP example.
5. Explain array concepts in Looping
Part - III Structure.
Explain in Brief Answer
1. Write the features Looping Structure.
2. Write the purpose of Looping
Structure in PHP

student activity

●● Create simple array element and display the values using foreach
●● Explain real world usages in using Looping Structure

Chapter 7 Looping Structure 119


www.tntextbooks.org

08
CHAPTER

Forms and Files

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

8.1 HTML Forms Basic HTML Form Controls


Main objective of PHP and HTML form The following control types are available
controls are to collect data from users. In in HTML form controlling:
the web development, user access website ●● Text inputs ●● Radio box
or web pages from remote client machine ●● Buttons ●● File Select
and feed the data to server. These data are
●● Checkbox ●● Form Tag
collected via HTML form controls like
Text inputs contain textbox and text area
textbox, dropdown box and radio button
controls. Buttons may contain Submit
etc., and sent to server using server side
button, Reset button and Cancel Button.
programming like PHP.
Checkbox is the important feature which

Pizza Shop 2.0

Name
Supreme
Pizza Topping Vegetarian
Hawaiian

Pizza Sauce Tomato


Optional Extras Extra Cheese Gluten Free Base
Delivery Instructions:

Send my order

Figure 8.1 Example of HTML form Page

120
www.tntextbooks.org

Forms and files


Forms and files are most important concepts that the PHP web development processes.

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

8.1.1 PHP Basic Form Handling


When the user keying the input data in HTML controls and clicks the submit button the
request will be generated and reaches a PHP file which is mentioned in the FORM tag
under the Action attribute. All input values are synchronized and sent to the server via
POST method or GET method. Method is an attribute form tag in HTML. Once the data
reaches the server, two PHP variables such as $_POST and $_GET collects the data and
prepares the response accordingly.
Post Method: The input data sent to the server with POST method is stored in the request
body of the client’s HTTP request.
Get Method: The input data sent to the server with POST method via URL address is
known as query string. All input data are visible by user after they clicks the submit button.

Example:
Test.html:
<html>
<body>

<form action=”welcome.php” method=”post”>

Name: <input type=”text” name=”name”><br>


E-mail: <input type=”text” name=”email”><br>
<input type=”submit”>
</form>

</body>
</html>
Welcome.php:
<html>
<body>
Welcome <?php echo $_POST[“name”]; ?><br>
Your email address is: <?php echo $_POST[“email”]; ?>
</body>
</html>

Chapter 8 Forms and Files 121


www.tntextbooks.org

Output

Name: sethuraman
E-mail: [email protected]
Submit

Output
Welcome sethuraman
Your email address is: [email protected]

Figure 8.2 Login module

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

Validation rules for HTML input field


Name (Text Input) : Should require letters and white-spaces
Email (Text Input) : Should require @ and .strings
Website (Text Input) : Should require a valid URL
Radio : Must be selectable minimum one value
Check Box : Must be checkable minimum one value
Drop Down menu : Must be selectable minimum one value

122 Chapter 8 Forms and Files


www.tntextbooks.org

Client Side Validation:


Before sending the data to server side program (PHP) the programmer can write few
validations from browser in the client machine. For this validation, we have to add
additional “required” attribute in HTML input tag. Refer Figure 8.3.
Example:
<input> required Attribute in HTML Username: Submit

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

PHP Open a File


fopen() is a system function available in PHP. This function helps to open a file in the
server. It contains two parameters one for the file and the other one specifies in which
mode the file should be opened (Read/Write).

Syntax:
$file_Object= fopen(“FileName”, “Read/WriteMode”) or die(“Error Message!”);

Example:
<?php
$myfile = fopen(“Student.txt”, “r”) or die(“Unable to open file!”);
?>

PHP Read a File:


The fread() function reads from an open file. The file object comes from fopen function.

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

Syntax: data Required. The data to write


to the file. Can be a string, an
fclose($file_Object);
array or a data stream
Example:
mode Optional. Specifies how
<?php
to open/write to the file.
$myfile = fopen(“student.txt”, “r”);
Possible values:
// some code to be executed....
fclose($myfile); FILE_USE_INCLUDE_PATH
?> FILE_APPEND
LOCK_EX

PHP write a File: context Optional. Specifies the


The fwrite() function is used to write to a context of the file handle.
file. Context is a set of options
that can modify the
Syntax:
behaviour of a stream.
fwrite($myfile, $txt);
Example: Example:
<?php <?php
$myfile = fopen(“new_school_file. $txt = “Student id “;
txt”, “w”)
or die(“Unable to open file!”); $myfile = file_put_contents(‘logs.txt’, $txt.
$txt = “School Name\n”; PHP_EOL , FILE_APPEND | LOCK_EX);
fwrite($myfile, $txt); ?>
$txt = “Student Name\n”; File Upload:
fwrite($myfile, $txt);
File upload is the best feature to select
fclose($myfile);
one file from the local machine to server
?>
machine. Form tag is used to mention a
PHP Appending a File method as POST or GET and encrypt
The file_put_contents() function is used attribute mentioned as “multipart/
to Append to a file. Look at Table 8.1 for form-data”. In the <Input> tag mention
various parameters used in appending a type=”file” attribute shows the input field
file. as a file-select control, with a “Browse”

124 Chapter 8 Forms and Files


www.tntextbooks.org

button next to the input control. The form above sends data to a file called “Student_
photo_upload.php”. Refer Figure 8.4.

Note:First, ensure that PHP is configured to allow file uploads.

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>

<form action=”Student_photo_upload.php “ method=”post” enctype=”multipart/form-


data”>
Select image to upload:
<input type=”file” name=”fileToUpload” id=”fileToUpload”>
<input type=”submit” value=”Upload Image” name=”submit”>
</form>

</body>
</html>

Figure 8.4 HTML and PHP File upload Screen

Chapter 8 Forms and Files 125


www.tntextbooks.org

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)

126 Chapter 8 Forms and Files


www.tntextbooks.org

points to remember

●● Form Attribute actionBackend script ready to process your passed data.


●● Method to be used to upload data. The most frequently used are GET and POST
methods.
●● Target Specify the target window or frame where the result of the script will be
displayed. It takes values like _blank, _self, _parent etc.
●● You can use the enctype attribute to specify how the browser encodes the data
before it sends it to the server.

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

Chapter 8 Forms and Files 127


www.tntextbooks.org

4. In HTML form <input type=”text”> 10. Which of the following functions


is used for reads the entire contents of a file?
a) One line text a) fgets()
b) Block of text b) file_get_contents()
c) One paragraph c) fread()
d) None d) readfile()
5. HTML classes that is already defined Part - II
and allow us to apply styles on it are Short Answers
called as
1. Define HTML form controls.
a) Pseudo classes
2. Define for Form Handling method
b) Css classes
in PHP.
c) Javascript classes
3. What is Form Validation in PHP?
d) None
4. List out HTML control to support
6. If you would like to read a file PHP language.
character by character which
function do you use? 5. Write Syntax of Text box in HTML.
a) fopen ( ) 6. Define File handling in PHP.
b) fread ( ) 7. Define Browse button in HTML.
c) fgetc ( ) 8. Write Syntax of Browse button in
d) file ( ) HTML.
7. PHP is a ______ typed language. 9. Compare Text box and Text Area.
a) User b) Loosely 10. Usage of File open function.
c) Server d) System
8. What does fopen() function do in Part - III
PHP? Explain in Brief Answer
a) It used to open files in PHP
1. Write the features Form Handling.
b) It used to open Remote Server
2. Write the purpose Get method and
c) It used to open folders in PHP Post method.
d) It used to open Remote Computer 3. Differentiate Get and Post Method.
9. How PHP files can be accessed? 4. Write short notes on File handling.
a) Through Web Browser 5. Write short notes on File handling
b) Through HTML files functions.
c) Through Web Server
d) All of Above

128 Chapter 8 Forms and Files


www.tntextbooks.org

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)

Chapter 8 Forms and Files 129


www.tntextbooks.org

09
CHAPTER

Connecting PHP and MYSQL

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

Connecting PHP and MySQL language connectivity, which covers


Data is important to all computer and Database connection establishment,
Internet related applications. Numerous Database Selection, SQL statement
growths of data need a secure and execution, and Connection termination.
convenient environment to store and
manipulate autonomously. All these
9.1 MySQL Function in PHP
features are available in Relational In PHP Scripting language many functions
Database Management System (RDMS) are available for MySQL Database
such as MySQL, Oracle, IBM DB2, connectivity and executing SQL queries.
and Microsoft SQLSERVER etc. These MySQLi is extension in PHP
databases are connected with Programing scripting language which gives access to
language and perform the major operations the MYSQL database. MySQLi extension
like INSERT, SELECT, UPDATE and was introduced version 5.0.0,
DELETE using Structure query language
(SQL). The combination of
PHP and MySQL has become
very popular server side web MySQL.
scripting language in Internet.
Refer Figure 9.1. php
This chapter covers
MySQL and PHP scripting
Figure 9.1 Browser Button

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

9.1.1 Database Connections:


Before accessing MySQL Database, connect to Database Server machine via PHP scripting
language using Mysqli_connect() Function.

Syntax:

mysqli_connect(“Server Name “,”User Name”,”Password”,”DB Name”);

This function requires four parameters to connect to database server. Database Server
name, Database username, password and Database Name.

9.1.2 Managing Database Connections


The below code snippet describes managing database connection methods and features.
<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$DB_name = “School_DB”;

// Create connection
$conn = mysqli_connect($servername, $username, $password,$DB_name);

// Check connection
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
?>

Chapter 9 Connecting PHP and MYSQL 131


www.tntextbooks.org

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.

9.1.3 Performing Queries


The main goal of MySQL and PHP connectivity is to retrieve and manipulate the data
from MySQL database server. The SQL query statements are helping with PHP MySQL
extension to achieve the objective of MySQL and PHP connection. “mysqli_query” is a
function, helps to execute the SQL query statements in PHP scripting language.

Syntax:

mysqli_query(“Connection Object”,”SQL Query”)

Example:
$con=mysqli_connect(“localhost”,”my_user”,”my_password”,”Student_DB “);
$sql=”SELECT student_name,student_age FROM student”;mysqli_query($con,$sql);

9.1.4 Closing Connection:


mysqli_close() Function is used to close an existing opened database connection between
PHP scripting and MySQL Database Server.

Syntax:

mysqli_close(“Connection Object”);

Example:
<?php
$con=mysqli_connect(“localhost”,”$user”,”$password”,”SCHOOL_DB”);
// ....some PHP code...
mysqli_close($con);
?>

132 Chapter 9 Connecting PHP and MYSQL


www.tntextbooks.org

Example of PHP and MySQL Program:


<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;
$dbname = “school_DB”;
$connection = mysqli_connect(‘$servername ‘, ‘$username’, ‘$password’,’$dbname’);
if (mysqli_connect_errno())
{
echo “Failed to connect to MySQL: “ . mysqli_connect_error();
}
sql_stmt = “SELECT * FROM my_contacts”; //SQL select query
$result = mysqli_query($connection,$sql_stmt);//execute SQL statement$rows =
mysqli_num_rows($result);// get number of rows returned
if ($rows) {
while ($row = mysqli_fetch_array($result)) {
echo ‘ID: ‘ . $row[‘id’] . ‘<br>’;
echo ‘Full Names: ‘ . $row[‘full_names’] . ‘<br>’;
echo ‘Gender: ‘ . $row[‘gender’] . ‘<br>’;
echo ‘Contact No: ‘ . $row[‘contact_no’] . ‘<br>’;
echo ‘Email: ‘ . $row[‘email’] . ‘<br>’;
echo ‘City: ‘ . $row[‘city’] . ‘<br>’;
echo ‘Country: ‘ . $row[‘country’] . ‘<br><br>’;
}
}
mysqli_close($connection); //close the database connection
?>
In the above code snippet, the SQL query retrieve two records from student table in school
database. These records are populated into client browser using PHP scripting language.

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.

Chapter 9 Connecting PHP and MYSQL 133


www.tntextbooks.org

Facebook technology stack consist of application written in many language, including


PHP and many others. Facebook still using PHP but it has built a compiler for it so it
can be turned into native code on.Facebook has many things built in PHP. Actually it’s
not the real PHP, Facebook has written alternative version of PHP that is, HipHop’s HPHP’c
which help to convert PHP code into C++.

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

●● PHP is Open source & Community support scripting language


●● PHP is a server-side scripting language designed for Web development.
●● Seventy Percentage of Website has been built by PHP and MySQL
●● Major of the webservers can support PHP scripting language
●● PHP can embed easily with HTML and client side scripting language
●● PHP has built-in function which is easily connect to MySQL database
●● PHP scripting language has been supported by many Software frameworks

SQL SQL is a domain-specific language used in programming and designed for


managing data held in a relational database management system
Queries A query is a request for data or information from a database table or
combination of tables.
MySQL MySQL is an open-source relational database management system
SERVER A server is a computer or a device that provides functionality for other
programs or devices, called “clients”. This architecture is called the client–
server model, and a single overall computation is distributed across multiple
processes or devices.
Database A database is an organized collection of data, generally stored and accessed
electronically from a computer system.

134 Chapter 9 Connecting PHP and MYSQL


www.tntextbooks.org

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

Chapter 9 Connecting PHP and MYSQL 135


www.tntextbooks.org

7. Which is the not a correct MySQL Function in PHP ?


a) Mysqli_connect() Function
b) Mysqli_close() Function
c) mysqli_select_data() Function
d) mysqli_affected_rows() Function
8. How many parameter are required for MYSQLi connect function in PHP ?
a) 2 b) 3 c) 4 d) 5
9. How many parameter are required for MYSQLi query function in PHP ?
a) 2 b) 3 c) 4 d) 5
10. How many parameter are required for MYSQLi Close function in PHP ?
a) 1 b) 2 c) 3 d) 5
11. Which version of PHP supports MySQLi fuctions ?
a) Version 2.0
b) Version 3.0
c) Version 4.0
d) Version 5.0

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

Chapter 9 Connecting PHP and MYSQL 137


www.tntextbooks.org

10
CHAPTER

Introduction to Computer Networks

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

10.1 Introduction All are well-known the term Internet


Networks of network is called Internet.
A set of computers connected together for
A multination company having
the purpose of sharing resources is called
worldwide branches, the company wants
as computer networks. At present, Internet
to know about the demand and feedback
is the most common resource shared
of product in day to day basis. If all
everywhere. Some of the shared resources
branches are connected in network with
shown in Figure 10.1 are file server, web
Internet easily collect all the information
camera, speakers, printer, scanner, fax
about the product.
machine etc., Accessing services such as
WWW (World Wide Web), Digital audio, Computer networking is a technique
Digital video which are shared to use of digital telecommunications network one
applications, software, and storage servers. that permits nodes to share its resources. This
computer networking exchanges the data
with each other through wired or wireless
connections between different terminals called
nodes. The data from these wires is transferred
over any cable media such as fiber optic cable
wire or a wireless media such as WiFi.
Computer which is connected to
network called as nodes. The data originates
and terminates at these particular nodes is called
Figure 10.1 Devices in Network as a source and destination. In networking,
138
www.tntextbooks.org

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.

10.2 History of Computer Networking and the Internet



The history of computer networks and its development were briefly explained in the table
given below:
Table 10.1 History of computer Networking

S. No Period Method History

1 Late SAGE (Semi – It was used at U.S Military Radar system.


1950 Automatic Ground
Environment)

2 1960 SABRE(Semi At Commercial Airline Reservation system online


Automatic Business connected with two main frame computers.
Research
Environment)

Packet switching Packet switching was developed by Paul Baran and


Donald Devices to transfer the information between
computers and network.
NPL network (National Physical Laboratory ) at united
kingdom local area network (LAN) using line speed of
768kbit/s was implemented by Davies pioneered

3 1963 Intergalactic Intergalactic Computer network was send by J.C.RLicklider


Computer network to his office colleagues discussing about this concept, a
computer network engaged to access communication with
users of computers.

Chapter 10 Introduction to Computer Networks 139


www.tntextbooks.org

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)

140 Chapter 10 Introduction to Computer Networks


www.tntextbooks.org
Age of commence begins
1995
Mosaic created
1993
WWW created
1989
Internet named and goes TCP/IP
1984
TCP/IP Created
1972
TCP/IP Created
1972
ARPANET
1969
Hypertent invented
1965
Packet switching invented
1964
First vast computer network envisioned
1962
Silicon chip
1958
A mathematical theory of communication
1948
Memex conceived
1945

1945 1995

Figure 10.2 Evolution of Internet

INTERNET Stands for sending and receiving money via payment


●● INTERnational NETwork (Technology, gateway using this Internet. Refer Figure
telecom, intelligence) 10.2 for the Evolution of Internet
●● INTER connected computer NETwork Internet is running all time 24X7,
(science, space and environment) 365 days. A person sale or buy anything and
●● Internet stands for Interesting Notions everything, anywhere and anytime that is
Transmitted Electronically Round main advantage of Internet.
Newly Engineered Technology. Now on E-Governance made easier
to collect their certificates through online,
Now a days the Internet plays a vital early days a person spend more time to
role. It provides all the information and collect the certificates and he have to directly
services to us. Early days if we want many more difficulties. To avoid this bribery
anything, we have to go to market and at office e-governance via Internet let a new
purchase in person. Nowadays we order path on all for ordinary man.
anything and everything (food, clothes, E-Banking plays an important role
stationeries, vegetables…etc.) through in our day today life, via Internet it can be
online(Internet). Online service providers accessed anytime, anywhere 24/7. The speed
are Flipkart, Amazon, snap deal etc to buy and efficiency was very much better than
products via Internet and have the product that of done by counter at bank. Now a days
at door steps. Online payments help in online payment were done via Internet to

Chapter 10 Introduction to Computer Networks 141


www.tntextbooks.org

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

something’s goes wrong. initially being developed, companies


Now a days computer are not waited and they do not feel shy
network technology to advertisement about the 5G efforts.
was developing in very It might be tested on laboratory on by
interesting ways. Some prototype versions of some elements then
keys developed that it may be standard 5G consumers were
have occurred over past several years also interested on the promise of signal
included coverage with 5G. Figure 10.3 shows
Growth on popularity of cloud Generation of Mobile Networks
storage and cloud computing. On behalf
of buying physical copies of games, music
and movies, increasingly downloading (or
streaming) and buy digital licenses their
need via Internet.
Developments on mobile network
infrastructure–both deployments of 4G
and 3G networks (older) that have allow
the people in their developed areas who
can allow it to their smart mobile phones
as video broadcasting system and as
mobile television. Some of the people Figure 10.3 Generation of Mobile Networks
underlying and staying connected all the
times, whenever they at the workplace, via Artificial intelligence will help
a home network, via public WiFi hotspots to maintain, manage, and protect it.
or smart phones. Now the networks were monitored by
algorithm that enables for anomalous
Difficulties faced by the service
build-ups of traffic and activity which
providers (include Google)in expanding
may be the result of nasty activities
their residential fiber optic cables
such as (DDos) Distributed Denial-of-
Internet service due to increased
Service attacks and attempted hacks.
competition and installation cost
This Artificial Network powering
from other broadband providers. Even
algorithms will become most intelligent;
though 4G LTE mobile network was
it might find faster and reliable methods
not reached by many parts of world,
of anticipating threats and cleaning
the industry of telecommunication has
networks. Artificial intelligence able to
been hard working on the development
be a better predict traffic as it collects
of their next generation “5G” cellular
and analyzes data in real time, some of
communication Technology. This 5G
network managers were better prepared
intense to boost up the speed the mobile
for big events such as the World cup ,
connections dramatically. Exactly how
Olympics, Valentine’s Day, which often
much customers was in need of this 5G
put on the Internet under pressure.
connection and to go. When 4G was
Chapter 10 Introduction to Computer Networks 143
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

it might large or small scale B2C, B2B, 10.3.2 Networks at Home


B2G,C2B, C2C, C2G, G2B,G2C, G2G or Now a day on this current situation
commercial that transfer of information our entire home became networked
across the Internet can be done here. instead of indivigual network we can
Cheaper marketing was carried out on access more than one person in one
this method, on early days product choices device(router/datacard). On this home
and comparison is very difficult nowadays network gaming and entertainment was
easy it lookout in Internet, via network very much needed for both parent and
it can be very easier and very cheaper to children’s. Network at home is a group
reach the customer who was in need of of devices such as computers, mobile,
our product. Company renewals, license, speakers, camera, game system, and
other certificates, bill payments, receipts, printer that connect via network with
invoice, stock maintenance, can be done each other. Networks at home were
without any geographical boundaries connected in two ways they are
required here on doing via Internet
●● Wired network
and computer networks. Government
subsidies were available for their business ●● Wireless network
to promote their business by digitalization.
A Wired network system connected with
Direct human interactions are network cable . For example speakers,
reduced because of Internet. Even working CCTV, printers, outdoors, and scanners
environment is also shrink. Buyer directly etc., with cables.
purchase any product from manufacturer
A Wireless network is connecting
with lowest cost, middle person brokerage
devices like tablets(tab), indoor cameras
charges are reduced. Above is possible if we
and E-readers, etc., without cables (WiFi).
are in Internet. The network connectivity
Refer Figure 10.5
in business is shown in Figure 10.4

INTERNET

Figure 10.4 Networks in Business

Chapter 10 Introduction to Computer Networks 145


www.tntextbooks.org

Wired network be done easier via Internet and computer


networking. No geographical can separate
them.
From the home we ordered delicious
Wireless network food from various hotels and restarants
at time without delay can be bought via
Internet.

10.3.3 Mobile Networks


Figure 10.5 Wired and Wireless Network Mobile network is the network connecting
devices without cable (wireless). Mobile
Network at home plays main role
computers, such as laptop, tablet, and
to access all such as e-banking, e-learning,
hand held computers, were fastest growing
e-governance, e-health, telemedicine, call
segments. At land areas network was
centers, video conferencing, digitalization
distributed as cells, each will be served by
of memories, can easy to access and use by
single – location transceiver, but generally
avoiding lot of time and stacked at queue.
three cell sites or a base transceiver station.
If a parent who stayed alone without This base station provides the cell with
their children’s, they can serve their parents network coverage and other features that
all via through Internet from food to can be utilized for transmission of voice,
medicine. Here on e-market or by online data and other content as well. Joining
shopping we can get from tooth paste to together all radio coverage is called as wide
car, all the travelling tickets and services can geographical area. This portable transceivers

DSL

Cable

Cellular
Internet

Internet service
provider

Satellite

Dial-up
Small office
telephone
Figure 10.6 Mobile Networks

146 Chapter 10 Introduction to Computer Networks


www.tntextbooks.org

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.

Probably all telecommunications


providers had developed data and voice
cellular networks for the occupied the
whole land area of earth. From this it
allows mobile phones and computing
devices were connected to the public
switched telephone network. Private
Figure 10.7 Social Media Outline
cellular networks can be used at various
locations like research and about large These social networks share several
organizations and small industries, likely attributes in common:
as public safety agencies. Even though ●● Membership. Social nets all generally

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.

Chapter 10 Introduction to Computer Networks 147


www.tntextbooks.org

●● Content contribution. These networks discussions became more convenient as


allow members to easily share not everyone needs to be online at the
comments, movies, music, short films exact same moment to post comments.
and/or photos with others. ●● Broadcast announcements. Cities
●● Frequent return visits. Healthy social can more comfort to spread word of
net takes a centers around a base of emergencies and natural calamities.
members who check in regularly to Venues and local shops can advertise
contribute theirs and also for new upcoming events on social networks.
updates Businesses able market their products
●● Human relationship building. The to customers (and retrieve some direct
common goal of most social networks feedback).
is allowing the interactions that ●● Fostering diversity of thought. Some
build stronger connections with in critics of social networks point out
communities of people. that online communities attract people
by similar interests and backgrounds.
Usefulness of Social Networks Indeed, when the people with different
Besides being a fun place to meet and opinions do get together on online, many
relax with people, social networking lead discussions seem to degenerate into
us some extremely useful benefits to their personal attacks and so-called “flame
individuals and communities: wars.” It can be argued, by online debates
●● Group information sharing over long are healthy in the long run. Although
distances. Although friends and family individuals may begin with more
members can keep in contact via extreme views, over time their thinking
mobile phone calls or by text messages, gets influenced by the comments of
social nets suggestion a much richer others at least to some extent.
environment for staying connected. To For people who struck with busy
many scenarios such as sharing photo schedule can have some relaxation and
albums videos or convey their wishes known current affairs, news via this social
someone, work better these networks networks can easier to wish someone and
because an entire group can participate keep on touch their follower, loveable
together with one. Overall, group person.

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

●● In 1960 SABRE(Semi Automatic Business Research Environment)for Commercial


Airline Reservation system online connected with two main frame computers.
●● Packet switching here it will split it into a small segments of data called as Packets
and combine all when it reach its destination.
●● In 1965 Telephone switch at first widely used Telephone switch was introduced by
Western Electric which implemented true computer control.
●● In 1966 WAN (WIDE AREA NETWORK)was introduced for time sharing.
●● ARPANET at 1969-1970 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.
●● In 1973 TCP/IP Using X.25 as commercial services were deployed, then using a
infrastructure for expanding TCP/IP networks.
●● ARCNET, token-passing network was used first to share storage device at 1976.
●● In 1995, the speed capacity of transmission of the Ethernet technology was slightly
increased from 10 Mbit/s to 100Mbit.
●● 1998, Ethernet supported transmission speed capacity towards gigabit. Frequently,
highest speeds up to 100 Gbit/s were added. Ethernet has ability to upgrade easily
like adapting to support NEW FIBRE OPTIC cable speeds etc.
●● Artificial intelligence able to be a better predict traffic as it collects and analyzes
data in real time, some of network managers were better prepared for big events
such as the World cup , Olympics, Valentine’s Day, which often put on the Internet
under pressure
●● The common uses of computer networks were
❍ Communication

❍ Resource Sharing

❍ Data (or) software sharing

❍ Money savings

●● Here computer networks were faster, the Internet became full strength and wireless
communications has been transformed the way of business performed
●● Networks at home were connected by two ways they are
❍ Wired network

❍ Wireless network

●● At land areas network was distributed as cells, each will be served by one fixed –
location transceiver. This base station provides the cell with network coverage. That
data can further be used for transmission of voice, data and any other resources.
Joining together of all radio coverage is called as wide geographical area.
●● When we have mixed group of people coming together online, many discussions
arise which lead to personal attacks called “flame wars.”

Chapter 10 Introduction to Computer Networks 149


www.tntextbooks.org

WWW World wide web


SAGE Semi – Automatic Ground Environment
SABRE Semi Automatic Business Research Environment
Packet Switching It used to transfer the information between computers and
network
Telephone Switches First widely used to which implemented true computer control.
WAN Wide Area Network
Arpanet Advanced Research Projects Agency Network
Hosts the service provider that leases this infrastructure, which is
known as hosting.
NEW FIBER OPTIC cable Here speed capacity of transmission has increased 10 Mbit/s
to 100 Mbit/s now on this fibre optic cable has speed upto 100
Gbit/s
e-Governance This is an application of ICT for access the government services,
communication transactions, of various standards system
between government to citizen, government to business.
e-Banking It was a safe, fast, easy and efficient electronic service that
enables you access to bank account and to carry out online
banking services, 24 hours a day, and 7 days a week.
Hackers Hackers were skilled computer experts, some who with their
technical knowledge access our accounts.
Viruses Malware treats or computer warms that replicates it
By its own is called as virus
Globalized Developed to make international influence or operation
possible.
Blogging Add new material to or regularly update a blog.
Cloud Storage Just a storage of data on online, access in different area no
geographical limits was in need
Cloud Computing It is based on Internet computing, to share resources, software
and information.
e-Readers E-Readers is similarly called as e-book reader these were
designed for the purpose of reading via mobile electronics
device to read digital e-books and periodically
Flame wars Flame wars are nothing that lengthy exchange of angry or
abusive messages between users of an online forum or other
discussion area.

150 Chapter 10 Introduction to Computer Networks


www.tntextbooks.org

EVALUATION

Part - I 5. Wi-Fi is short name for


Choose the correct answer a) Wireless Fidelity
1. A set of computers connecting b) Wired fidelity
together is called as ----------
c) Wired fiber optic
a) Network b) Server
c) Hub d) Node d) Wireless fiber optic
2. Computer network devices that
6. People everywhere can express and
originates route and terminate the
publish their ideas and opinions via
data were called as
a) Tele-medicine
a) Hub
b) blogging
b) Resource
c) Node c) Server
d) Cable d) Node
3. Match the period and mehods 7. Which one of the following periods,
available on history of computer the speed capacity supported towards
networking in the Internet gigabit on computer network?
a) 1950 - X.25 TCP/IP a) SABRE
b) 1966 - SAGE
b) SAGE
c) 1976 - WAN
c) NEW FIBRE OPTICS
d) 1972 - ARCNET
d) ARCNET
a 4321 b 3421
c 1234 d 2341 8 One among them was challenging
to the business people on computer
4. Western Electric introduced the first networking
widely used ----------------- that a) Hacking
implemented true computer control.
b) Viruses
a) Packet switch
c) Both a & b
b) Arpanet
d) none of this above
c) Host
d) Telephone switch

Chapter 10 Introduction to Computer Networks 151


www.tntextbooks.org

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

152 Chapter 10 Introduction to Computer Networks


www.tntextbooks.org

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

List out the wireless network ?


1. Find out how your family members and public members uses the network ?
2. Instead of landline (wired network) what were the types of wireless network you
know
3. Some of example devices with wireless networks

How social media has its memory management ?


1. Do you have a account on social media (or) create an account
2. Analyse how the social media applications transfer a huge data

Chapter 10 Introduction to Computer Networks 153


www.tntextbooks.org

11
CHAPTER

Network Examples and Protocols

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

11.1 Introduction network. Network protocols have to do


end-to-end process of secure on time and
Internet Protocol (IP) is the principle of the
manage data or network communication.
communications protocol in the Internet
protocols for layering on datagram across All requirements which combine
boundaries of other networks. The main process, on network protocols such as to
function is to allows Internet working and carry out the communication between
boost up the Internet. routers, servers, computers, laptop, and
other authorized networked device. Here
Internet protocol (IP) will deliver
on network protocols might be installed
packets from the source host and it will
and rooters in both sender and receiver
deliver to the destination host via through
to ensure data or network communication
an IP address in the packets header. Vint
and apply to software and hardware nodes
Cerf and Bob Kahnin in 1974 introduced
which communicate on a network.
IP connection less datagram service was
in the transmission control program. Now The broad types of networking
the IP is referred as TCP/IP Transmission protocols, including:
Control Protocol/Internet Protocol. ●● Network communication protocols
Network protocols is that the usual is that the Basic data communication
procedures, rules, formal standards and protocols which specific as HTTP and
policies comprised of formats which TCP/IP .
allocates communication between more ●● Network security protocols is that
than one device which connected to the which implement security over
154
www.tntextbooks.org

Figure: 11.1 INTERNET

network communications and include system, including infrastructure and


HTTP, SFTP and SSL. hardware, whereas the web is one of the
●● Network management protocols will services interconnected over the Internet.
Provide network governance and See Figure 11.1
maintenance and include ICMP and INTRANET: It is a private
SNMP. network within an enterprise to share
company data and computing resources
11.1.1 Internet/Intranet/
Extranet between the employees. It may consist
of many interlinked local area networks.
INTERNET: The Internet, “the Net,” is a
It includes connections through one or
worldwide system of computer networks-
more gateway (connects two networks
A network of networks where the users
using different protocols together known
at any one computer can, if they have
as protocol convertor) computers to
permission, get information from any other
outside Internet. See Figure 11.2
computer. The Internet is a network of
global connections – comprising private,
public, business, academic and government
networks – linked by guided, wireless and
fiber-optic technologies. It was perceived
by the Advanced Research Projects Agency
(ARPA) of the U.S. government in 1969 and
was first recognized as the ARPANet. The
unique aim was to generate a network that
Figure 11.2 Intranet
would permit users of a research computer
from one university to “talk to” research EXTRANET: It is a private network that
computers on other universities. The uses Internet technology and the public
jargons Internet and World Wide Web are telecommunication system to securely
frequently used interchangeably, but they share business’s information with suppliers,
are not precisely the same thing; the Internet vendors, partners, customers, or other
denotes to the global communication businesses. See Figure 11.3 and 11.4
Chapter 11 Network Examples and Protocols 155
www.tntextbooks.org

Individual
Internet users

Firewall

Extranet
Figure 11.3 Extranet

Internet of Things refers to the digital


interconnection of everyday objects
(home applicances, wearable devices or
automobiles) with the Internet. The ‘thing’ in IoT
refers to an objects that have been assigned an IP
address and have the ability to collect and transfer
data over a network without manual assistance or
intervention.

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

156 Chapter 11 Network Examples and Protocols


www.tntextbooks.org

Network Diagram Internet


server Firewall

Extranet
server Intranet
Internet server

Application
server

Extranet Intranet

Figure 11.4 Internet, Intranet and Extranet

Table 11.2 Network Applications


Application of Internet. Application of Intranet Application of Extranet
●● Download programs and ●● Sharing of company ●● Customer communications
files policies/rules and ●● Online education/ training
●● Social media regulations ●● Account status enquiry
●● E-Mail ●● Access employee database ●● Inventory enquiry
●● E-Banking ●● Distribution of circulars/ ●● Online discussion
●● Audio and Video Office Orders ●● Supply – chain managements
Conferencing ●● Access product and ●● Order status enquiry
●● E-Commerce customer data ●● Warranty registration
●● File Sharing ●● Sharing of information of ●● Claims
●● E- Governance common interest ●● Distributor promotions
●● Information browsing ●● Launching of personal/
●● Search the web addresses departmental home pages
for access through search ●● Submission of reports
engine ●● Corporate telephone
●● Chatting and etc directories.

11.1.2 Mobile Networks Within each cell there is a base station,


A mobile network or cellular network as it which sends and receives the mobile signals.
is made up of a large number of signal areas A mobile device will connect to the nearest
called cells. These cells join to form a large or least base station. The base stations are
coverage area. Users can cross into different connected to digital exchange where the
cells without losing their connection. communication is sent to other telephone
Chapter 11 Network Examples and Protocols 157
www.tntextbooks.org

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+

First Generation (1G) 1981


– NMT launch
During the initial periods the mobile
Rural
systems were based on analog
transmission. NMT stands for Nordic
Mobile Telephone communication. They
Microcells
had a very low traffic density of one
call per radio channel, and a very poor
voice quality, and they used unsure and
Urban
unencrypted transmission, which leads to
the spoofing of its identities.

Figure 11.5 Mobile Network Second Generation (2G) 1991 –


Mobile networking assign to the technology GSM launch
and supports voice/data, network Later the second generation of mobile
connectivity using via radio transmission systems were placed on digital transmission
solution. Mobile networking assign to the with GSM. GSM stands for (Global
technology that can support data / voice, System for Mobile communication)
network connectivity using via radio was most popular standard which is used
transmission solution, wireless. Similarly in second generation, using 900MHz
the common application of mobile networks and 1800MHz for the frequency bands.
is mobile phones, tablets, etc.. In past, GSM mobile systems grown digital
wireless communications largely used transmission using SIM. SIM stands for
circuit switching to carry only voice over a (Subscriber Identity Module) technology
network, but now currently both data and to authenticate a user for identification
voice are being transmitted over both circuit and billing purposes, and to encrypt the
via switched networks and packet-switched data to prevent listen without permission
networks. (eavesdropping). The transmission used
The generations of mobile networks as TDMA. TMDA stands for (Time
are as follows. Division Multiple Access) and CDMA
One stands for (Code Division Multiple
●● First Generation(1G) 1981- NMT
Access ) method to increase the amount of
launch
information transported on the network.
●● Second Generation(2G) 1991-GSM
Mobility is supported at layer 2, which
Launch
158 Chapter 11 Network Examples and Protocols
www.tntextbooks.org

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.

Fifth Generation (5G) 2019+


5G is the stage succeeds the 4G (LTE/
WiMAx), 3G(umts) and 2G(GSM)
syetems. 5G targets to performance Figure 11.6 Wi-Fi
the high data rate, reduced latency,
energy saving, cost reduction, higher ADVANTAGES: Benefits of Wi-Fi are
system, capacity, and massive device ●● It provides mobility. Example: I get
connectivity. The two phases of 5G, Internet connection wireless through
First one will be Release-15 complete my laptop computer at home and at
by March 2019,Second one Release-16 work, because of Wi-Fi, hotspots both
is expected to complete at March2020, at home and at work.
for submission to the ITU(International ●● It provides connection to Internet.
Telecommunication Union) as a ●● Flexibility of LAN.
candidate IMT-2020 technology. The ●● Ensures connectivity.
ITU IMT – 2020 provides speeds up
●● It allows places that are remote to
to 20 gigabits per second it has been
benefit from connectivity.
demonstrated with millimeter waves of
●● Low cost, high benifts.
15 gigahertz and higher frequency. 3 GPP
standard includes any network using th 11.1.4 RFID
New Radio software. 5G New Radio can 1. RFID - Radio Frequency
access at lower frequencies from 600 MHz Identification.
to 6 GHz. Speed in the lower frequencies
2. RFID uses RF wireless technology to
are only modest higher than 4G systems,
identify.
estimated at 15% to 50% faster.
RFID stands for Radio –Frequency
11.1.3 WLANS 802.11 Identification (RFID). RFID used for radio
Wi-Fi stands for Wireless Fidelity. It waves to read and capture information
is a wireless network technology that stored on a tag attached to an object. Tag
permits computers and alternative devices can be read from several feet away and
to be connected to every alternative into a does not need to be in direct-line-of-sight
local area network and to the net without of the reader to be tracked. RFID has been
wires and cables. Wi-Fi is additionally stated made up of two parts a reader and a tag
as wireless local area networkthat stands for or a label. RFID tags are installed with a
wireless local area network, and 802.11, that transmitter and receiver.

160 Chapter 11 Network Examples and Protocols


www.tntextbooks.org

RFID component on the tags has ●● A Controller: It is the host computer


two parts: a microchip which stores and with a Microprocessor which receives
processes the information, and the antenna the reader input and process the data.
to receive and transmit a signal. The Tag Two types of RFID Systems:
replies the information from its memory 1. Active RFID system: the tag has its
bank. The reader will transmit to read the own power source. These systems
result to RFID computer program. used for larger distances and to track
Two types of RFID tags were Active high value goods like vehicles.
RFID and Passive RFID systems. 2. Passive RFID system: the tag gets
1. Passive RFID tag will be used the power through power from a reader
reader radio wave energy to really its antenna to the tag antenna. They are
stored information back to the reader. used for shorter range transmission.
2. Battery powered RFID tag is installed Working of Passive RFID System
with small battery that powers the
A Passive RFID system using Induction
broadcast of information
coupling method:
Main Components of a RFID System
The RFID tag gets power from the reader
●● A RFID tag: It has silicon microchip through the inductive coupling method.
attached to a small antenna and mounted See Figure 11.9
on a substrate. See Figure 11.7

Reader
Tag

Reader coil inductively coupled to tag coil

Figure 11.9 Passive RFID using Inductive Coupling

A Passive RFID system using EM


Figure 11.7 RFID Tag wave propagation method:
●● A reader: It has a scanner with antennas The reader antenna transmits the
to transmit and receive signals, used electromagnetic waves that are received
for communication. See Figure 11.8 by the antenna. See Figure 11.10
The tag amtenna reflects back
the received signal

Reader antenna sends


electric signal to the tag
antenna
Figure 11.8 An RFID Reader Figure 11.10 Passive RFID using EM-wave
transmission
Chapter 11 Network Examples and Protocols 161
www.tntextbooks.org

Working Of Active RFID System


TIPS
The reader sends signal to the tag using an
antenna. See Figure 11.11 There are many prompts used to remember
the OSI layer order:
●● Everyone Needs Data Processing.
Reader or
interrogator ●● Everyone Should Try New Diet Pepsi.

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

Figure 11.12 OSI LAYERS

162 Chapter 11 Network Examples and Protocols


www.tntextbooks.org

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

Time to live Protocol Header checksum


Source address
Destination address
Options
Data

Source port Destination port


Sequence number
Acknowledgement number
TCP flags
TCP

Offset Revserved C E U A P R S F Window


Checksum Urgent pointer
TCP options

Figure 11.13 TCP/IP Layer

Chapter 11 Network Examples and Protocols 163


www.tntextbooks.org

The Different Layers of TCP/IP HTTPS positions for Hypertext


There are four total layers of TCP/IP Transfer Protocol Secure. It’s a protocol
protocol, each of which is listed below where encoded data transfer on a secure
with a brief description. connection. This HTTPS make data more
and provides data security over the network
●● Network Access Layer - concerned
mainly on public networks like Wi-Fi. See
with building packets.
Figure 11.14
●● Internet Layer - describes how packets
are to be delivered. For example, let us take a bank
website, say hdfcbank.com. https it support
●● Transport Layer - ensure the proper
for our secured bank transaction in networks
transmission of data.
Frequently we go to login page, we may watch
●● Application Layer - application an HTTPS in address bar with some specific
network processes. These processes design. HTTPS mainly deals with financial
include File Transfer Protocol (FTP), transactions or transfer users personal data
Hypertext Transfer Protocol (HTTP), were highly sensitive. Banking websites
and Simple Mail Transfer Protocol were common examples for HTTPS. Data
(SMTP). exchanged between the user and the website
is not stolen, read or altered by a third party.
11.2.3 Other Network Protocols
But it can be encode everything, with some
Network protocols other than OSI and
limitations too. For example, can encode port
TCP/IP were simply known as other
numbers and host addresses.
network protocols which implements
security over the network communication In layman’s terms, HTTPS gurantees
that include HTTPs, SSL, and SFTP. that users watch websites that they want
Other networks similarly classified in to watch. Data exchanged between the
network layer IP, ARP, ICMP,IGMP, at user and the website is not read, stolen
transport layer TCP,UDP at Application or tampered with by a third party. But
Layer HTTP, FTP, Telenet, SMTP, and it can’t encrypt everything - it has some
DNS. limitations too. For example, HTTPS can’t
encrypt host addresses and port numbers.

Figure 11.14 Network Layers

164 Chapter 11 Network Examples and Protocols


www.tntextbooks.org

TCP/IP Layers TCP/IP Prototocols

Application Layer HTTP FTP Telnet SMTP DMS

Transport Layer TCP UDP

Network Layer IP ARP ICMP IGMP

Network Interface Other link-layer


Ethernet Token ring
Layer protaocols

Figure 11.15 TCP/IP Protocols

TCP/IP procedures are based on a layered MAC (Medium Access Control)


framework. TCP/IP has four layers. See addresses. (A MAC address is a
Figure 11.15 hardware identification number that
uniquely identifies each device on
Network Interface Layer a network.)i.e., to map IP network
It is the bottommost level layer. It is addresses to the hardware addresses.
comparable to that of the Open System Internet Control Message Protocol
Interconnection Physical and Data Link (ICMP): Used by network devices to
layers. Different TCP/IP protocols are send error messages and operational
being used at this layer, Ethernet and information. Example: A host or router
Token Ring for local area networks and might not be reached or a requested
protocols such as X.25, Frame Relay, and service is not presented.
ATM for wide area networks. It is assumed ●● Internet Group Management Protocol
to be an unreliable layer. (IGMP): It is a communication protocol
Network Layer used by hosts and routers to send Multicast
(group Communication) messages to
It is the layer where data is addressed,
multiple IP addresses at once.
packaged, and routed among networks.
The important Internet protocols that Transport Layer
operate at the Network layer are: The sessions are recognized and data
●● Internet Protocol (IP): Routable packets are swapped between hosts in this
protocol which uses IP addresses layer. Two main protocols established at
to deliver packets. It is an this layer are:
unreliable protocol, does not ●● Transmission Control Protocol
guarantee delivery of information. (TCP): Provides reliable connection
Address Resolution Protocol oriented transmission between
(ARP): Resolves IP addresses to two hosts. It ensures delivery
Chapter 11 Network Examples and Protocols 165
www.tntextbooks.org

of packets between the hosts. Hypertext Transfer Protocol


User Datagram Protocol (UDP): (HTTP): The core protocol of the World
Provides connectionless, unreliable, Wide Web. File Transfer Protocol (FTP):
one-to-one or one-to-many delivery. enables a client to send and receive
complete files from a server. Telnet:
Application Layer connect to another computer on the
The Application layer of the TCP/IP model Internet. Simple Mail Transfer Protocol
is similar to the Session, Presentation, and (SMTP): Provide e-mail services. Domain
Application layers of the OSI Reference Name System (DNS): Refer to other host
Model. The most popular Application computers by using names rather than
layer protocols are: numbers.

points to remember

●● The Internet is a network of global connections – comprising private, public,


business, academic and government networks – linked by guided, wireless and
fiber-optic technologies.
●● ARPANET was Advanced Research Projects Agency (ARPA) of the U.S.
government in 1969 and was first recognized
●● INTRANET: It is a private network within an enterprise to share company data
and computing resources between the employees.
●● EXTRANET: It is a private network that uses Internet technology and the
public telecommunication system to securely share business’s information with
suppliers, vendors, partners, customers, or other businesses.
●● Communication over mobile network is be made up of voice, data, images and
text messages.
●● RFID –(Radio Frequency Identification) uses RF wireless technology to
identify.
●● Open System Interconnection (OSI) model was found in the year 1934, over
all basis that permits network protocols along with software and schemes to be
developed based on Universal guidelines.
●● Transmission Control Protocol/Internet Protocol, TCP/IP is a set of protocols
permitting communications among all computers on the Internet.
●● HTTP – A protocol used between a web client and a web server protects non-
secure data transmissions. The core protocol of the World Wide Web.
●● HTTPS - A protocol used between a web client and a web server permits secure
data transmissions.
●● FTP - Used between computers for sending and receiving data. Enables a client
to send and receive complete files from a server.

166 Chapter 11 Network Examples and Protocols


www.tntextbooks.org

●● Internet Protocol (IP): routable protocol which uses IP addresses to deliver


packets. It is an unreliable protocol, does not guarantee delivery of information.
●● Address Resolution Protocol (ARP): Resolves IP addresses to MAC (Medium
Access Control) addresses.( A MAC address is a hardware identification number
that uniquely identifies each device on a network.)
●● Internet Control Message Protocol (ICMP): Used by network devices to send
error messages and operational information.
●● Transmission Control Protocol (TCP): Provides reliable connection oriented
transmission between two hosts. It guarantees delivery of packets between the
hosts.
●● Simple Mail Transfer Protocol (SMTP): Provides e-mail services.
●● Domain Name System (DNS): A method of refering to other host computers by
using names rather than numbers.

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

Chapter 11 Network Examples and Protocols 167


www.tntextbooks.org

EVALUATION

Part - I a) Social media


Choose the correct answer b) mobile network
1. The-----------, “the Net,” is a c) whatsapp
worldwide system of computer d) software
networks 5. Wi-Fi stands for---------------------
a) Internet a) Wireless Fidelity
b) mobile b) wired fidelity
c) communication c) wired optic fibre
d) protocol d) wireless optic fibre
2. Which one of the following will be easy 6. A TCP/IP network with access
the way to uses Internet technology restricted to members of an
and the public telecommunication organization
system to securely share business’s
a) LAN b) MAN
information with suppliers, vendors,
partners and customers. c) WAN d) Intranet
a) Extranet b) Intranet 7. RFID stands for --------------
c) arpanet d) arcnet a) Radio Free identification
3. Match the following and choose the b) real Frequency identity
correct answer c) Radio Frequency indicators
i. HTTP -The core protocol of the d) Radio Frequency Identification.
World Wide Web. 8. It guarantees the sending of data is
ii. FTP- enables a client to send successful and which checks error on
and receive complete files from a operation at OSI layer is--------------
server. a) Application layer
iii. SMTP - Provide e-mail services. b) Network layer
iv. DNS- Refer to other host c) Transport Layer
computers by using names rather d) Physical layer
than numbers.
9. Which one of the following will
a) i, ii, iii, iv b) ii, iii, iv, i secure data on transmissions
c) iii, iv, i, ii d) iv, iii, ii, i a) HTTPS b) HTTP
4. Communication over ------------ c) FTP d) SMTP
------is be made up of voice, data,
10. ----------- provides e-mail service
images and text messages.
a) DNS b) TCP
c) FTP d) SMTP
168 Chapter 11 Network Examples and Protocols
www.tntextbooks.org

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

List out some web address with http and https


1. Find some of the http web addresses
2. Give some example for https
3. Can you know difference between http and https.

Chapter 11 Network Examples and Protocols 169


www.tntextbooks.org

12
CHAPTER

DNS (Domain Name System)

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

12.1 Introduction seven layers. Application layer is one


among the seven layers. There are several
In earlier, websites were accessed through
applications in the application layer and
their IP addresses. It was difficult for an
DNS (Domain Name System) is one among
individual to remember all the IP address
them. Internet is based on IP addresses,
to access the websites. So, the domain
not domain names. But it is easy to use
names were created and mapped with
domain names to refer them rather than
IP addresses. Like phonebook where all
the long numbers (IP address). To enable
the contact numbers are stored under
the use of domain names in a network,
respective names and are accessed by the
the Domain Name System (DNS) is used.
contact names, Domain Name System
Domain names to IP address mapping
(DNS) maintains all the directory of
must be consistent across the network
domain names/host names and help us to
to ensure interoperability. DNS provides
access the websites using the domain/host
the domain name to IP address mapping
names.
through Name servers. To know more
about DNS working we must first know
12.2 Overview of DNS about IP address, URL, DNS components.
For the communication to takes place, So, let us see about each in detail. Refer
the information should pass through Figure 12.1

170
www.tntextbooks.org

www.tnschools.gov.in

35.173.69.207

The host computer

DNS server

Figure 12.1 Domain Name Systems

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

10000000 10001111 10001001 10010000


1st Byte 2nd Byte 3rd Byte 4th Byte

= 128 = 143 = 137 = 144

128.143.137.144
Figure 12.2 IPv4 Address

12.3.2 IPv6 Address


IPv6 address is a 128-bit unique address given to a computer system. The number of addresses
that can be formed in IPv6 is 2128. In IPv6 address, the 128 bits are divided into eight 16-bits
blocks. Each block is then changed into 4-digit Hexadecimal numbers separated by colon
symbols. E.g. 2001:0000:32313:DFE1:0063:0000:0000:FEFB. Refer Figure 12.3
128 Bits

Network prefix (64 bits) Host number (64 bits)

XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX

X - Hexadecimal number (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F


XXXX - 0000 to FFFF

Figure 12.3 IPv6 Address

12.4 Uniform Resource Locator (URL)


URL (Uniform Resource Locator) is the address of a document on the Internet. URL is
made up four parts–protocols, hostname, folder name and file name. Each part has its
own specific functions. Depending on the applications, additional information can be
added to the URL but the common and fundamental URL consists of these four parts.
Refer Figure12.4

http://cms.tn.gov.in/sites/default/files/press_release/pr070119a.jpg

Protocol domain name/ file


host name (this will have
Folders
an extension
such as .htm,
.jpg, .gif, .css)

Figure 12.4 URL Parts

172 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

Figure 12.4 shows the basic URL 12.5.1 Name Space


where http is a protocol, www.cms.tn.gov.in The domain names must be very unique
is a hostname / domain name, sites/ and appropriate. The names should be
default/files/press_release are the folders selected from a namespace. The name
and pr070119a.jpg is the file name. These space can be organized in two ways
are all the basic information which can be
●● Flat name space
obtained from a URL.
●● Hierarchical name space
URL Type
Flat name space is where the name
Depending on the location of the
is assigned to the IP address. They do not
document the URL is divided into 2 types
have any specific structure. In this flat name
●● Absolute URL space, some meaningful names are been
●● Relative URL given to IP address for accessing. The major
disadvantage of flat name space is that they
12.4.1 Absolute URL cannot be used in large system. Because they
Absolute URL is the complete address need to be accessed and controlled centrally
of a document on the Internet. Absolute to avoid ambiguity and redundancy. But it
URL contains all the information that are is difficult in flat name system. To avoid this
required to find the files on the Internet. major disadvantage hierarchical name space
These are similar to postal address if any is used in large.
of the information is missing then the Hierarchical name space is where
post will not be able to deliver to the right the name is made up of several parts.
person. Similarly, if any of the four parts is The first part may represent the nature
missing then the browser would not able of organization, the second part may
to link to the specific file. So, all the four represent the name of organization, and
parts is very important in absolute URL. third part may represent the department
of the organization and so on. In this way
12.4.2 Relative URL the power to control the name space can be
Relative URL is the partial address of a decentralized. The centralized authority
document on the Internet. Relative URL can be given to nature and then to name
contains only file name or file name with of the organization and so on. To achieve
folder name. We can use this type of URL hierarchical name space, Domain Name
when the file is on the same server related Space was designed.
to original document.
Domain Name Space

12.5 DNS Components Domain name space was designed to


achieve hierarchical name space. In this,
There are three important components in
the names are represented as a tree like
the Domain Name System. They are
structure with root element on the top
●● Namespace and this tree can have a maximum of 128
●● Name server levels starting from root element taking
●● Zone the level 0 to level 127.
Chapter 12 DNS (Domain Name System) 173
www.tntextbooks.org

Root (Level 0)

arpa com edu org ad zw

Figure 12.5 Domain Name Space

Figure 12.5 represent the domain Label


name space where the root element is It is a string which can have maximum of
present at the top most level i.e., level 63 characters. Each node in that level should
0. The root element always represents have different labels thereby assuring the
the NULL string (empty string). The individuality of the domain name.
next level to the root element is node
In other words, Labels are the
(children of root element). Each node
names given to domains. Domain is a sub
in the tree has a label and a domain
tree in domain name space tree structure.
name.
The domain can be further divided into
sub domains.
Root

Label

edu
edu. Domain name

Label

fhda fhda.edu. Domain name

Label

atc atc.fhda.edu. Domain name


Label

Challenger challenger.atc.fhda.edu. Domain name

Figure 12.6 Domain Name and Label

174 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

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

ROOT Root level

Top level
.com .org .net .in domains

Second level
.ac .mil .co .gov .nic
.tnscert .tnpesu domains

.tnteu .tn Sub domains

.dge
.eservices

Figure 12.7 Domain representation of www.tnscert.org

Chapter 12 DNS (Domain Name System) 175


www.tntextbooks.org

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.

Name Server is a main part in the


Domain names may also be used Domain Name System (DNS). It translate
in other than English languages
the domain names to IP addresses. Name
in UNICODE format. Tamil
language is also used in three country server contains the DNS database which
Top Level Domain names which are. consists of domain names and their
இந்தியா,.சிங்கப்பூர் and .இலங் corresponding IP addresses. There is a
கை
need to store large number of domain
Domain Name Meaning
names for the world wide usage, so plenty
இந்தியா India
of servers are used in the hierarchical
சிங்கப்பூர் Singapore manner. Name servers do the important
Srilanka task of searching the domain names. While
இலங்
you searching a website, Local Name
கை
server (provided by ISP) ask the different
12.5.2 Name Servers name servers until one of them find out
The information which needs to be stored your answer. At last it returns IP address
in Domain name space is quite large. for that domain name. Your computer can
Single system would be inefficient and now connect to the requested webpage
insufficient to store such a huge amount stored on the webserver. Refer Figure 12.8

176 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org
Root DNS
name server Root DNS
Web Server
name server

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

Types of Name Servers 12.5.3 Zone


There are three types of Name Servers which The entire name space is divided into many
control the entire Domain Name System: different zones. It is the area up to which
the server has access. Zone is defined as
1. Root Name Server - top level server
a group of contiguous domains and sub
which contains entire DNS tree,
domains. If the zone has a single domain,
maintained by ICANN. There are 13
then zone and domain are the same.
servers.
2. Primary/Master Name Server– Every zone has the server which
contains a zone resource records. contains a database called zone file. Using
These records are updatable by domain the zone file, the DNS server replies the
name holders such as organizations. queries about hosts in its zone. There are
two copies of zone files available, Master
3. Secondary/Slave Name Server –
file and slave file. Refer Figure 12.9
contains a copy of primary server files.
This server has no authority to update,  A domain is a single node of

but reduce the workload of master the Domain Namespace.

server by sharing the queries.  A zone is a subset of the



Domain namespace generally
stored in a file.
ICANN, Internet Corporation for ●● Domain Name space is an entire collection
Assigned Name and Numbers is the Domains, Sub domains and Zones
Non-profit Organization ●● Name server manages the database of
which assigns names and domain names and corresponding IP
numbers for all Internet addresses.
resources like domain ●● A server can contain more than one zone
names and IP addresses. files (Zones). A zone can contain more
than one sub domains

Chapter 12 DNS (Domain Name System) 177


www.tntextbooks.org

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.

Figure 12.9 Zone and Domains


12.5.5 How DNS works?
12.5.4 Resolver When the user enters the URL (consists
Domain Name System is a client/ server of protocol, domain name, folder name,
application. A host system need to map file name) in the browser, the system first
domain name to IP address or vice versa checks its DNS cache for the corresponding
according to the call and that work is done IP address. If the IP address is found in
by resolver. Resolver either asks server to the cache then the information is retrieved
provide information about IP address. If it from cache. If not, then the system needs to
doesn’t find any information, then it sends perform DNS query i.e., the system needs
the request to other servers and so on. to query the resolver about the IP address
Once the resolver receives the mapping, it from Internet Service Provider (ISP). Each
checks whether it is an error or resolution resolver has its own cache and if it is found
(mapping) and provides result according to in that then that information is retrieved. If
that. not, then the query is passed to next domain

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

Figure 12.10 workflow of basic DNS

178 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

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

IANA is an affiliated authority of ICANN. IANA does the


overall management of the DNS Root, IP addressing, and
other Internet protocol resource handling. IANA takes care of
a number of key aspects of the DNS, including the root zone, and the
domains .int and .arpa.
https://www.iana.org/

The WHOIS is a service of ICANN. It is a free, publicly available


directory containing the details of registered domain names and their
owners (registrants). https://whois.icann.org/en

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.

●● IP address is a logical address used to uniquely identify a computer over the


network. There are two types: IPv4 and IPv6.

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

Chapter 12 DNS (Domain Name System) 179


www.tntextbooks.org

●● IPv6 address is a 128 bit unique address given to a computer or a device. It


follows Hexadecimal number notation.

●● URL (Uniform Resource Locator) is the address of a document on the


Internet. URL is divided into two types: Absolute URL and Relative URL

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

●● Label is a string which can have maximum of 63 characters. Each node in


that level should have unique label.

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

●● Resolver, a client/ server application, initiates the process of resolving the


domain names.

180 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

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

Chapter 12 DNS (Domain Name System) 181


www.tntextbooks.org

3. How many bits are used in the IPv6 a) Zone


addresses? b) Domain
a) 32
c)Resolver
b) 64
d) Name servers
c) 128
d) 16 11. ISP stands for
4. Expansion of URL is a) International Service provider
a) Uniform Resource Location b) Internet Service Provider
b) Universal Resource Location c) Internet service Protocol
c) Uniform Resource Locator
d) Index service provider
d) Universal Resource Locator
12. TLD stands for
5. How many types are available in
Relative URL? a) Top Level Data
a) 2 b) 3 c) 4 d) 5 b) Top Logical Domain
c) Term Level Data
6. Maximum characters used in the
label of a node? d) Top Level Domain
a) 255 b) 128 c) 63 d) 32 13. Which of the following statements
are true?
7. In domain name, sequence of labels
are separated by i) Domains name is a part of URL.
a) ; ii) URL made up of four parts
b) .(dot) iii) The relative URL is a part of Absolute
URL
c) :
iv) URL doesn’t contain any protocol
d) NULL
a) i & ii b) ii
8. Pick the odd one out from the
following. c) i, ii & iii d) i, ii & iv
a) node b) label 14.
c) domain d) server Assertion (A) : The number of
addresses used in IPv6 addressing
9. Which of the following initiates method is 128 .
the mapping of domain name to IP Reason (R) : IPv6 address is a 128 bit
address? unique address.
a) Zone a) A is true and R is false.
b) Domain b) A is false and R is true.
c) Resolver c) Both A and R are correct and R is

d) Name servers the correct explanation of A.
10. Which is the contiguous area up to d) Both A and R are correct and R is

which the server has access? not the correct explanation of A.

182 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

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

1. Find out IP address of your system


i. Click start menu and type command or cmd to open command prompt
ii. A command prompt window will be displayed. Type ipconfig and press enter.
iii. The IP number is listed under IPv4 Address and IPv6 Address.
iv. Find out the MAC address of the network card in the list.
v. Find out and analyze what the other information displayed on the screen.

Chapter 12 DNS (Domain Name System) 183


www.tntextbooks.org

2. Find out IP address for the websites using command prompt


i. Click start menu and type command or cmd to open command prompt.
ii. A command prompt window will be displayed. Type tracert and press enter.
iii. From the displayed window, You’ll see the IPv4 and IPv6 address.
iv. Find out IP address for another website.

3. List out websites to find out IP address of other websites


For example:
https://ipinfo.info/html/ip_checker.php

4. Use nslookup in command line and analyse what purpose it is used.

5. Buy your own domain name or create free sub-domain and connect free hosting
servers.
For example:
www.goDaddy.com, www.webs.com

184 Chapter 12 DNS (Domain Name System)


www.tntextbooks.org

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.

13.1 Introduction and became one as Internet. The essential


service of Internet is WWW (World Wide
Once the basics of computer was invented
Web) which was invented by Tim Berners
by Charles Babbage, the people started
Lee. Internet can be accessed easiliy from
inventing much newer technology
anywhere but the setting up of the network
compatible with the computer. In the 19th
is a big nightmare. Still network cables are
Century the US military base had much
being used worldwide to produce a faster
technology to serve weapons and people
Internet to the people. The network cables
but they did not have any technology to
are used to transfer the data from one device
send a report from one place to another.
to another device.
Then slowly the word network grew bigger
and bigger. Then the Advanced Research
Projects Agency Network (ARPANET) was
invented and the TCP/IP was adopted with
ARPANET. Then the researchers began to
research the “network of networks”.
First the network was within one
computer to another computer, then it
moved to one place to another place, then
Figure 13.1 Network cables
one city to another, then slowly it grew up Source: Data center knowledge

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

5. Serial and Parallel cables: Before


In the year of 1980s to 1990s the
Ethernet and the USB were not
developed. Then the Serial and
Figure 13.4 Fiber optic cable with 4 cores
Parallel interface cables are used to

combined with one cable.
connect the Internet to the system.
4. USB Cables: The Universal Serial They were sometime used for PC
Bus are used to connect keyboard, to PC networking. Before the USB
mouse and other peripheral devices. emerged, the system will have both
But there are some special network serial port and parallel port. The
devices used to connect the Internet serial port will send 1 bit at one time

Figure 13.5 The USB Cables and USB dongle connected to a laptop.

Chapter 13 Network Cabling 187


www.tntextbooks.org

whereas the parallel port will send 8


Just like the crossover cable,
bit at one time. The parallel cables
RS-232 cable is also used for
are used to connect to the printer interconnecting two computers
and other disk drivers. RS232 is one without modem. So it is also a null
type of serial cable, also known as modem cable. A cable interconnecting
Null modem cable. See Figure 13.6 two devices directly is known as a null
modem cable.

Figure 13.6 The serial cable at the left and



parallel cable at the right.

6. Ethernet Cables: Ethernet cable is


the most common type of network
cable mainly used for connecting
the computers or devices at home
or office. This cable connects wired 13.3 Ethernet Cabling

devices within the local area network Components
(LAN) for sharing the resources and
Computer Networking is a group of
accessing Internet.
interconnected computers or other
The Crossover Ethernet cable is an devices for sharing the data and resources
example of the Null modem Cables. among them. Computers can be connected
This cable is used to join two PCs or on the network with the help of wired
two network devices of the same type. media (Unshielded Twisted pair, shielded
This cable is the sophisticated Ethernet Twisted pair, Co-axial cables and Optical
cable used to connect the Internet to fibre) or wireless media (Infra Red,
the system. This cable works at a speed Bluetooth, WiFi)
of 10 gbps and more. The Ethernet
Wireless networks enable more
crossover cable is identical on both
devices including mobiles sharing the
the ends. Nowadays Routers are being
resources and Internet connections
connected through the crossover cables
remotely. But Compared to wireless
to provide wireless network from the
networks, wired networks maintain a
local network. See Figure 13.7
faster Internet speed and more secure.
Wired networks for larger area are more
expensive. Wired networks are still used
widely in the offices where need increased
speed and secure connections.
The computers with wired
connections must be configured with
Figure 13.7 The Ethernet cables.

188 Chapter 13 Network Cabling


www.tntextbooks.org

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

Chapter 13 Network Cabling 189


www.tntextbooks.org

13.3.2 RJ45 Connector to terminate the twisted-pair cable on


The RJ45 connector is a small plastic cup each end, which are T-568A and T-568B.
which will be used to connect the wire The Table 13.1 describes the pinouts and
inside the connector and ready to connect colour coding of these schemes.
the Internet. The RJ45 connector looks
similar like a telephone jack but it looks Table 13.1 Wiring schemes with colour

 
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

190 Chapter 13 Network Cabling


www.tntextbooks.org

T568A T568B
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
12
34
56
78

Figure 13.10 The Ethernet wiring schemes (T568A & T568B)

TX which is transmission of data and RX negative terminal and the color is


which is Receiver of data. See Figure 13.10 used in this position is Green.
& Figure 13.11 3. In the position of pin no.3 describes
the receive data or bidirectional
1. In the Figure 13.10 the position of pin with the RX (positive). The RX is
no. 1 describes the transmit data or compatible to receive the data which
bidirectional, the bidirectional means has positive terminal and the color is
it can be sent to both connection used in this position is white orange.
with the TX (positive). The TX+ has 4. In this position of pin no. 4 describes
positive terminal and the color is used that it is not connected or bidirectional.
in this position is white green. It means there will be no transmitting
2. In the position of pin no. 2 describes or receiving will exist. But it can be
the transmit data or bidirectional used later for some other connection.
with the TX (negative). The TX- has The color used in this pin is blue.

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

Position 1 at RJ45 jack Position 1 at RJ45 plug


Figure 13.11 The Ethernet port pin details

Chapter 13 Network Cabling 191


www.tntextbooks.org

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)

connect and transmit data to the devices


on the network. It may be an expansion
card or built-in type. Expansion card is a
separate circuit board also called as PCI
Ethernet card which is inserted into PCI Ethernet cable RJ-45 Connector (8P8C plug)
(Twisted pair cable)
slot on motherboard of a computer. Now
a days most of the computers come with Figure 13.13 Ethernet cable with Port
built-in Ethernet cards which resides on Once you inject the plug into the
motherboard. Wireless Ethernet cards are port the two led lights will glow in the
also available, which uses radio waves to computer; the one is green and another
transmit data. See Figure 13.12 one is orange. The orange light will
Ethernet port is an opening which is a start blinks then it means the Internet is
part of an Ethernet card. It accepts RJ45 connected.
Motherboard

Ethernet port Ethernet port

PCI Ethernet port Built-in Ethernet card


Figure 13.12 Ethernet Network Interface Cards

192 Chapter 13 Network Cabling


www.tntextbooks.org

Crimping process for making


TIPS
Ethernet cables

Devices/Technology Alternative Names 1. Cut the cable with desired length


Ethernet Technology RJ45, 802.3 2. Strip the insulation sheath about 1
(according to IEEE) inch from both end of the cable and
RJ45 Connector RJ45 plug, Ethernet expose the Twisted pair wires
(male) connector, 8P8C
3. After stripping the wire, untwist the
connector
smaller wires and arrange them into
RJ45 socket (female) Rj45 jack, Ethernet the proper wiring scheme, T568B
Port
preferred generally.
RJ45 Cable Ethernet cable,
4. Bring the wires tighter together and
cut them down so that they all have
13.3.4 Crimping Tool the same length ( ½ inch).
Crimping is the process
5. Insert the all 8 coloured wires into the
of joining two or more
eight grooves in the connector. The
pieces of metal or wire by
wires should be inserted until the plastic
deforming one or both of
sheath is also inside the connector.
them to hold each other.
Joining RJ45 connector 6. Use the crimping tool to lock the
together with twisted pair cable at each end RJ45 connector on the cable. It
is an essential process in Ethernet cabling should be strong enough to handle
which lead the cable to function properly. manual traction. Now it is ready for
data transmission.
The crimping tool is a physical tool
which is used to connect the patch wire 7. Use a cable tester to verify the proper
and the Ethernet connector. The crimping connectivity of the cable, if need. See
tool looks like a small cutting handle with Figure 13.15
two mold of Ethernet port. The tool will
puncture the connector and makes the
wire set in the connector. See Figure 13.14

Figure 13.14 Crimping Tool for RJ-11 (6 pin) and Figure 13.15 Crimping process using crimping

RJ-45 (13 pin) tool

Chapter 13 Network Cabling 193


www.tntextbooks.org

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

13.4 Types of Jacks transmission configuration, the two


pins give the receiver configuration
Registered Jacks: A Registered Jack
and the other two pins will be
commonly known as RJ is a network
kept for reserved. The two pin will
interface used for network cabling, wiring
have the positive terminal and the
and jack construction. The primary
negative terminal.
function of the registered jack is to
connect different data equipment and
telecommunication devices. The commonly
known registered jacks are RJ-11, RJ-45,
RJ-21, and RJ-28. The registered jack refers
to the male physical connector (Plug), a
female physical connector (Jack) and it’s
wiring. We will talk some of the variety of
registered jack below with some definitions.
See Figure 13.16
1. RJ-11: It is the most popular modern
form of registered jack. It is found
Figure 13.16 comparison of RJ-45 with RJ-11
in home and office. This registered
jack is mainly used in telephone 2. RJ-14 and RJ-61: The RJ-14 is the
and landlines. When we look the same as RJ-11 which will be used
pin details of the RJ-11, there are for telephone lines where same it
6 pin where the two pins give the as 6 pins whereas the RJ-61 will
194 Chapter 13 Network Cabling
www.tntextbooks.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

applications. See Figure 13.18 7 7


8 8

Figure 13.19 Straight through wiring connection

13.5.2 Cross-over Wiring


If you require a cable to connect two
computers or Ethernet devices directly
together without a hub, then you will need
to use a Crossover cable instead. Then the
Figure 13.18 The RJ-21 Ethernet port wire with pairs(Tx and Rx lines) will be crossed
many other ports on the other end.
which means pin 1 & 2 of the plug on one
end are connected with pin 3 & 6 of the
13.5 Ethernet Cable Color plug on other end, and vice versa (3 & 6 to

Coding Techniques pin 1 & 2).
There are three types of wiring techniques The easiest way to make a crossover
to construct the Ethernet cable. It is also cable is to make one end to T568A colour
known as color coding techniques. They coding and the other end to T568B.
are Another way to make the cable is to
●● Straight-Through Wiring remember the colour coding used in this
●● Cross-over Wiring type. Here Green set of wires at one end
●● Roll-over Wiring are connected with the Orange set of wires
Chapter 13 Network Cabling 195
www.tntextbooks.org

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

196 Chapter 13 Networking Cabling


www.tntextbooks.org

another. They are mainly used in ●● The RJ45 Ethernet connector is


Wide Area Network (WAN). a small plastic cup which will be
●● There are two types of fibre optic used to connect the wire inside the
cables are available are Single- connector and ready to use to connect
mode (100BaseBx) and Multimode the Internet.
(100BaseSX). ●● The RJ45 connector has eight small
●● Single-mode cables are used for long pins inside to connect eight small
distance transmission and at a high wires in the patch cable. The eight
cost whereas the multimode cables are cables has eight different colours
used for short distance transmission ●● The Ethernet port is the jack where
at a very low cost. the Ethernet cable is to be connected.
●● USB cables are used connect keyboard, This port will be there in both the
mouse and other peripheral devices computers and the LAN port.
●● The serial port will send 1 bit at one ●● The crimping tool is a physical tool
time whereas the parallel port will which is used to connect the patch wire
send 13 bit at one time. and the Ethernet connector(RJ45).
●● The parallel cables are used to connect ●● A Registered Jack (RJ) is a network
to the printer and other disk drivers. interface used for connecting
●● Cross over cable is used to join two different data equipment and
network devices of the same type telecommunication devices.
like example two PCs or two network ●● RJ11 jack is mainly used in telephone
devices. The Null modem Cables are and landlines
the example of the crossover cables. ●● There are three wiring techniques
●● The Ethernet cable is the basic available in Ethernet cables: Straight
component of the Local Area Network through Wiring, Cross over Wiring
(LAN) and Roll over Wiring.

ARPANET Advanced Research Project Agency Network, predecessor to the modern


Internet
WWW World Wide Web, Definition comes from the World Wide Web Consortium
(W3C): “The World Wide Web is the universe of network-accessible
information, an embodiment of human knowledge.”
10BASE-T / 10 Mbps / 100 Mbps
100BASE-TX / Mbps stands for Mega bits per second
100BASE-FX/ T stands for Twisted pair
100BASE-BX/ X stands for number of paired copper wires
100BASE-SX F, B, S – Fibre optic cables
Chapter 13 Networking Cabling 197
www.tntextbooks.org

WAN Wide Area Network,


WAN is the network that spans large geographical area
USB Universal Serial Bus, connects all the peripheral devices with the computers

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

Part - I 4. Expansion of UTP is


Choose the correct answer a) Uninterrupted Twisted Pair

1. ARPANET stands for b) Uninterrupted Twisted Protocol
a) American Research Project c) Unshielded Twisted Pair


Agency Network d) Universal Twisted Protocol
b) Advanced Research Project Area 5. Which medium is used in the optical

Network fibre cables to transmit data?
c) Advanced Research Project a) Microwave b)infra red


Agency Network c)light d)sound
d) American Research Programs 6. Which of the following is a small

And Network peripheral device with a sim slot to
2. WWW was invented by connect the computers to Internet?
a) Tim Berners Lee a) USB
b) Charles Babbage b) Dongles
c) Blaise Pascal c) Memory card
d) John Napier d) Mobiles
3. Which cable is used in cable TV to 7. Which connector is used in the
connect with setup box? Ethernet cables?
a) UTP cable b) Fibre optics a) RJ11 b) RJ21

c) Coaxial cable d)USB cable c) RJ61 d) RJ45
198 Chapter 13 Networking Cabling
www.tntextbooks.org

8. Which of the following connector is Part - II


called as champ connector? Short Answers
a) RJ11 1. Write a note on twisted pair cable.
b) RJ21 2. What are the uses of USB cables?
c) RJ61 3. Write a note on the types of RJ45
d) RJ45 connector.
9. How many pins are used in RJ45 4. What is an Ethernet port?
cables? 5. What is the use of Crimping tool?
a) 8 6. What are the types of twisted pair
b) 6 cables?
c) 50 7. What is meant by champ connector?
d) 25 Part - III
10. Which wiring standard is used for Explain in Brief Answer
connecting two computers directly? 1. Write a note on crossover cables.
a) straight Through wiring 2. Write a short note on RJ45 connector.
b) Cross Over wiring 3. What are the differences between
c) Rollover wiring serial and parallel ports?
d) None 4. What is meant by null modem cable?
11. pick the odd one out from the 5. What are the components involved
following cables in Ethernet cabling?
a) roll over 6. What are the types of Fibre optic
b) cross over cables?
c) null modem
Part - IV
d) straight through Explain in detail
12. Match the following 1. What is meant by Registered Jack?
1. Ethernet - Port Explain briefly the types of Jacks.
2. RJ45 connector - Ethernet 2. Explain wiring techniques used in
3. RJ45 jack - Plug Ethernet cabling.
4. RJ45 cable - 802.3 3. Explain about RJ45 connector.
4. Explain the components used in
a.1, 2, 4, 3 b. 4, 1, 3, 2 Ethernet cabling.
c. 4, 3, 1, 2 d. 4, 2, 1, 3 5. Explain the types of network cables

Chapter 13 Networking Cabling 199


www.tntextbooks.org

student activities

1. Make your own Crossover cable.


A Purchase the following
i. a patch cable(UTP cat 5e / 6) with desired length
ii. RJ45 connector(8P8C modular plug) of both wiring schemes(T568A and
 
T568B)
iii. Crimping Tool
 
B. Construct the cable using the method described in the text book, with the help
 
of crimping tool
2. Connect two computers using Crossover cable for sharing resources

200 Chapter 13 Networking Cabling


www.tntextbooks.org

14
CHAPTER

Open Source Concepts

LEARNING OBJECTIVES
To know the
●● Need of Open Source Software. ●● OpenNMS and Group which created
●● NS2 and its Use OpenNMS
●● OpenSource Hardware

14.1 Introduction one. Open source software is usually created


and updated by many programmers around
Free software and compilers were provided
the world and made freely accessible.
with early computer hardware. With these
Proprietary software is owned by an
human understandable code the user can
organization or individual. The makers
modify, add new code and identify the
of proprietary software have not allowed
errors.
the users or other developers to view or
Can anyone change the codes in edit the source code. But the advantage
open source software? of the proprietary software is that it gives
Open source software has been more control, support, training, security
developed by a variety of programmers. and stability for user making the software
However, to add a new change to the reliable to the users
software,the modified codewill be submitted In a network it is not easy to find
to a group of dedicated programmers. These problems. Especially when there are more
programmers then test the modified codes systems are connected, the complexity is
and if itsatisfies the appropriate rules, it will more, so we need Network Software to
then be distributed toall Control , Analysis the Server, System,
protocol, Network, Traffic flow and
Why it called open source reports about ups and downs of network
Open Source simply refers to making the parts. Notification help the user and
source code of the software freely available administrator easily find working status
for users or other developers to use and of network systems and hardware. Alert
make changes into the original repository message give details of faults, where and
or fork the project into and build a new when it happens. 201
www.tntextbooks.org

NRCFOSS When you change the source


National Resource Centre for Free and code, OSS requires the inclusion of what
Open Source Software an Institution you altered as well as your methods. The
of Government of India. To help in software created after code modifications
development of FOSS in India may or may not be made available for
free.
Organizations related to Open
Source Open-Source Software vs.
●● Apache Software Foundation
Free Software
●● The Document Foundation Although the terms are often used
interchangeably, OSS is slightly different
●● The Eclipse Foundation
from free software. Both deal with the
●● Free Software Foundation
ability to download and modify software
●● Linux Foundation without restriction or charge. However,
●● OpenCourseWare Consortium free software a concept developed in
●● Open Source Initiative the 1980s by an MIT computer science
researcher, Richard Stallman is defined
BOSS by four conditions, as outlined by the
BOSS (Bharat Operating System Solutions) nonprofit Free Software Foundation.
Operating System Developed in India These “four freedoms” emphasize the
by C-DAC (Centre for Development of ability of users to use and enjoy software
Advanced Computing) Help to prompt as they see fit.
the use of open source software in India.
In contrast, the OSS criteria, which
It Supports many India Languge.
the Open Source Initiative developed
a decade later, place more emphasis on
Types of open source license
the modification of software, and the
●● Apache License 2.0
consequences of altering source code,
●● BSD 3-Clause “New” or “Revised”
licensing, and distribution.
license
●● BSD 2-Clause “Simplified” or Obviously, the two overlap; some
“FreeBSD” license would say the differences between OSS
●● GNU General Public License (GPL) and free software are more philosophical
●● GNU Library or “Lesser” General than practical. However, neither should
Public License (LGPL) be confused with freeware. Freeware
●● MIT license usually refers to proprietary software that
●● Mozilla Public License 2.0 users can download at no cost, but whose
●● Common Development and source code cannot be changed.
Distribution License
●● Eclipse Public License

202 Chapter 14 Open Source Concepts


www.tntextbooks.org

Open-Source Software and


Copyright
Developers
OSS projects are collaboration Owner Owner Owner
opportunities that improve skills and
build connections in the field. Domains
OSS
that developers can contribute to the open Project
source community include:
●● Communication tools.
User User User
●● Distributed revision control systems.
●● Bug trackers and task lists.
●● Testing and debugging tools.

Copyright
Vendor Vendor Vendor
Owner
Contributor Contributor
OSS
Project
OSS
Project

Owner Owner Owner


User User User
Copyright

How Open Source work

Chapter 14 Open Source Concepts 203


www.tntextbooks.org

Benefits of Open Source 14.2 Network simulation


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

204 Chapter 14 Open Source Concepts


www.tntextbooks.org

14.3 Open NMS was Released in 1999 by Steve Giles, Brian


Weaver, and Luke Rindfuss.
Open NMS (Network Management System)
is a free and open-source initiative grade In 2004 OpenNMS Group was
network monitoring and management created by Balog, Matt Brozowski, and
platform. It is established and maintained David Hustace. It is written in Java and
by a community of users ,developers and by can run on all type of platform. It gives
the Open NMS Group, it offering services, us Event management & Notification,
training and support. The goal is for Open Discovery & Provisioning, service
NMS to be an actually distributed, scalable monitoring and Data Collection. Won lot
management application platform for all of awards for best of opensource software.
features of the FCAPS (Fault, configuration,
accounting, performance, security) network OpenNMS has three main functional
management model. Presently the emphasis areas:
is on Fault and Performance Management. ●● Service monitoring, where a number
of monitor modules can govern if
It was intended to cope tens of
network-based services (ICMP, HTTP,
thousands of devices from a single server
DNS, etc.) are accessible.
as well as achieve unlimited devices using
a cluster of servers. OpenNMS comprises a ●● Data Gathering by using SNMP and
discovery engine to routinely configure and JMX.
manage network devices without operator ●● Event management and notifications,
intervention. It is written in Java and is issued which comprises of alarm reduction
under the GNU (General Public License.) and a robust announcement system
OpenNMS is the Worlds first with accelerations and duty schedules.
software for Network monitor and OpenNMS is recognized for its
management with opensource options. scalability. Though it can be easily used
There are two types in this Meridian and to handle a small SMB Network, it is also
Horizon. When we need stability and long accessible enough to be used in place of large
term support choose Meridian which is enterprise management products such as HP
best for Enterprises as well as businesses. Open View, IBM Micro muse or IBM Tivoli.
Horizon used where innovation occurs In this period of increased
frequently. It is Best for IT-ecosystem, competition and cyber crimes, the
new technologie monitoring. OpenNMS computers used by indivudals or business
organisations may have spy
Open Source Hardware hardwares of rivals. Open source
● Remix hardware technology helps in such
● Remake threats. In this technique we get
● Remanufacture the components of the hardware
● Redistribute and its circuit diagram, so that we
● Resell can remove suspicious spyware if
● Study and Learn found.

Chapter 14 Open Source Concepts 205


www.tntextbooks.org

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.

NS2 Network Simulation 2

OpenNMS First Open Source Network Management Software

Trace File A document file, consists of every incident happens in a simulation

OTCL Object-oriented Tool Command Language

FCAPS Fault, configuration, accounting, performance, security

GNU General Public License

SSFNet Scalable Simulation Framework Net Models

API APPLICATION PROGRAM INTERFACE

SOURCE CODE Set of Instructions that decide, how the software should work

BOSS Bharat Operating System Solutions

C-DAC Centre for Development of Advanced Computing

206 Chapter 14 Open Source Software


www.tntextbooks.org

EVALUATION

Part - I 5. Fill in the blanks : NS2 comprises of


Choose the correct answer ______key languages?
1. If the source code of a software is a) 13 b) 3 c) 2 d) 4
freely accessible by the public, then 6. Choose the Correct Pair from the
it is known as following to build NS2
a) freeware a) UNIX & TCL
b) Firmware b) UNIX & a. C++
c) Open source c) C++ & OTcl
d) Public source d) C++ & NS2
7. Which of the following is not a
2. Which of the following is a software network simulation software?
program that replicates the
a) Ns2
functioning of a computer network?
b) OPNET
a) Network software
c) SSFNet
b) Network simulation
d) C++
c) Network testing
8. Which of the following is a open
d) Network calculator
source network monitoring
3. Which of the following can software?
document every incident that
a) C++
happened in the simulation and are
b) OPNET
used for examination?
c) Open NMS
a) Net Exam
d) OMNet++
b) Network hardware
9. Open NMS was released in
c) Trace file …………………
d) Net document a) 1999 b) 2000
4. Which is an example of network c) 2003 d) 2004
simulator? 10. OpenNMS Group was created
a) simulator by……………….
b) TCL a) Balog
c) Ns2 b) Matt Brozowski
c) David Hustace
d) C++
d) All of them.

Chapter 14 Open Source Software 207


www.tntextbooks.org

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

208 Chapter 14 Open Source Software


www.tntextbooks.org

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.

15.1 Introduction to In near future commercial activities



E-Commerce such as buying or selling of goods between
merchant and consumer will be bygone
“The wise possess all”.
and forgotten like barter system.
Anyone who is quick
to identify and adopts
innovations would be
successful. Commerce
always profits from
innovations. Successful businesses
quickly identify developing opportunities
in emerging new technology, and expand
their commercial capabilities.
The customer goes to the market,
checking out a variety of products,
choosing required stuff, purchasing them
Figure 15.1 Conventional commodities exchanging
and then paying the specific amount is

System
traditional commerce. However, recent
ways of buying or selling goods and Like the most other things, the
services have come up with technology Internet and technology have changed the
innovations. way that commerce is conducted. Refer
Figure 15.1
209
www.tntextbooks.org

In 1996, IBM coined the term A company can be called E-Business if


E-Business. Just, as business is broader and only if
than commerce, E-Commerce is a subset ●● It has the ability to conduct business
of E-Business. E-Commerce is commercial electronically over Internet.
transaction through Internet, but E-Business
●● It manages payment transaction
entirely depends on the Internet for its every
through Internet.
intra-company and inter-company activities
such as procurement of raw materials, ●● It has a platform for selling products &
marketing, finance, manufacturing, selling services via Internet.
and negotiation.
Definition
While, E-Commerce is limited E-Commerce is currently one of the most
with monetary transactions using important aspects of the Internet era. Just
Internet E-Business is grounded like the words e-mail, e-book with the prefix
on technologies such as Network ‘e’ (‘e’ stands for electronic) Commerce
Infrastructures (like Internet, Intranet, and Internet makes E-Commerce. It also
Extranet), Multimedia content & allows the consumers to exchange goods
network publishing infrastructures (like and services with no barriers of time
HTML, Online Marketing), Messaging & or distance. Electronic commerce has
information distribution infrastructures expanded rapidly over the past few years
(like EDI, e-mail, http, Computerized and is predicted to accelerate.
Inventory Management Systems)
and other Common business service E-Commerce can be described as the
infrastructures (like electronic payments process of buying or selling products,
gateways, globalized Supply Chain services or information via computer
Management (SCM), Online Transaction networks.
Processing). See Figure 15.2
It could be a consumer based retail
sites or auction sites or trade between large
business organizations. The commodity
E-Business could be a laptop or a wrist watch or it
could be an operating system or a simple
browser plugin.
Service Infrastructure

The goods, information or services


Multimedia content

Common Business
Infrastructure

& publishings

are delivered in tangible or electronic


Messaging &
Information
Distribution
Network

form. See Figure 15.3

Figure 15.3 Tangible and intangible goods.


Figure 15.2 E-Business building block

210 Chapter 15 E-COMMERCE


www.tntextbooks.org

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

In 1979, Michael Aldrich, an English entrepreneur,


proposed a technique that enables online
transaction processing between consumers and businesses,
or between businesses. It was later proficiently called
as E-Commerce. In 1980 he invented a multi-purpose
home infotainment device called Teleputer, which was a
fusion of Television, Computer and Telecom networking
technologies.

Chapter 15 E-COMMERCE 211


www.tntextbooks.org

Growth of E-Commerce is also


In August 11, 1994 by noon of
related to the socio-technological changes.
the day, Phil Brandenberger of
The more, the medium becomes deep- Philadelphia (U.S.A), bought a
rooted, the more, are the users drawn music CD (Sting’s “Ten Summoners’
towards it. Increase of users, increases the Tales”) from Kohn of Nashua (U.S.A)
markets. As the markets expand, more and paid $12.48 plus shipping charges
business organizations are attracted. The using his credit card through online. This
more businesses accumulate it create is marked as the first true E-Commerce
competition. The competition leads to transaction.
innovation; innovation in turn drives the
development of technology; technology
facilitates E-Commerce’s growth. See
Figure 15.4
Electronic date interchange allows
1960s companies to carry out electronic
transactions-a precursor to online
shopping
English inventor Michael Aldrich
connected a TV set to a computer
with a phone line and created 1979
“teleshopping” - meaning shopping
at a distance
1981 The first business-to-business
transaction from Thompson holidays

The ‘Electronic mail’ is launched by


Compuserve - users could purchase
1984
items directly from 110 online
merchants
The National Science Foundation
1991 allows the internet to be used for
commerical purposes
Online retailer NetMarket makes the
‘first secure retail transacton on th
web’ - a copy of Sting’s album Ten Aug 1994
Summoner’s Tales
Joe McCambley ran the first ever
Oct 1994 online banner ad. It went like on
HotWired.com and promoted 7 art
museums.
Amazon sold its first item - a science Jul 1995
textbook

eBay sold its first item - a broken


Sep 1995 laser pointer

The first online-only shop, Zappo’s,


opens 1999

Social commerce (people using


social media in their buying
2005
decisions) is born thanks to
networks like Facebook
Groupon is launched
2008

India’s Total E-Commerce sale is


2009 3.9 billion Americal Dollar
With mobile commerce, it is expected to
hike 265% up and will be $ 850 billion 2018
American Dollar

Figure 15.4 Timeline describing various events in E-Commerce

212 Chapter 15 E-COMMERCE


www.tntextbooks.org

15.3 The Development and ●● The Second Wave of Electronic


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

Blogs, Wiki, Instant Mesenger, 2D portals, Augmented Reality,


Read-only Web, Text, Widgets, Pull web Gesture Technology,
Catalogs, Forms, Search, Avatar representations,
Pictures, Flash Wearable Techanology,
Smart Personal Assistant,
3D Portals, Push web

1995 2004 2010

Figure: 15.5 Evolution of Electronic Commerce

Chapter 15 E-COMMERCE 213


www.tntextbooks.org

also the geographic coordinates are used 15.4 Classification of


to screen the specific location-tailored E-Commerce Business
information properly. The term Web 3.0, models
summarize the various characteristics
Business organizations, Consumers
of the future Internet which include
and Government (also called as
Artificial Intelligence, Semantic Web,
Administrations) are the major parties in
Generic Database etc.
the E-Commerce. Sometimes Employees
(Informal workers) also indulge in this
Dotcom Bubble system. Based upon the entities involved
The Dotcom Bubble was a historic in transaction, E-Commerce has been
excessive growth (excessive assumption) classified into the following typical
of economy that occurred roughly categories. The model in which the
between 1995 and 2000. It was also a
government plays as an entity is termed as
period of extreme growth in the usage
e- Governance. See Figure 15.7
and adaptation of the Internet as well.
In the late 1995, there was a
BUSINESS CONSUMER GOVERNMENT
tremendous development in US equity
investments in Internet-based companies.
During the dotcom bubble, the value of BUSINESS B2B B2C B2G

equity markets grew exponentially with


the NASDAQ composite index of US CONSUMER C2B C2C C2G
stock market rising from under 1000
points to more than 5000 points.
GOVERNMENT G2B G2C G2G
NASDAQ Composite Index
(1990-Present)
8000

7000

6000
Dot-com
market peak
Indes matches
Dot-com peak Figure 15.6 E-Commerce business models
5000

1. Business to Business (B2B)


4000
Irrational Dot-com
3000 exuberance market
speech trough
2000

2. Business to Consumer (B2C)


Dot-com bull
market begins
1000

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

3. Business to Government (B2G)


Dotcom Burst 4. Consumer to Business (C2B)

The Nasdaq-Composite stock market


5. Consumer to Consumer (C2C)
index, fell from 5046.86 to 1114.11. This is 6. Consumer to Government (C2G)
infamously, known as the Dotcom Crash 7. Government to Business (G2B)
or Dotcom Burst. This began on March
11, 2000 and lasted until October 9, 2002.
8. Government to Consumer (G2C)
During the crash, thousands of online 9. Government to Government (G2G)
shopping companies, like as Pets.com
failed and shut down. Some companies ●● Business to Business (B2B)
like Cisco, lost a large portion of their In B2B E-Commerce, commercial
market capitalization but survived, and
transactions take place between different
some companies, like Amazon declined
in value but recovered quickly. business organizations, through the
Internet. For example, a cycle company
214 Chapter 15 E-COMMERCE
www.tntextbooks.org

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

Out-sourcing and Off-shoring are generally associated with B2B E-Commerce.


●● If a company’s work is hired to another company, it would be termed as out-sourcing.
●● If the work is outsourced to a company, which is outside of its own country, is termed
as off-shoring.

Figure 15.7 Business to Business

●● Business to Consumer (B2C)


In B2C E-Commerce, commercial transactions take place between business firms and
their consumers. It is the direct trade between companies and end-consumers via the
Internet. B2C companies sell goods, information or services to customers through online
in a more personalized dynamic environment and is considered as real competitor for a
traditional storekeeper. An example of B2C transaction is a book company selling books to
customers. This mode is intended to benefit the consumer and can say B2C E-Commerce
works as ’retail store’ over Internet. See Figure 15.8

Figure 15.8 Business to Consumer

●● Business to Government (B2G)


B2G is a business model that refers to business organizations sells products, services or
information to Governments or to its administrations. In other words, when a company
get paid for its goods, services by the Government through Internet it is called as B2G
model. B2G networks models provide a way for businesses to bid on Government projects
or products those Governments might need for their organizations. e.g. A Government or
its administration buys laptops for students from a business. See Figure 15.9

Chapter 15 E-COMMERCE 215


www.tntextbooks.org

Figure 15.9 Business to Government

●● Consumer to Business (C2B)


C2B can be described as a form of E-Commerce where, the transaction is originated by
the consumers. The consumers will fix a set of requirements or specific price for a service
or a commodity. C2B model, is also called as reverse auction model. Here, customer bid
his price for a service or a product. Then E-Commerce business entity will match the
requirements of the consumers to the best possible extent.
For instance, in a travel website (eg.yatra.com) a consumer may specify his dates of travel,
his source and destination, number of tickets required and range of hotel etc. The website
then finds out the various options for him which best meets his requirements. These
websites generate revenue through affiliate links, sponsored advertisement or even a small
commission in every booking. e.g. Name-your-price websites. See Figure 15.10

Figure 15.10 Consumer to Business

●● Consumer to Consumer (C2C)


C2C in E-Commerce provides opportunity for trading of products or services among
consumers who are connected through the Internet. In brief when something is bought
and sold between two consumers using Internet it is called C2C E-Commerce. Here
the websites act as a platform to facilitate the transaction. The electronic tools and
Internet infrastructure are employed to support transactions between individuals.
Typically, this type of E-Commerce works as Consumer to Business to Consumer
(C2B2C). It means that a consumer would contact a business in search for a suitable
customer. Most of the auction websites and matrimonial websites are working on this
methodology.
For example, a consumer who wants to sell his property can post an advertisement
on the website (eg:timesclassifieds.com). Another person who is interested in buying
a property can browse the property, advertisement posted on this site. Thus, the two
consumers can get in touch with each other for sale/purchase of property through another
business’ website. See Figure 15.11

216 Chapter 15 E-COMMERCE


www.tntextbooks.org

Figure 15.11 Consumer to Consumer

●● Consumer to Government (C2G)


Citizens as Consumers and Government engage in C2G E-Commerce. Here an individual
consumer interacts with the Government. C2G models usually include income tax or
house tax payments, fees for issuance of certificates or other documents. People paying for
renewal of license online may also fall under this category. See Figure 15.12

Figure 15.12 Consumer to Government

●● Government to Business (G2B)


G2B is closely related to B2G. G2B in E-Commerce refers to a business model where
Government providing services or information to business organization. It may be a
formal offer such as a takeover bid for a road project. See Figure 15.13

Figure 15.13 Government to Business

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

Figure 15.14 ebiz.gov.in

Chapter 15 E-COMMERCE 217


www.tntextbooks.org

●● Government to Consumer (G2C)


G2C in E-Commerce is very similar to C2G. Here the Government provides platform for
its citizens to avail its services and information through th Internet. The services may
be issuance of certificates through online.e.g. https://csc.gov.in/governmenttocitizen. See
Figure 15.15

Figure 15.15 Government to Consumer

●● Government to Government (G2G)


G2G is the online (usually non-commercial) interaction between Government
organizations or departments. G2G’s principle objective is to implement e-governance
rather commerce. G2G model in e-governance involves distributing data or information
between its agencies/departments. G2G systems can be classified into two types
●● Internal facing or local level - joining up a single Government’s bureaucracies.
e.g. https://www.nic.in/
●● External facing or international level - joining up multiple Governments’
bureaucracy.

See Figure 15.16

Figure 15.16 Government to Government

15.5 E-Commerce Revenue Models



Apart from regular selling of commodities, today there are many other ways by which
companies can make money from the Internet. The other forms of E-Commerce activities
are:
1. Affiliate site is a form of third party marketing in which the site owner get paid
based on the performance. The affiliate site may be a price comparison service or
shopping directories or review sites or blogs that contain a link to a normal retailing
site and are paid when a customer makes a purchase through it. The affiliate site
usually attracts visitors by offering more information and tutorials on some specific
product or a topic. See Figure 15.17 to Figure 15.23
218 Chapter 15 E-COMMERCE
www.tntextbooks.org

Figure 15.17 Affiliate site (price comparation website)

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/

Figure 15.18 E-Auction website

Chapter 15 E-COMMERCE 219


www.tntextbooks.org

3. Banner advertisement site displays advertisements of other companies in its websites


and thereby earns revenue.

Figure 15.19 Banner advertisement site

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/

Figure 15.20 Bulk-buying sites

220 Chapter 15 E-COMMERCE


www.tntextbooks.org

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/

Figure 15.21 Digital Publishing website

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.

Figure 15.22 Google Search in IGNOU website

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/

Figure 15.23 Name-your-price sites

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.

Chapter 15 E-COMMERCE 221


www.tntextbooks.org

15.6 Comparison between Traditional Commerce and


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.

Figure 15.24 Traditional vs E-Commerce

Table 15.1 Traditional vs E-Commerce


Traditional Commerce E-Commerce
Traditional commerce is buying or selling of E-Commerce carries out commercial
products and services physically. transactions electronically on the Internet.
Customer can easily identify, authenticate and Neither customer nor merchant see the other.
talk to the merchant.
Physical stores are not feasible to be open all It is always available on all time and all days
the time. of the year.
Products can be inspected physically before Products can’t be inspected physically before
purchase. purchase.
Scope of business is limited to particular area. Scope of business is global. Vendors can
expand their business Worldwide.
Resource focus Supply side. Resource focus Demand side.
Business Relationship is Linear. Business Relationship is End-to-end.
Marketing is one way marketing. One-to-one marketing.
Payment is made by cash, cheque, cards etc. Payment system is mostly credit card and
through fund transfer.
Most goods are delivered instantly. It takes time to transport goods.

222 Chapter 15 E-COMMERCE


www.tntextbooks.org

15.7 Advantages and ●● Customers can shop from home or


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.

Chapter 15 E-COMMERCE 223


www.tntextbooks.org

●● Physical product disputes are a traditional supply chain arrangements


major disadvantage in E-Commerce. for perishable and non-durable goods.
E-Commerce purchases are often made ●● Delivery ambiguity. Since supplying
on trust. This is because, we do not have businesses can be conducted across the
physical access to the product. Though world, it can be uncertain whether they
Internet is an effective channel for visual are indeed genuine businesses or just
and auditory information it does not going to take our money. It is pretty hard
allow full scope for our senses. We can see to knock on their door to complain or
pictures of the perfumes, but could not seek legal recourse. Further, even if the
smell their fragrance; we can see pictures item is sent, it is easy to start bothering
of a cloth, but not its quality. If we want whether or not it will ever arrive on time.
to inspect something, we choose what
we look at and how we look at it. But in The following are some of the advantages
online shopping, we would see only the and disadvantages of E-Commerce for a
pictures the seller had chosen for us. Business organisation.
People are often much more comfortable
Benefits of E-Commerce to a
in buying the generic goods (that they
business organisation.
have seen or experienced before and in
which there is little ambiguity) rather ●● Access to Global Market: The Internet
than unique or complex things via the spans the world of E-Commerce, and
Internet. it is possible to trade with any business
or a person who is connected with the
●● We couldn’t think of ordering a single
Internet. It helps to access the global
ice cream or a coffee from a shop
marketplace. Simple local businesses such
in Paris. Though specialized and
as herbal product stores are able to market
refrigerated transport can be used,
and sell their products internationally
goods bought and sold via the Internet
using E-Commerce. Thus, the whole
need to survive the trip from the
world becomes a potential market for an
supplier to the consumer. This makes
E-Commerce company.
the customers turn back towards

Disruptive innovations in E-commerce


The innovations which replace the existing term disruptive innovation was first coined
technologies are called as disruptive by Clayton M in his book “The Innovator’s
innovations. Disruptive innovation creates Dilemma”.
a new market. Not all innovations are near Example: Film cameras market is disrupted
disruptive. The first automobiles in the late by digital camera innovations, floppy
nineteenth century were a great innovation. disk market is interrupted by CD and
But it didn’t affect existing animal-based road USB innovations. E-Commerce itself is a
transport market until 1908 when Henry disruptive innovation.
Ford introduced affordable motor cars. The

224 Chapter 15 E-COMMERCE


www.tntextbooks.org

Voice Shopping and chatbots


The future navigational experience vice shopping these devices place order
is less text-based but more conversation- to e-shopping websites. In the other end
based in order to find any information. chatbots interact with consumers and take
Humans can speak 150 words per minute the orders. The Artificial Intelligence,
but can type only 40 words. Voice machine learning and big data technology
activated speakers like google home / allows consumers interact with chatbots
alexa are capable of doing much more instead a customer relation officer to buy a
than just playing favorites songs. Through things via phone.

●● Lower Transaction Cost: E-Commerce ●● Low cost of entry: Though E-Commerce


reduces the cost of business was first emerged in private networks
transactions substantially. For instance, it did not remain the same. Internet has
significant number of customer changed the face of E-Commerce. The
service representatives in a bank can Internet is all about democratization.
be reduced by using net banking. Internet is a place where the small guy
Since these interactions are initiated can effectively fight against the giants and
by customers, the customers provide hope to win. Days when E-Commerce
a lot of data for the transactions that was only for affordable large national
may otherwise need to be entered by chains are gone. Today, it is common for
employees. This means that some retailers to move their traditional store
of the work and costs are effectively to online with very less add-on only for
shifted to customers; this is referred as building a good website.
‘customer outsourcing’. ●● Computer platform-independent:
●● 24X7 working: A website is open all 24 Most computers have the ability
hours, 7 days in a week. As E-Commerce to communicate via the Internet,
firm can provide information about irrespective of operating systems and
its products and services to customers hardware. Consumers need not have
around the clock, it can thus, take orders, to upgrade their computer or network
keep an eye on delivery of goods and to participate in E-Commerce. They
receive payments at any time. are not limited by existing hardware

Chapter 15 E-COMMERCE 225


www.tntextbooks.org

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.

or software. Also the E-Commerce Limitations of E-Commerce


company need not worry about Every rose has its thorns. Similarly,
fast changes in computer network E-Commerce also has some limitations.
technology. E-Commerce applications The following are the major drawbacks of
can be more efficiently developed and E-Commerce for a business organisation.
distributed because they are platform
●● People won’t buy all products online:
independent. Internet’s altruism helps
There are certain products like high price
E-Commerce.
jewels, clothes or furnishings which
●● Snapping middleman: E-Commerce people might not like to buy online. They
enjoys the benefit of bypassing might want to, inspect it, feel the texture
middlemen and reaching the end of the fabric etc. which are not possible
customer directly through Internet. in E-Commerce. As the online shopping
In B2C E-Commerce business does not allow physical inspection,
firms establish a direct contact customers have to rely on electronic
with their customers by eliminating images of the products. E-Commerce
middlemen. It helps to increase the is an effective means for buying known
sales of the organization without any and established services, that is, things
interventions. This results in cheaper that are being used every day. Example
price for consumers and higher profit booking tickets, buying books, music
margins for the companies.
226 Chapter 15 E-COMMERCE
www.tntextbooks.org

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.

For a successful implementation of E-Commerce, an organization must requires the well-


designed website, adequate computer hardware and software, effective telecommunication
system, technically qualified and responsive workforce and business service infrastructure

Chapter 15 E-COMMERCE 227


www.tntextbooks.org

Steps to Start an E- Business


The following are the initial steps involved in the process to start an online business
and start selling items instantly:

●● Business structure and Registration


Operating an E-Commerce or E-Business does not exclude from requiring certain
business licenses and permits. The company must be registered before starting
the trade. Registration includes business name, trade name, type of company.
(e.g., Private Ltd, Public Ltd, Partnership or Sole Proprietor, LLP - limited liability
partnership etc.) The company must be registered to get the bank account opened
in the company name and obtaining GST registration documents easily. Any one is
allowed to enroll in an online platform and start selling immediately, but there will
be no limited liability protection provided to litigation. Thus, if one need to sustain
and grow it is best to start with an LLP or a company. http://www.mca.gov.in/

Home page of Ministry of Corporate Affairs to register a Business organization online

228 Chapter 15 E-COMMERCE


www.tntextbooks.org

●● Tax Registration section. Logistics is a major part of


Taxation is unavoidable in any country. the E-Commerce. Third party logistics
A company must have registered with companies may help us to deliver sold
tax department of the concerned products to the customers at their
nation. In India registration with GST mentioned destination.
and other tax norms is a necessary to ●● Identifying suppliers
begin selling online, it does not matter Global market space comes along with
whether we are starting our own online competition in selling products online.
business website or selling on a others’ so finding the best quality and best prices
portal. https://services.gst.gov.in, for the products we sell is very important.
https://ctd.tn.gov.in/home We should shop around until we find a
supplier we find a suitable supplier.
●● Business Bank Account
●● Marketing
Bank account facilitate payment
systems. Once the company or LLP is Marketing plays a significant role in
registered successfully, the next step is any business. Using Internet and social
to apply for a bank account in the name media effectively will take out product
of the online venture. GST certificate is worldwide. Marketing could be started as
necessary to open a bank account for a early as it could be. Catchy captions and
business firm. logos attract more new customers. It’s a
good idea to set up social media profiles
●● Payment Gateway and writing content for blogs from very
The next important step is to implement first day because we do not want to wait
a payment gateways integrated with when it is ready to serve.
E-Commerce website to allow customers
●● Right technologies
make their payments through credit
card, debit card, Internet banking, Updating our technical knowledge will
etc. With digital payment gateway, the give hand in E-Commerce. Technology
customers can make the payment online makes so much of our work easier. So
which automatically gets transferred to before we start our E-Commerce business,
business’s bank account. we should be familiar with some of the
basic entities like customer relationship
●● Shipment Solution management, accounting, project
Once the above steps are accomplished management, email and marketing etc.
and start receiving the order, the The deeper we learn, the greater we grow..
next step is to set up the logistics

Chapter 15 E-COMMERCE 229


www.tntextbooks.org

points to remember

●● E-Commerce can be described as the process of buying or selling products, services or


information via Internet.
●● FinTech Financial technology is a collective term for technologically advanced financial
innovations. In simple words Fintech is a new finance industry that uses technology to
improve financial activity.
●● The dotcom bubble was a rapid rise in U.S. equity market of Internet-based companies
during 1990s.
●● Web 1.0 (Web of Content) is the early web that contained text, images and hyperlinks
and allowed users only to search for information and read it. There was a very little in
the way of user interaction or content generation.
●● Web 2.0 (Web of Communication) is a read-write web that allowed users to interact
with each other.
●● Web 3.0 (Web of Context) is termed as the semantic web or executable web with
dynamic applications, interactive services, and “machine-to-machine” interaction.

Affiliate Business who promotes the products of another business for a commission.

Blog An online platform for writing articles about a topic.

Brick and mortar The term that refers to a business that has a physical store; opposite of
online store.

Dotcom Common name for Internet based companies.

Mobile commerce Businesses that are conducted through the Internet using mobile phones
or other wireless hand-held devices.

Nascent stage Initial stage of growth.

Off-shoring Company’s work is given to overseas (another country) company

Out-sourcing Hiring third party service providers to handle business on behalf.

Social media In terms of E-Commerce, a platform for advertising products to targeted


consumers e.g. Facebook, twitter.

Tangible form Physical goods we receive.

Teleputer Fusion of television, computer and telecom networking technologies.

Wordpress A free, open source online blogging platform.

230 Chapter 15 E-COMMERCE


www.tntextbooks.org

EVALUATION

Part I c) The Third Wave of Electronic


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

10. Which of the following is not a characteristics of E-Commerce


a) Products cannot be inspected physically before purchase.

b) Goods are delivered instantly.
c) Resource focus supply side
d) Scope of business is global.

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

●● Draw a timeline describing various developments in E-Commerce.


●● List the business around your society and sort it according to business modules.
●● Interview a consumer who recently bought a product online and write his experience.

232 Chapter 15 E-COMMERCE


www.tntextbooks.org

16
CHAPTER

Electronic Payment Systems

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

a receiver. Sometimes it is also called 16.2 Classification of


liquidation, clearing system or clearing Electronic Payment
service. It ensures the transfer of value methods
from one subject of the economy to
Many electronic payment methods have
another and plays an important role in
been developed with the advancements
modern monetary systems.
in the Internet technologies. Based on the
Modern payment systems may value of money transactions, processing
be physical or electronic and each has time, processing requirements, security
its own procedures and protocols that issues and usability electronic Payment
guide the financial institution with systems are generally classified into two
payment mechanisms and legal systems. types. They are
Standardization has allowed some of these
●● Micro electronic Payment Systems
systems to grow to globally.
●● Macro electronic Payment Systems
The term electronic payment refers to a
payment made from one bank account 16.2.1 Micro electronic Payment
to another bank account using electronic Systems
methods forgoing the direct intervention It is an on-line payment system
of bank employees. designed to allow efficient and frequent
payments of small amounts. In order
Payment system is an essential to keep transaction costs very low, the
part of a company’s financial operations. communication and computational
But it becomes complex, when many costs are minimized here. Unlike macro
different payment systems are used. electronic payments, which use expensive
Further challenges come from the public key cryptography, micro electronic
continuous introduction of newer payment are relaxed by using light weight
payment systems such as paytm, UPI, cryptographic primitives and off-line
bitcoin and various mobile payment payment verifications.
options. As a result there are more than As the security of micro electronic
750 payment systems throughout the payment systems is comparatively low it
world. See Figure 16.1 could be tampered but, the cost of fraud
is much higher than the possible value to
be gained by fraud itself. So the security
in micro electronic payment methods is
considered to be adequate. The majority
Payment
of micro electronic payment systems were
method designed to pay for simple goods on the
Internet. e.g., subscriptions of online
games, read journals, listen to a song or
watch a movie online etc.

Figure 16.1 Electronic Payment Systems


234 Chapter 16 Electronic Payment Systems
www.tntextbooks.org

In general, the parties involved in prevent these payment systems to be used


the micro on-line payments are Customer, for the payment of small amounts. Some
Service Provider and Payment processor. of the popular macro on-line payment
The Micro electronic payment transactions systems are mentioned below
can be explained in the following way. ●● Card based payment systems

Step 1 Customer proves his authentication ●● Electronic account transfer



and the payment processor issues ●● Electronic cash payment systems

micro payments. ●● Mobile payment systems and internet

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

Chapter 16 Electronic Payment Systems 235


www.tntextbooks.org

has a purchase limit set by the issuing Advantages of credit card


bank or the firm. A credit card is different ●● Most credit cards are accepted
from a debit card where the credit card worldwide.
issuer lends money to customer instead ●● It is not necessary to pay physical
of deducting it from customer’s bank money at the time of purchase. The
account instantly. customer gets an extra period to pay
The term credit card was first the purchase.
mentioned in 1887 in the sci-fi novel ●● Depending on the card, there is no
“Looking Backward” by Edward Bellamy. need to pay annuity.
The modern credit cards concept was ●● Allows purchases over the Internet in
born in the U.S.A, in the 1920s, when installments.
private companies began to issue cards to
●● Some issuers allows “round up” the
enable their customers to purchase goods
purchase price and pay the difference
on credit within their own premises.
in cash to make the transactions easy.
In February 1950, Frank
McNamara and Ralph Schneider Key players in
created The Diners Club card operations of credit card
which was made of paper-cardboard. 1. Bearer: The holder of the credit
Initially The card was accepted in only 27 card account who is responsible
restaurants and was used only by friends for payment of invoices in full
and acquaintances of the two founders
(transactor) or a portion of the
(approximately 200 people). Later it was
enhanced and accepted worldwide. From
balance (revolver) the rest accrues
1955, the card was made of plastic. The interest and carried forward.
Diners Club still exists today under the 2. Merchant: Storekeeper or vendor
name Diners Club International. who sell or providing service,
receiving payment made by its
customers through the credit card.
3. Acquirer: Merchant’s bank that is
responsible for receiving payment on
behalf of merchant send authorization
requests to the issuing bank through
the appropriate channels.
4. Credit Card Network: It acts as the
intermediate between the banks.
The Company responsible for
communicating the transaction
between the acquirer and the credit
card issuer. These entities operate
the networks that process credit
card payments worldwide and
levy interchange fees. E.g. Visa,
236 Chapter 16 Electronic Payment Systems MasterCard, Rupay
www.tntextbooks.org

Figure 16.2 Key players of Credit card transaction

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

Figure 16.3 Credit Card

Chapter 16 Electronic Payment Systems 237


www.tntextbooks.org

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

238 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

16.3.3 Stored value cards in the form of binary-coded data.


Stored value card is a type of debit card that Closed loop cards are issued by
is pre-loaded with certain amount(value), a specific merchant or merchant
with which a payment is made. It is a card group and can only be used to make
that has default monetary value onto it. purchases from specific place. e.g.
The card may be disposed when the value chennai metro rail travel card.
is used, or recharged to use it again. The 2. Open loop (multipurpose)
major advantage of stored value card is that Open loop cards can be used to make
customers don’t need to have a bank account debit transaction at variety of retailers.
to get prepaid cards. See Figure 16.4 It is also called as prepaid-debit cards.
It can be used anywhere the branded
cards are accepted. e.g. Visa gift cards.

In some countries it is legal for


anyone to enter or leave the
country with money that is stored
on cards, unlike carrying cash in high
amounts which is believed a form of
money laundering.

16.3.4 Smart card


The modern version of card based
payment is smart cards. Smart cards
Figure 16.4 Stored value card along with the regular features of any
Like a credit card or debit card it card based payment system holds a EMV
is a plastic and has a magnetic strip on chip. This chip is similar to well-known
its back. The magnetic strip stores the sim card in appearance but differ in its
monetary value of the card. Stored value functionalities. The advantage of Smart
cards may not have the card holder’s name cards is that it can provide identification,
always. It is also indistinguishable from a
regular credit or debit card in appearance.
What look like a credit card or debit card
act like a credit or debit card. It is used to
make purchases offline and online in the
same way as in credit card or debit card.
There are two varieties for stored
value card.
1. Closed loop (single purpose)
In closed loop cards, money is
metaphorically stored on the card Figure 16.5 Contact Smart card & POS

Chapter 16 Electronic Payment Systems 239


www.tntextbooks.org

authentication, data storage and application 16.4 Electronic Account


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.

2. Contactless smart cards 16. 4.1 Electronic Clearing


Contactless smart card is empowered Services (ECS)
by RF induction technology. Unlike Electronic Clearing Service can be
contact smart cards, these cards defined as repeated transfer of funds
require only near proximity to an from one bank account to multiple bank
antenna to communicate. Smart accounts or vice versa using computer and
cards, whether they are contact or Internet technology. The payer instructs
contactless cards do not have an the bank to debit from his bank account
internal power source. Instead, they and credit it to one or more payee bank
use an inductor to capture some of account provided amounts and dates
the interrupting radio-frequency of the payments earlier. This system
signal, rectify it and power the card’s provides the convenience of paperless
processes. See Figure 16.6 payments.

Figure 16.6 Contactless smart card

240 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

Figure 16.7 ECS

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

Chapter 16 Electronic Payment Systems 241


www.tntextbooks.org

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

The function of cryptocurrency is by an unknown person or a group under


based on technologies such as Mining, the pseudonym “SatosiNakamoto”. The
Blockchain, Directed Acyclic Graph, SHA-256, a cryptographic hash function,
Distributed register (ledger), etc. The has been used as a working algorithm.
information about the transaction is Later forks like: Namecoin, Litecoin,
usually not encrypted and is available in Bitcoin-gold and many others appeared.
clear text. See Figure 16.8

In 1989, David Chaum an Bitcoin is the most popular


American cryptographer invented cryptocurrency, but there are many other
the first form of Cryptocurrency cryptocurrencies, which are referred to
called “DigiCash” in the Netherlands. as “altcoins”. Currently, more than 1300
David Chaum, was offered with 180 cryptocurrencies are listed over 200
million dollars by Microsoft for his special cryptocurrency stock exchanges.
DigiCash. But things changed and his
Most (not all) are based on different types
company went bankrupt in 1998.
of blockchain technology.
Many cryptocurrencies operate
on the basis of the same source code, in
which the authors make only a few minor
changes in parameters like time, date,
distribution of blocks, number of coins,
etc. These currencies are called as fork.
In fork, both cryptocurrencies can share a
common transaction history in blockchain
Bitcoin until the split.
The term “cryptocurrency” began to be
used after the appearance of the Bitcoin. Altcoins
Bitcoin is the most popular and the first Altcoins is the collective name for all
decentralized cryptocurrency. Bitcoin cryptocurrencies that appeared after
payment system, was developed in 2009 Bitcoin. The early Altcoins Litecoin
and Namecoin appeared in 2011. Their
miners sought to overcome a number of
problems inherent in Bitcoin (for example,
Litecoin has a higher transaction rate)
or use blockchain technology in other
areas (Namecoin was developed to build
alternative root DNS servers).
Many altcoins are inherently very
similar to Bitcoin in characteristics and
Figure 16.8 symbol of Bitcoin structure. But some cryptocurrencies

Chapter 16 Electronic Payment Systems 243


www.tntextbooks.org

have significant differences. About 400


The process of mining is extremely
altcoins were considered as “dead”, as their
electrical energy consumptive. For
value became zero. example while the whole Singapore
Until July 2013, the software of all nation consumes 48.59 TWh (as of Feb
cryptocurrencies, except Ripple, was based 2019) electrical energy, the computers
on the open source code of the Bitcoin used to mine cryptocurrencies around
the world too consume approximately
system. Since July 2013, cryptocurrency
same energy. New cryptocurrencies are
platforms began to appear to support being created all the time.
various infrastructures like stock trading,
shops, instant messengers, and so on.
These cryptoplatforms includes BitShares,
Mastercoin, Nxt.
From 2014, the 2nd generation of
cryptocurrency appeared, such as Monero,
Ethereum and Nxt. These crypto-coins
have advanced features such as hidden
addresses and smart contracts.
In terms of trade, the creation of
Mining
cryptocurrencies may be related to the
The cryptocurrency units are created ICO (Initial Coin Offer) procedure, i.e. the
by the solution of cryptographic tasks ICO, aimed at gathering the initial capital
called mining. The miners not only necessary for the further development
generate new monetary units, but of the system. The initial value of
also initiate new transactions to the cryptographic currency is just the cost
blockchain. As a reward, they will of consumed electricity. The secondary
receive new Bitcoins. value is determined by the demand for the
cryptocurrency.

Buyer Seller
Block Crypto-Hashing Distributed databases
(transaction)

Transaction is distributed Transaction is commited Seller received the


Buyer creates a
and validated via to blockchain and miners transaction
transaction or a block
cryptographic hashing are rewarded

Figure 16.9 Blockchain

244 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

Blockchain wallets turned out as an efficient


Blockchains are an open distributed transaction tool. This is evidenced by
book that records transactions of the many E-Commerce websites that
cryptocurrencies between any two use electronic wallets as a transaction
parties in an efficient and verifiable tool. There are several electronic wallet
manner. It is a continuously growing services that are now widely used. e.g.
list of records, called blocks, which :PayPal, SBI Buddy. See Figure 16.10
are linked to each other and protected
using encryption algorithm. Each block
typically contains a hash pointer as a
link to a previous block. It records data
about every transaction with its date
and time. Once recorded, the data in any
given block cannot be altered without
the alteration of all subsequent blocks.
Blockchains are by default resistant to
data modification without the approval
of a trusted authority. The validity of
the coins of each cryptocurrency is also
provided by a blockchain. See Figure 16.9
Figure 16.10 e-wallets
Since blockchains are safely
designed with high fault tolerance it is best
suited to distributed computing system. 16.6 Mobile Banking and

Decentralized structure of blockchain Internet Banking
solves the problem of double spending. As smartphones have already usurped
the place of digital camera and voice
16.5.2 Electronic wallets
recorders, soon it will double up as virtual
Electronic wallets (e-wallets) or electronic debit cards. It enables to send or receive
purses allow users to make electronic money instantly without any plastic cards.
transactions quickly and securely over
the Internet through smartphones or 16.6.1 Mobile Banking
computers. The electronic wallet functions
Mobile banking is another form of net
almost the same as a physical wallet in term
banking. The term mobile banking (also called
that it holds our money. Electronic wallets
m-banking) refers to the services provided by
were first recognized as a method for storing
the bank to the customer to conduct banking
money in electronic form, and became
transactions with the aid of mobile phones.
popular because it provides a convenient
These transactions include balance checking,
way for online shopping.
account transfers, payments, purchases, etc.
With the development of Transactions can be done at anytime and
advanced Internet, the use of electronic anywhere. See Figure 16.11

Chapter 16 Electronic Payment Systems 245


www.tntextbooks.org

Figure 16.11 mobile banking through smartphone application

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

246 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

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.

Figure 16.12 Home page of SBI Internet banking

Chapter 16 Electronic Payment Systems 247


www.tntextbooks.org

Virtual payment address (VPA) also


Indian Financial System Code
called as UPI-ID, is a unique ID similar to
(IFSC) is an 11 digit alpha-numeric
code issued by Reserve Bank of
email id (e.g. name@bankname) enable us
India to uniquely identify individual to send and receive money from multiple
bank’s branch in India. It is used for banks and prepaid payment issuers. Bank
domestic e-payments. SWIFT code is or the financial institution allows the
used for international bank transactions. customer to generate VPA using phone
number associated with Aadhaar number
and bank account number. VPA replaces
16.7 Unified Payments bank account details thereby completely
Interface hides critical information.
Unified Payments Interface (UPI) is a The MPIN (Mobile banking
real-time payment system developed Personal Identification number) is
by National Payments Corporation of required to confirm each payment. UPI
India (NCPI) to facilitate inter-bank allows operating multiple bank accounts
transactions. It is simple, secure and in a single mobile application. Some
instant payment facility. This interface is UPI application also allows customers to
regulated by the Reserve Bank of India initiate the transaction using only Aadhaar
and used for transferring funds instantly number in absence VPA.
between two bank accounts through
mobile (platform) devices. http://www. UPI is also available as an
npci.org.in/ Unstructured Supplementary
Service Data (USSD) service.
Unlike traditional e-wallets, which
Users who don’t have Internet can dial
take a specified amount of money from
*99# and get UPI services within India.
user and store it in its own account, UPI The financial services like transferring
withdraws and deposits funds directly fund, payment request and non-financial
from the bank account whenever a services like changing MPIN and balance
transaction is requested. It also provides check are currently available through the
the “peer to peer” collect request which can USSD.
be scheduled and paid as per requirement
and convenience.
UPI is developed on the basis of
Immediate Payment Service (IMPS). To
initiate a transaction, UPI applications
use two types of address - global and local.
●● Global address includes bank account
numbers and IFSC.
●● Local address is a virtual payment
address.

248 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

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.

Chapter 16 Electronic Payment Systems 249


www.tntextbooks.org

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

250 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

EVALUATION

Part - I 5. ECS stands for


Choose the correct answer a) Electronic Clearing Services
1. Based on the monetary value e b) Electronic Cloning Services
payment system can be classified into c) Electronic Clearing Station
a) Mirco and Macro d) Electronic Cloning Station
b) Micro and Nano 6. Which of the following is not a
c) Maximum and Minimum Altcoin
d) Maximum and Macro a) Litecoin b) Namecoin
2. Which of the following is not a c) Ethereum d) Bitcoin
category of micropayment? 7. Which of the following is true about
a) Buying a movie ticket Virtual payment address (VPA)
b) Subscription to e journals a) Customers can use their e-mail

c) Buying a laptop id as VPA
d) Paying for smartphone app b) VPA does not includes numbers
3. Assertion (A): Micro electronic c) VPA is a unique ID
payment systems support higher d) Multiple bank accounts cannot

value payments. have single VPA
Reason (R): Expensive cryptographic 8. Pick the odd one in the credit card
operations are included in macro transaction
payments a) card holder
a) Both (A) and (R) are correct and b) merchant

(R) is the correct explanation of c) marketing manager
(A) d) acquirer
b) Both (A) and (R) are correct, but 9. Which of the following is true about

(R) is not the correct explanation debit card
of (A) i. debit cards cannot be used in ATMs

c) (A) is true and (R) is false ii. debit cards cannot be used in

d) (A) is false and (R) is true online transactions
4. Which of the following is correctly iii. debit cards do not need bank

matched accounts
a) Credit Cards - pay before iv. debit cards and credit cards are

b) Debit Cards - pay now identical in physical properties
c) Stored Value Card - pay later a) i, ii, iii b) ii, iii, iv
d) Smart card – pay anytime c) iii alone d) iv alone

Chapter 16 Electronic Payment Systems 251


www.tntextbooks.org

10. Match the following Part - III


List A List B Explain in Brief Answer
A1) First Digit B1) Account 1. Define micro electronic payment
and its role in E-Commerce.

 
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

Presentation about various payment systems


●● Choose any presentation tool (e.g. Open office impress)
●● Create a slide describing a payment method.
●● List the futures of the particular payment method.
●● List the advantages and disadvantages of the same.
●● Repeat the steps for other payment methods.

252 Chapter 16 Electronic Payment Systems


www.tntextbooks.org

17
CHAPTER

E-Commerce Security Systems

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

17.1 E-Commerce Security E-Commerce security is a set of protocols


With the rapid development of the that safely guide E-Commerce transactions
Internet, online transactions have through the Internet.
increasingly become a new business
model. E-Commerce transactions 17.2 Types of E-Commerce

based on network resources have been Threats
accepted by the public. While enjoying Since E-Commerce is based on information
the convenience brought by online technology and computer networks, it
transactions, the security of transactions inevitably faces a series of security issues
has attracted much attention. The compared with traditional businesses.
inherent openness and resource sharing E-Commerce security threats can be accidental
of the network have seriously threatened (caused by a human error) or intentional.
the security of online transactions. To an
Foreign or domestic, internal or
E-Business security threats not only result
external, group or individual, business
in loss of revenue but also in reputation.
rivals or disgruntled employees, terrorists
Definition or hackers anyone with the capability,
technology, opportunity, and intent to
Security has become the critical factor and
do harm can be a potential threat to
core issue in any emerging E-business.
E-Commerce. Though every business has
Solving the security problems in
pitfalls E-Commerce business would face
transactions is the basis for ensuring the
the following specific threats.
smooth development of E-business.

253
www.tntextbooks.org

2. Tampering: E-Commerce has the


Viruses cause harm to the
problem of the authenticity and
computers thereby harms the
efficient and smooth functioning
integrity of business information.
of E-Commerce. Some viruses destroy all When hackers grasp the data
the information stored in a computer and transmitted on the network, it can be
cause huge loss of revenue and time. The falsified in the middle through various
emergence of computer viruses and their technical means, and then sent to the
variants has rapidly increased over the destination, thereby destroying the
past decade. The Internet has turned to be authenticity and integrity of the data.
the best medium for the spread of viruses.
Many new viruses directly use the Internet 3. Payment frauds: Payment frauds have
as their mode of transmission causing subsets like Friendly fraud (when
huge economic losses to E-businesses. customer demands false reclaim or
refund), Clean fraud (when a stolen
1. Information leakage: The leakage credit card is used to make a purchase)
of trade secrets in E-Commerce Triangulation fraud (fake online shops
mainly includes two aspects: (a) the offering cheapest price and collect
content of the transaction between credit card data) etc.
the vendor and customer is stolen by 4. Malicious code threats: Within an
the third party; (b) the documents E-Commerce site, there are multiple
provided by the merchant to the vulnerable areas that can serve as an
customer or vice versa are illegally intrusion point for a hacker to gain
used by the another. This intercepting payment and user information. Using
and stealing of online documents is malware, Cross Site Scripting or SQL
called information leakage. Injection, an attacker will extract the
credit card information and sell the
acquired data on black markets. Fraud
Phishing is also a E-Commerce
threat in which a target is contacted is then committed to extract the greatest
by e-mail, telephone or text value possible through E-Commerce
message by someone who pretend himself transactions or ATM withdrawals, etc.
as a genuine authority. They try to trap 5. Distributed Denial of Service
individuals to provide sensitive data such (DDoS) Attacks: It is a process of
as, banking and credit card details, OTP,
taking down an E-Commerce site by
PIN or passwords. Once they succeed, the
results would lead to devastating acts such sending continious overwhelming
as identity theft and financial loss. request to its server. This attack
will be conducted from numerous
unidentified computers using botnet.
This attack will slow down and make
the server inoperative. DDoS attacks
is also called as network flooding.
6. Cyber Squatting: Cybersquatting is the
illegal practice of registering an Internet

254 Chapter 17 E-Commerce Security Systems


www.tntextbooks.org

domain name that might be wanted of E-Commerce activities has become


by another person in an intention to the core research field of E-Commerce.
sell it later for a profit. It involves the The following are some of the security
registering of popular trademarks and elements involved in E-Commerce.
trade names as domain names before ●● Authenticity: conforming genuineness
the particular company do. Cyber of data shared.
squatters also involve in trading on
the reputation and goodwill of such ●● Availability: prevention against data
third parties by inducing a customer to delay or removal.
believe that it is an official web page. ●● Completeness: unification of all
business information.
In September 2015, the domain
●● Confidentiality: protecting data
google.com was bought for 12
against unauthorized disclosure.
American dollars by a former
Google employee which he later sold it ●● Effectiveness: effective handling of
for 6006.13 American dollars. hardware, software and data.
●● Integrity: prevention of the data being
7. Typopiracy: Typopiracy is a variant of
unaltered or modified.
Cyber Squatting. Some fake websites
try to take advantage of users’ common ●● Non-repudiation: prevention against
typographical errors in typing a website violation agreement after the deal.
address and direct users to a different ●● Privacy: prevention of customers’
website. Such people try to take personal data being used by others.
advantage of some popular websites ●● Reliability: providing a reliable
to generate accidental traffic for identification of the individuals or
their websites. e.g. www.goggle.com, businesses.
www.faceblook.com
●● Review ability: capability of monitoring
Hacking refers to unauthorized activities to audit and track the
intrusion into a computer or a operations.
network. That is to say breaking
security to gain access to a website
illegally and intercept confidential 
R ansomware: Ransomware is
information. They would then misuse a type of malware that usually
such information to their advantage or encrypt all the files in a target’s
modify and even destroy its contents to computer and threatens to publish
harm the competitors. the critical data unless a ransom
(money) is paid.

17.3 Dimensions of

E-Commerce security
As the security issue is the most worrying
issue for E-Business, ensuring the security

Chapter 17 E-Commerce Security Systems 255


www.tntextbooks.org

17.4 Security technologies Symmetric key encryption


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.

SAMPLE ENCRYPTION AND DECRYPTION PROCESS

SSN: SSN:
783-43-1616 Bc9Yzwoga
Encryption + XBzdWogZG
9sb3lgc2I0IG
FtZXQNCg...

Plain text Algorithm Cipher text

SSN: SSN:
Bc9Yzwoga 783-43-1616

Decryption
XBzdWogZG
9sb3lgc2I0IG
+
FtZXQNCg...

Cipher text Algorithm Plain text

Figure 17.1 Data Encryption and Decryption process

256 Chapter 17 E-Commerce Security Systems


www.tntextbooks.org

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.

Symmetric Key Encryption Asymmetric Key Encryption


Same key is used for both encryption and Different keys are used for encryption and
decryption decryption

Speed of encryption or decryption is very Speed of encryption or decryption is


fast comparatively slow

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

Provides confidentiality Provides confidentiality, authenticity and


non-repudiation

The number of key used grows The number of key used grows linearly with
exponentially with the number of users the number of users

Chapter 17 E-Commerce Security Systems 257


www.tntextbooks.org

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 certificates because he trusts that CA has done their


A digital certificate (also known as part verifying the sender’s identity.
public key certificate) is an electronic
document used to prove the ownership of
a public key. This certificate includes the
information about the sender’s identity,
digital signature and a public key.
Digital certificates function is
similar to the functions of identification
cards such as passports and driving
licenses. Digital certificates are issued
by recognized Certification Authorities
(CA). When someone requests a digital
certificate, the authority verifies the
identity of the requester, and if the
requester fulfills all requirements, the
authority issues it. When the sender uses
a certificate to sign a document digitally,
receiver can trust the digital signature
Figure 17.2 Digital Certificates
258 Chapter 17 E-Commerce Security Systems
www.tntextbooks.org

Common digital certificate systems are responsibility, it is easier to implant in


X.509 and PGP. the law, X.509 is currently world wide
●● Pretty Good Privacy (PGP): Phil accepted certification technology.
Zimmermann developed PGP in
1991. It is a decentralized encryption The digital certificate are being
program that provides cryptographic issued by a licensed Certifying
Authority (CA). NIC, Safescript,
privacy and authentication for data
TCS, MTNL, e-Mudhra are some of the
communication. PGP encryption
authorized Certifying Authorities under
uses a serial combination of hashing, Government of India.
data compression, symmetric-key
cryptography and asymmetric-key Digital signature
cryptography and works on the concept
of “web of trust”. A digital signature is a mechanism that
is used to verify that a particular digital
●● The X.509 system is a centralized document, message or transaction is
system in which the authenticity of authentic.
the key is guaranteed by the hierarchy
of certification authorities formally It provides a receiver the guarantee
certifying the key relationship with the that the message was actually generated
identity of its owner. Due to its clear by the sender. It also confirms that the

Digital signature Digital certificate


A digital signature is a mechanism that is used to A digital certificate is a computer file which officially
verify that a particular digital document, message or approves the relation between the holder of the
transaction is authentic. certificate and a particular public key.

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

Chapter 17 E-Commerce Security Systems 259


www.tntextbooks.org

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

Figure 17.3 Difference between http and https

Secure Sockets Layers Today, all browsers in the market


The most common Cryptographic support SSL, and most of the secure
protocol is Secure Sockets Layers (SSL). communications are proceeded through this
SSL is a hybrid encryption protocol for protocol. SSL works completely hidden for
securing transactions over the Internet. the user, who does not have to intervene in
The SSL standard was developed the protocol. The only thing the user has to
by Netscape in collaboration with do is make sure the URL starts with https://
MasterCard, Bank of America, MCI and instead of http:// where the “s” obviously
Silicon Graphics. It is based on a public means secured. It is also preceded by a
key cryptography process to ensure green padlock.
the security of data transmission over
the internet. Its principle is to establish 3D Secure
a secure communication channel “3-D Secure is a secure payment protocol
(encrypted) between a client and a server on the Internet. It was developed by Visa to
after an authentication step. increase the level of transaction security,
The SSL system acts as an additional and it has been adapted by MasterCard. It
layer, to ensure the security of data, gives a better authentication of the holder
located between the application layer and of the payment card, during purchases
the transport layer in TCP. For example, a made on websites. The basic concept
user using an internet browser to connect of this (XML-based) protocol is to link
to an SSL secured E-Commerce site will the financial authorization process with
send encrypted data without any more an online authentication system. This
necessary manipulations. Secure Sockets authentication model comprise 3 domains
Layers (SSL) was renamed as Transport (hence the name 3D) which are:
Layer Security (TLS) in 2001. But still it 1. The Acquirer Domain
is popularly known under the name SSL. 2. The Issuer Domain
TLS differs from SSL in the generation of
symmetric keys. 3. The interoperability Domain

Chapter 17 E-Commerce Security Systems 261


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

262 Chapter 17 E-Commerce Security Systems


www.tntextbooks.org

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.

Chapter 17 E-Commerce Security Systems 263


www.tntextbooks.org

EVALUATION

Part - I 5. PGP stands for


Choose the correct answer a) Pretty Good Privacy
1. In E-Commerce, when a stolen credit b) Pretty Good Person
card is used to make a purchase it is c) Private Good Privacy
termed as
d) Private Good Person
a) Friendly fraud
6. _____ protocol is used for securing
b) Clean fraud
credit cards transactions via the
c) Triangulation fraud Internet
d) Cyber squatting a) Secure Electronic Transaction


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

264 Chapter 17 E-Commerce Security Systems


www.tntextbooks.org

10. Which of the following is true about Ransomware


a) Ransomware is not a subset of malware

b) Ransomware deletes the file instantly

c) Typopiracy is a form of ransomware

d) Hackers demand ransom from the victim

Part - II
Short Answers
1. Write about information leakage in E-Commerce.
2. Write a short note on typopiracy.
3. Define non-repudiation.
4. List the different types of security technologies in E-Commerce
5. Write about digital signature.

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

Identifying the security protocols used in the particular payment gateway.


●● Create a chart for a payment process.
●● Describe the security technology used in that payment method.
●● Repeat the process for few other payment process.

Chapter 17 E-Commerce Security Systems 265


www.tntextbooks.org

18
CHAPTER

Electronic Data Interchange- EDI

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

18.1 Introduction to EDI and avoiding many errors of traditional


“on paper” communications.
The Electronic Data Interchange (EDI)
is the exchange of business documents Before the popularization of
between one trade partner and another Internet-based E-Commerce, it was a
electronically. It is transferred through a major E-Commerce model. EDI includes
dedicated channel or through the Internet data exchange between buyers and
in a predefined format without much sellers, trade partners, and also internal
human intervention. data exchange within departments of a
company. There are many internationally
It is used to transfer documents
accepted EDI standard e.g. EDIFACT,
such as delivery notes, invoices, purchase
XML, ANSI ASC X12, etc. See Figure 18.1
orders, advance ship notice, functional
acknowledgements etc. These documents
EDI is “Paperless Trade” and EFT
are transferred directly from the computer
(Electronic Transfer) is “Paperless
of the issuing company to that of the
Payment”
receiving company, with great time saving

Figure: 18.1 Electronic Document Exchange


266
www.tntextbooks.org

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.

transmitted electronically by the use of


Like many other early information
Radio teletype, telex messages, or telephone.
technologies, EDI was also inspired
by developments in Defense In late 1960s, shipping line,
Research Organization. Ed Guilbert, is railroads, airlines, and truck companies of
called as the father of EDI. He manifested USA were exchanging electronic messages
shipping standardized format (much like for their businesses. These messages
the 856, or ASN) during the 1948 Berlin were in different formats, and it resulted
airlift. Guilbert with his team developed problems in transfer of goods. In 1968,
the first standardized system for business these companies grouped together among
documents, that later influenced how themselves and formed the Transportation
documents would be passed from computer Data Coordinating Committee (TDCC)
to computer. This standard helped to track to develop EDI standard formats.
“what was contained in the shipment”, In 1975, first EDI standards were
“who was delivering the cargo”, while not released by TDCC, of which Ed Guilbert
allowing language barriers or confusing was a major contributor. In 1977, a
formats to delay the shipment. group of supermarket companies and
their business partners begin drafting
and using an EDI project. The TDCC is
renamed as Electronic Data Interchange
Association (EDIA) in 1978. Later in that
year, the EDIA was undertaken by the
American National Standards Institute
and becomes the ANSIX12 committee.
Soon, businesses began to realize Since then this committee is responsible
using the EDI will smoothen the business for the publication of EDI standards.
transactions and increase the profit. These Later in 1985, UN created the
standardizations made ordering and EDIFACT to assist with the global reach
shipping faster, more organized, and less of technology in E-Commerce. EDIFACT
expensive. Earlier, EDI documents were is the most widely used EDI.

Chapter 18 Electronic Data Interchange- EDI 267


www.tntextbooks.org

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.

Figure: 18.2 EDI via VAN

268 Chapter 18 Electronic Data Interchange- EDI


www.tntextbooks.org

EDI via FTP/VPN, SFTP, FTPS ●● Providing information on process status


When protocols like FTP/VPN, SFTP ●● Optimizing financial ratios
and FTPS are used for exchange of EDI
based documents through the Internet or 18.4 EDI Layers
Intranet it is called as EDI via FTP/VPN, Electronic data interchange architecture
SFTP, FTPS. specifies four different layers namely
Web EDI 1. Semantic layer
Web based EDI conducts EDI using an 2. Standards translation layer
web browser via the Internet. Here the 3. Transport layer
businesses are allowed to use any browser 4. Physical layer
to transfer data to their business partners.
Web based EDI is easy and convenient for These EDI layers describes how data
small and medium organizations. flows from one computer to another. See
Figure 18.3
Mobile EDI EDI semantie
Application level services
layer
When smartphones or other such
EDIFACT business form standards
handheld devices are used to transfer EDI standard
layer
EDI documents it is called as mobile EDI. ANSI X 12 business form standards

Mobile EDI applications considerably Electronic mail X.435, MIME


increase the speed of EDI transactions. EDI transport
Point to point FTP. TELNET
layer
World Wide Web HTTP
18.3 Advantages of EDI
Physical layer Dial-up line, internet, I-way
EDI was developed to solve the problems
inherent in paper-based transaction Figure: 18.3 EDI Layers
processing and in other forms of
electronic communication. Implementing 18.5 EDI Components
EDI system offers a company greater
There are four major components of EDI.
control over its supply chain and allow it
They are
to trade more effectively. It also increases
1. Standard document format
productivity and promotes operational
efficiency. The following are the other 2. Translator and Mapper
advantages of EDI. 3. Communication software
●● Improving service to end users 4. Communication network
●● Increasing productivity
18.6 EDI Standards
●● Minimizing errors
●● Slashing response times The standard is the most critical part
of the entire EDI. Since EDI is the data
●● Automation of operations
transmission and information exchange
●● Cutting costs
in the form of an agreed message
●● Integrating all business and trading format, it is important to develop a
partners unified EDI standard. The EDI standard
Chapter 18 Electronic Data Interchange- EDI 269
www.tntextbooks.org

is mainly divided into the following 18.7 UN/EDIFACT


aspects: basic standards, code standards,
United Nations / Electronic Data
message standards, document standards,
Interchange for Administration, Commerce
management standards, application
and Transport (UN / EDIFACT) is an
standards, communication standards and
international EDI - standard developed
security standards.
under the supervision of the United Nations.
The first industry-specific EDI In 1987, the UN / EDIFACT syntax rules
standard was the TDCC published by were approved as ISO: ISO9735 standard
the Transportation Data coordinating by the International Organization for
Committee in 1975. Then other industries Standardization. See Figure 18.4
started developing unique standards based
EDIFACT includes a set of
on their individual needs. E.g. WINS in
internationally agreed standards, catalogs
the warehousing industry.
and guidelines for electronic exchange
Since the application of EDI has of structured data between independent
become more mature, the target of trading computer systems.
operations is often not limited to a single
industry. In 1979, the American National
Standards Institute Accredited Standard
Committee (ANSI ASC) developed a wider
range of EDI standard called ANSI X12.
On the other hand, the European
region has also developed an integrated
EDI standard. Known as GTDI (Guideline
EDIFACT
for Trade Data Interchange).
ANSI X12 and GTDI have become
the two regional EDI standards in North
America and Europe respectively.
Figure: 18.4 UN/EDIFACT
After the development of the
two major regional EDI standards and It is a cross-industry, standard data
a few years after trial, the two standards format of electronic data for commercial
began to integrate and conduct research transactions. Maintenance and further
and development of common EDI development of this standard goes through the
standards. Subsequently, the United United Nations Center for Trade Facilitation
Nations Economic Commission for and Electronic Business (UN/CEFACT),
Europe (UN/ECE/WP.4) hosted the task which is affiliated to the UN Economic
of the development of international EDI Commission for Europe (UNECE).
standards. In 1986, UN/EDIFACT is
officially proposed. The most widely used EDIFACT directories

EDI message standards are the United The versions of EDIFACT are also called
Nations EDIFACT and the ANSI X12. as directories. These EDIFACT directories

270 Chapter 18 Electronic Data Interchange- EDI


www.tntextbooks.org

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

Figure 18.5 Sample EDI Application

Chapter 18 Electronic Data Interchange- EDI 271


www.tntextbooks.org

Highest Level

Piece of data between


Interchange
segments UNB/UNZ

Piece of data between


Functional Groups
segments UNG/UNE

Piece of data between


Messages
segments UNH/UNT

Segment Groups Block of related data

Mixture of simple and


Segments
composite elements

Composite
Group of related simple elements
Elements

Simple data
Piece of single data
Elements

Lowest Level

Figure: 18.6 UN/EDIFACT Message structure

272 Chapter 18 Electronic Data Interchange- EDI


www.tntextbooks.org

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

Chapter 18 Electronic Data Interchange- EDI 273


www.tntextbooks.org

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

274 Chapter 18 Electronic Data Interchange- EDI


www.tntextbooks.org

Advance ship notice A notification of pending deliveries


FTP A standard network protocol used for the transfer of computer files
between a client and server on a computer network.
Interchange The top level message of EDI hierarchical structure
Invoice A commercial document issued by a seller to a buyer containing
product name, quantity and price.
Purchase order A commercial and first official document issued by a buyer to a seller
indicating types, quantities, and agreed prices for products or services.
Segment Segments may contain one, or several related user data elements.
Separators punctuation marks that are used to separate segments or elements.
TDCC Transportation Data Communication Committee - The first industry-
specific EDI standard.
Telex A type of teleprinter
VAN Value Added Network, a third party network service provider

EVALUATION

Part - I 3. Which is the first industry-specific


Choose the correct answer EDI standard?
1. EDI stands for a) TDCC
a) Electronic Details Information b) VISA
b) Electronic Data Information c) Master
c) Electronic Data Interchange d) ANSI
d) Electronic Details Interchange
4. UNSM stands for?
2. Which of the following is an
internationally recognized standard a) Universal Natural Standard

format for trade, transportation, message
insurance, banking and customs? b) Universal Notations for Simple

a) TSLFACT message
b) SETFACT c) United Nations Standard message
c) FTPFACT d) United Nations Service message
d) EDIFACT
Chapter 18 Electronic Data Interchange- EDI 275
www.tntextbooks.org

5. Which of the following is a type of 10. Number of characters in an single


EDI? EDIFACT messages
a) Direct EDI a) 5 b) 6 c) 4 d) 3
b) Indirect EDI
Part - II
c) Collective EDI
Short Answers
d) Unique EDI
1. Define EDI.
6. Who is called as the father of EDI?
2. List few types of business documents
a) Charles Babbage that are transmitted through EDI.
b) Ed Guilbert 3. What are the 4 major components of
c) Pascal EDI?
d) None of the above 4. What is meant by directories in
7. EDI interchanges starts with ____ EDIFACT?
and ends with ____ 5. Write a note on EDIFACT subsets.
a) UNA, UNZ
Part - III
b) UNB, UNZ Explain in Brief Answer
c) UNA, UNT 1. Write a short note on EDI.
d) UNB, UNT 2. List the various layers of EDI.
8. EDIFACT stands for 3. Write a note on UN/EDIFACT.
a) EDI for Admissible Commercial 4. Write a note on EDIFACT message.

Transport 5. Write about EDIFACT separators
b) EDI for Advisory Committee and

Transport Part - IV
c) EDI for Administration, Explain in detail

Commerce and Transport 1. Briefly explain various types of EDI.
d) EDI for Admissible Commerce 2. What are the advantages of EDI?

and Trade 3. Write about structure of EDIFACT.
9. The versions of EDIFACT are also
called as
a) Message types b) Subsets
c) Directories d) Folders

stu nt activity
de
●● Prepare a chart explaining various types of EDI standards. (e.g. web EDI)

276 Chapter 18 Electronic Data Interchange- EDI


12th STD - Computer Applications - Practical
www.tntextbooks.org

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.

2. Type the following text:


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.

3. Set the heading ‘HAPPINESS’ in 18 points, Arial font, bold and alignment centre.

4. Format the paragraph as follows:


(a) Font – Arial
(b) Font size – 12
(c) Alignment – Justified
(d) Leading – 20

5. Save the document as ‘happiness’.

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

7. To save the document as ‘happiness’


(a) Press Ctrl + S (or) Choose File > Save in the menu bar. Save publication dialogue
box appears. Type ‘happiness’ in the File name text box and press Save button.

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

PageMaker-Creating Notice Board

AIM
To create a Student Notice Board.

Create a Student Notice Board using PageMaker.

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

PageMaker-Creating Visiting Card

AIM
To create a Visiting Card using PageMaker software.

Create the following Visiting Card using PageMaker.

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.

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.

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

PageMaker-Creating Notice Board

AIM
To create a Label using PageMaker software.

Create the following Label using PageMaker.

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.

7. Choose Element > Rounded corners from the menu bar.

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.

Type Subject : and press a Tab key.

11. Select all the text using Text tool.

12. Choose Type > Indents / Tabs (or) press Ctrl + I.

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

14. Now the required label is created.

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;

CREATE TABLE student(

studentID int,

LastName varchar(255),

FirstName varchar(255),

Address varchar(255),

City varchar(255)

);

ALTER TABLE `members` ADD COLUMN `credit_card_number` VARCHAR(25);

DROP DATABASE SchoolDB

SELECT * FROM student

INSERT INTO student (studentID ,LastName , FirstName,Address,City ) VALUES

(“002”, “Ram”,”Kumar”, “ROJA NAGAR”,”CHENNAI”);

SELECT * FROM student

UPDATE student SET LastName = ‘SRI’ WHERE studentID = 003;

SELECT * FROM student

DROP TABLE student ;

SELECT * FROM student

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

Welcome to Our School

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

PHP–Create & Execute Variables

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

Create & Execute ECHO and PRINT


statements

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

echo “<h2>” . $txt1 . «</h2>»;


echo “Study PHP “ . $txt2 . «<br>”;
echo $x + $y;
$txt3 = “Hello”;
$txt4 = “Welcome”;
$x = 7;
$y = 3;

print “<h2>” . $txt3 . «</h2>»;


print “Hi “ . $txt4 . «<br>”;
print $x + $y;
?>
</body>
</html>

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

// calculates position of strong


echo strpos(“Hello world!”, “world”);
// replacing the text
echo str_replace(“Hi”, “Hello”, “Hi Everyone”);
define(“GREETING”, “Good Morning!!!”);
echo GREETING;
// changes the color of the first character of a word
$text = ‘PHP Tutorial’;
$text = preg_replace(‘/(\b[a-z])/i’,’<span style=”color:red;”>\1</span>’,$text);
echo $text;
?>
</body>
</html>

OUTPUT
12
3
emoclew
6
Hello Everyone
Good Morning!!!
PHP Tutorial

Practicals 307
www.tntextbooks.org

10
exercise

Converting Word to Digit

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

1. COMPUTER NETWORKS FIFTH EDITION ANDREW S. TANENBAUM Vrije Universiteit


Amsterdam, The Netherlands DAVID J. WETHERALL University of Washington Seattle,
WA
2. DATA AND COMPUTER COMMUNICATIONS Eighth Edition William Stallings
3. Data Communications and Computer Networks for Computer Scientists and Engineers
Second Edition Michael Duck and Richard Read
4. Domain Names - Concepts and Facilities, P. Mockapetris, The Internet Society (November
1987)
5. “Name space specifications and terminology”. Domain Names - Domain Concepts and
Facilities Paul Mockapetris (November 1987).
6. DNS Security: Defending the Domain Name Systemby Allan Liska and Geoffrey Stowe .
7. DNS and BIND, 3rd Edition by Paul Albitz and Cricket Liu, 1998, O’Reilley & Associates,
Inc..
8. Cabling: The Complete Guide to Network Wiring, Third Edition, by David Barnett, David
Groth and Jim McBee
9. LAN wiring (3rd ed. By Trulove and James, McGraw-Hill Professional
10. Electronic Commerce – A Manager‘s Guide by Kalakota, Ravi and Whinston, Andrew B.
Pearson Education, Inc.(ISBN: 9788177583922)
11. E-Commerce – Cutting Edge of Business, Kamlesh K Bajaj, Debjani Nag, Tata McGraw
Hill. (ISBN: 9780070585560)
12. E-Commerce Concepts, Models, Strategies, C S V Moorthy, Himalaya Publications. (ISBN:
9788178662763)
13. Electronic Payment Systems for E-Commerce by Donal O’Mahony (ISBN: 9781580532686)
14. Payment System Technologies and Functions: Innovations and Developments 1st Edition
by Masashi Nakajima (ISBN: 978161520645)
15. E-Commerce Security: Weak Links, Best Defenses by Anup K. Ghosh (ISBN: 9780471192237)
16. Practical Internet Security by John R. Vacca (ISBN: 9780387405339)
17. Cyber Security and IT Infrastructure Protection by John R. Vacca (ISBN: 9780124166813)
18. Architecting EDI with SAP IDocs: The Comprehensive Guide by Emmanuel Hadzipetros
(ISBN:9781592298716)
19. Demystifying EDI: A Practical Guide to Electronic Data Interchange by Russel Allen Stultz
(ISBN:9781556227080)

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

ADVISER & EXPERT Content Writers


Mrs. Subashini,
DR. P. KUMAR, Professor & HOD, Dept of Information Technology,
Joint Director (Syllabus)
Sathyabama Institute of Science & Technology,
State Council of Education Research and Training Tamilnadu
Chennai 600 006 Chennai

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.

Reviewers Ms.A.Sangeetha, PG Asst. (Computer Science)


Mr.Saravanan, Govt.Hr.Sec.School,
Vice principal, Rajanthangal, Thiruvannamalai.
Apollo Arts & Science College.
Chennai. Mr. M. Sivakumar, PG Asst. (Computer Science)
Govt.Hr.Sec.School, Sirugambur, Trichy.
Mr. M. Murali,
Technology Consultant,
Cognizent Technology, Mr. J. Sundar, PG Asst. (Computer Science)
Thuraippakam, SGR Govt.Hr.Sec.School,
Chennai. Kosavanpudur, Vellore.

Academic Co-ordinator Mr. G. Suresh kumar, PG Asst. (Computer Science)


Govt.Boys Hr.Sec.School,
U. Aarthi,
Thirumangalam, Madurai.
B.T.Assistant,
Govt. Girls Higher Secondary School,
Madurantagam, Mr. M. Ganesh, PG Asst. (Computer Science)
Kanchipuram Govt.Hr.Sec.School, Mathur, Krishnagiri.

Mr. S. Venkatachala Perumal, PG Asst. (Computer Science)


Book Design (Layout Govt.Hr.Sec.School, Manur, Tirunelveli.
Designing and Illustration)
Arokiam Felix QR Code Management Team
BlackBird Designs & Prints
Chennai S. Albert Valavan Babu, B.T,
GHS, Perumal Kovil,
Paramakudi, Ramanathapuram.
Wrapper Design
Kathir Arumugam M. Murugesan, B.T,
PUMS. Pethavelankottagam,
Muttupettai, Thiruvarur.

V. Padmavathi, B.T,
Coordination GHS, Vetriyur, Ariyalur.
Ramesh Munisamy
This book has been printed on 80 G.S.M.
Elegant Maplitho paper.

Printed by offset at:

You might also like