12th Computer Science EM FTB V23-1
12th Computer Science EM FTB V23-1
HIGHER SECONDARY
SECOND YEAR
COMPUTER SCIENCE
www.freetnbooks.com
12th Std - CS EM Introduction Pages.indd 1 23-12-2022 13:19:00
Government of Tamil Nadu
First Edition - 2019
Revised Edition - 2020, 2022, 2023
(Published under New syllabus)
Content Creation
The wise
possess all
II
www.freetnbooks.com
12th Std - CS EM Introduction Pages.indd 2 23-12-2022 13:19:00
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”.
HOW
his book does not require
T TO USE
prior knowledge in computer
Technology
THE BOOK?
ach unit comprises of simple
E
activities and demonstrations which can be done by
the teacher
and also students.
Technical terminologies are listed in glossary for easy understanding
he “ Do you know?” boxes enrich the knowledge of reader with
T
additional information
orkshops are introduced to solve the exercises using software
W
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
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
www.freetnbooks.com
12th Std - CS EM Introduction Pages.indd 3 23-12-2022 13:19:00
Computer Knowledge Hub
C PG in Computer Science
Centre ffor Development of Advanced Computing https://www.cdac.in/ Artificial Intelligence Database Management
IV
Technical Diploma
Scholarships for graduate
Diploma in Engineering
D and post graduate courses
www.freetnbooks.com
DST – INSPIRE
IN Fellowships (for Ph.D)
Professional Degree & Entrance Exams
P 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)
CAREER GUIDANCE AFTER 12TH
Institute of Chartered Accountants of India https://icai.org TIFR GS - Tata Institute of Fundamental 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
23-12-2022 13:19:00
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
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
www.freetnbooks.com
Towards More Practical Reinforcement Learning,
with Applications to Educational Games
Research Institutions in various areas of science
23-12-2022 13:19:01
Table of Contents
Computer Science-II Year
UNIT NO. CHAPTER COMPUTER SCIENCE PAGE NO MONTH
UNIT- I 1 Function 1 June
Problem 2 Data Abstraction 11 June
Solving 3 Scoping 21 June
Techniques 4 Algorithmic Strategies 31 June
5 Python -Variables and Operators 47 July
E - book Assessment
VI
www.freetnbooks.com
12th Std - CS EM Introduction Pages.indd 6 23-12-2022 13:19:01
CHAPTER 1
Unit I
FUNCTION
After the completion of this chapter, the A function is a unit of code that is
student will be able to: often defined within a greater code structure.
Specifically, a function contains a set of
• Understand Function Specification.
code that works on many kinds of inputs,
• Parameters (and arguments). like variables, 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. The duration bound to the name ‘a’. Definitions are not
of computation time must be independent expressions, at the same time expressions are
of the programming language, compiler, also not treated as definitions. Definitions
and computer used. As you aware that are distinct syntactic blocks. Definitions can
algorithms are expressed using statements have expressions nested inside them, and
of a programming language. If a bulk of vice-versa.
statements to be repeated for many numbers 1.2.2 Parameters and arguments
of times then subroutines are used to finish
the task. Parameters are the variables in a
function definition and arguments are
Subroutines are the basic building the values which are passed to a function
blocks of computer programs. Subroutines definition.
are small sections of code that are used to
1. Parameter without Type
perform a particular task that can be used
repeatedly. In Programming languages these Let us see an example of a function
subroutines are called as Functions. definition:
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 1 23-12-2022 15:42:16
When we write the type annotations
(requires: b>=0 ) for ‘a’ and ‘b’ the parentheses are
(returns: a to the power of b) mandatory. Generally we can leave out
let rec pow a b:= these annotations, because it's simpler to
if b=0 then 1 let the compiler infer them. There are times
else a * pow a (b-1) we may want to explicitly write down types.
This is useful on times when you get a type
error from the compiler that doesn't make
In the above function definition
sense. Explicitly annotating the types can
variable ‘b’ is the parameter and the value
help with debugging such an error message.
which is passed to the variable ‘b’ is the
argument. The precondition (requires) and
The syntax to define functions is close
postcondition (returns) of the function
to the mathematical usage: the definition is
is given. Note we have not mentioned any
introduced by the keyword let, followed by
types: (data types). Some language compiler
the name of the function and its arguments;
solves this type (data type) inference
then the formula that computes the image
problem algorithmically, but some require
of the argument is written after an := sign. If
the type to be mentioned.
you want to define a recursive function: use
“let rec” instead of “let”.
In the above function definition if
expression can return 1 in the then branch,
Syntax: The syntax for function definitions:
shows that as per the typing rule the
entire if expression has type int. Since the
if expression is of type ‘int’, the function's let rec fn a1 a2 ... an := k
return type also be ‘int’. ‘b’ is compared to
0 with the equality operator, so ‘b’ is also Here the ‘fn’ is used as a function
a type of ‘int’. Since ‘a’ is multiplied with name. The names ‘a1’ to ‘an’ are variables
another expression using the * operator, ‘a’ used as parameters. The keyword ‘rec’ is
must be an int. required if ‘fn’ is to be a recursive function;
otherwise it may be omitted.
2. Parameter with Type
Now let us write the same function
definition with types for some reason: Note
A function definition which call
(requires: b>=0 ) 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 find
the factorial of a number.
if b=0 then 1
else a * pow a (b-1)
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 2 23-12-2022 15:42:16
Interface is a description of all functions.
(Requires: n>= 0)
In our example, anything that "ACTS LIKE"
let rec fact n :=
a light, should have function definitions like
if n = 0 then 1 turn_on () and a turn_off (). The purpose of
else interface is to allow the computer to enforce
n ✳ fact(n-1) the properties of the class.
The syntax for function types: The difference between interface and
implementation is
x→y
x1 → x2 → y Interface Implementation
x1 → ... → xn → y
Interface just Implementation
defines what carries out the
The ‘x’ and ‘y’ are variables indicating an object can instructions defined
types. The type x → y is the type of a function do, but won’t in the interface
that gets an input of type ‘x’ and returns an actually do it
output of type ‘y’. Whereas x1 → x2 → y is
a type of a function that takes two inputs, In object oriented programs classes are
the first input is of type ‘x1’ and the second the interface and how the object is processed
input of type ‘x2’, and returns an output of and executed is the implementation.
type ‘y’. Likewise x1 → … → xn → y has
type ‘x’ as input of n arguments and ‘y’ type 1.3.1 Characteristics of interface
as output. • The class template specifies the interfaces
to enable an object to be created and
Note operated properly.
All functions are static • An object's attributes and behaviour is
definitions. There is no dynamic controlled by sending functions to the
function definitions. object.
3 Function
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 3 23-12-2022 15:42:16
let min x y z :=
ENGINE if x < y then
if x < z then x else z
else
if y < z then y else z
getSpeed
1.4 Pure functions
Internally, the engine of the car is The above function square is a pure
doing all the things. It's where fuel, air, function because it will not give different
pressure, and electricity come together to results for same input.
create the power to move the vehicle. All of
There are various theoretical
these actions are separated from the driver,
advantages of having pure functions. One
who just wants to go faster. Thus we separate
advantage is that if a function is pure, then
interface from implementation.
if it is called several times with the same
Let us see a simple example, consider arguments, the compiler only needs to
the following implementation of a function actually call the function once. Let’s see an
that finds the minimum of its three example
arguments:
let length s:=
i: = 0
if i <strlen (s) then
-- Do something which doesn't affect s
++i
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 4 23-12-2022 15:42:16
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 side effects is
Evaluation of pure modifying the variable outside of function.
functions does not cause any side
For example
effects to its output
y: = 0
1.4.1 Impure functions let inc (x: int): int:=
y: = y + x
The variables used inside the
return (y)
function may cause side effects though the
functions which are not passed with any
In the above example the value of y
arguments. In such cases the function is
get changed inside the function definition
called impure function. When a function
due to which the result will change each
depends on variables or functions outside
time. The side effect of the inc () function is
of its definition block, you can never be
it is changing the data of the external visible
sure that the function will behave the same
variable ‘y’. As you can see some side effects
every time it’s called. For example the
are quite easy to spot and some of them may
mathematical function random() will give
tricky.
different outputs for the same function call.
From all these examples and
let randomnumber :=
definitions what we can understand about
a := random() the main differences between pure and
if a > 10 then impure functions are
return: a
else
return: 10
5 Function
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 5 23-12-2022 15:42:16
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) In each iterative step, two chameleons
else
of the two types (equal in number) meet and
return a
change their colors to the third one. For
output
example, if A, B, C = 4, 4, 6, then the series
gcd 13 27
1
of meeting will result in
gcd 20536 7826
2 iteration a b c
0 4 4 6
In the above example ‘gcd’ is the name
of the function which recursively called till 1 3 3 8
the variable ‘b’ becomes ‘0’. Remember b
and (a mod b) are two arguments passed to 2 2 2 10
‘a’ and ‘b’ of the gcd function. 3 1 1 12
4 0 0 14
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 6 23-12-2022 15:42:16
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
monochromatize a b c
return a, b, 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
which are not passed with any arguments. In such cases the function is called impure
function
7 Function
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 7 23-12-2022 15:42:16
Hands on Practice
Evaluation
Part - I
Choose the best answer (1 Mark)
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code
structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function (C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) { } (B) ( ) (C) [ ] (D) < >
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
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 8 23-12-2022 15:42:16
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
Part - III
9 Function
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 9 23-12-2022 15:42:16
Part - IV
REFERENCES
www.freetnbooks.com
12th Computer Science_EM Chapter 1.indd 10 23-12-2022 15:42:16
CHAPTER 2
Unit I
DATA ABSTRACTION
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 11 26-12-2022 17:25:50
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
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 12 26-12-2022 17:25:50
city value passed as parameter city value passed as parameter city value passed as parameter
13 Data Abstraction
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 13 26-12-2022 17:25:50
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
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 14 26-12-2022 17:25:50
Example for List [10, 20]. rational(n, d):
The elements of a list can be accessed return [n, d]
in two ways. The first way is via our familiar numer(x):
method of multiple assignment, which return x[0]
unpacks a list into its elements and binds denom(x):
each element to a different name. return x[1]
lst := [10, 20]
x, y := lst 2.5.2 Tuple
Any way of bundling two values Note the square bracket notation is
together into one can be considered as a used to access the data you stored in the pair.
pair. Lists are a common method to do so. To access the first element with nums[0] and
Therefore List can be called as Pairs. the second with nums[1].
Representing Rational Numbers Using
List
You can now represent a rational
number as a pair of two integers in pseudo
code : a numerator and a denominator.
15 Data Abstraction
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 15 26-12-2022 17:25:50
2.6 Data Abstraction in person:=['Padmashri', 'Baskar', '994-
Structure 222-1234', '[email protected]']
List allow data abstraction in that but such a representation doesn't explicitly
you can give a name to a set of memory specify what each part represents.
cells. For instance, in the game Mastermind,
you must keep track of a list of four colors For this problem instead of using a
that the player guesses. Instead of using four list, you can use the structure construct (In
separate variables (color1, color2, color3, OOP languages it's called class construct)
and color4) you can use a single variable to represent multi-part objects where each
‘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- item The new data type Person is pictorially
object where each 'item' is a named thing: represented as
the firstName, the lastName, the id, and the
email. One could use a list to represent a
person:
creation ( )
function belonging to the new datatype
}
first Name
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 16 26-12-2022 17:25:50
Let main() contains
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.
• Abstract Data Types (ADT's) offer a high level view (and use) of a concept independent
of its implementation.
17 Data Abstraction
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 17 26-12-2022 17:25:50
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
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 18 26-12-2022 17:25:50
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
Part - III
19 Data Abstraction
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 19 26-12-2022 17:25:50
Part - IV
Reference Books
1. Data structure and algorithmic thinking with python by narasimha karumanchi
2. sign and analysis of algorithms by s sridhar
3. Data Structures and Algorithms in Python by Goodrich, Tamassia & Goldwasser
4. https://www.tutorialspoint.com
www.freetnbooks.com
12th Computer Science_EM Chapter 2.indd 20 26-12-2022 17:25:50
CHAPTER 3
Unit I
SCOPING
21
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 21 26-12-2022 17:27:47
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:
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 22 26-12-2022 17:27:47
below in terms of hierarchy (highest to lowest).
BUILT-IN
GLOBAL
ENCLOSED
LOCAL
2. a:=7 7
Disp( ):
3. print a a:=7
print a
4. Disp() Disp ( )
23 Scoping
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 23 26-12-2022 17:27:47
On execution of the above code the variable a displays the value 7, because it is defined
and available in the local scope.
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
2. Disp(): a:=10 7
Disp( ):
3. a:=7 a:=7 10
print a
4. print a Disp( ):
print a
5. Disp()
6. print a
On execution of the above code the variable a which is defined inside the function
displays the value 7 for the function call Disp() and then it displays 10, because a is defined in
global scope.
3.4.3 Enclosed Scope
All programming languages permit functions to be nested. A function (method) with
in another function is called nested function. A variable which is declared inside a function
which contains another function definition with in it, the inner function can also access the
variable of the outer function. This scope is called enclosed scope.
When a compiler or interpreter search for a variable in a program, it first search Local,
and then search Enclosing scopes. Consider the following example
2. a:=10 10
Disp( ):
3. Disp1(): a:=10 10
Disp 1( ):
print a
4. print a
Disp 1( )
5. Disp1() print a
Disp( )
6. print a
7. Disp()
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 24 26-12-2022 17:27:47
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
function which is defined in the modules of a programming language has Built-in or module
scope. They are loaded as soon as the library files are imported to the program.
Disp( ):
Disp1( ):
print a
Disp1( )
print a
Disp( )
Normally only Functions or modules come along with the software, as packages.
Therefore they will come under Built in scope.
25 Scoping
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 25 26-12-2022 17:27:47
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.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 26 26-12-2022 17:27:47
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.
27 Scoping
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 27 26-12-2022 17:27:47
Hands on Practice
1. Observe the following diagram and Write the pseudo code for the following
sum( )
num1:=20
sum1( )
num1:=num1 + 10
sum2( )
num1: = num1 + 10
sum2( )
sum1( )
num1:=10
sum( )
print num1
Evaluation
Part - I
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 28 26-12-2022 17:27:47
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
Part - III
29 Scoping
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 29 26-12-2022 17:27:47
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'
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
Part - IV
REFERENCES
www.freetnbooks.com
12th Computer Science_EM Chapter 3.indd 30 26-12-2022 17:27:47
CHAPTER 4
Unit I
ALGORITHMIC STRATEGIES
31
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 31 21-12-2022 15:55:00
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
2. Boil the water and pour it into the
bowl
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 32 21-12-2022 15:55:00
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
33 Algorithmic Strategies
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 33 21-12-2022 15:55:00
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
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 34 21-12-2022 15:55:00
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.
35 Algorithmic Strategies
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 35 21-12-2022 15:55:00
(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
E f 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.
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 36 21-12-2022 15:55:00
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)
37 Algorithmic Strategies
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 37 21-12-2022 15:55:00
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
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 38 21-12-2022 15:55:00
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
So interchange 15 11 16 12 14 13
15>16
11 15 16 12 14 13
No swapping
16>12
11 15 16 12 14 13
So interchange
16>14 11 15 12 16 14 13
So interchange
16>13
11 15 12 14 16 13
So interchange
11 15 12 14 13 16
The above pictorial example is for iteration-1. Similarly, remaining iteration can be
done. The final iteration will give the sorted array.
At the end of all the iterations we will get the sorted values in an array as given below:
11 12 13 14 15 16
This algorithm repeatedly selects the next-smallest element and swaps in into the right
place for every pass. Hence it is called selection sort.
Procedure
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
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 39 21-12-2022 15:55:00
2. Now we move on to the second element 4. This is repeated, until the array is
position, and look for smallest element completely sorted.
present in the sub-array, from starting
Let's consider an array with values {13, 16,
index to till the last index of sub - array.
11, 18, 14, 15}
3. Now replace the second smallest
identified in step-2 at the second position Below, we have a pictorial representation of
in the or original array, or also called first how selection sort will sort the given array.
position in the sub array.
11 13 16 14 14 14
18 18 18 18 15 15
14 14 14 16 16 16
15 15 15 15 18 18
In the first pass, the smallest element will be Finally we will get the sorted array
11, so it will be placed at the first position. end of the pass as shown above diagram.
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 40 21-12-2022 15:55:01
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 sorted
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.
previous 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
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 41 21-12-2022 15:55:01
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:
• An algorithm is a finite set of instructions to accomplish a particular task.
• Algorithm consists of step-step-by instructions that are required to accomplish a task
and helps the programmer to develop the program.
• Program is an expression of algorithm in a programming language.
• Algorithm analysis deals with the execution or running time of various operations
involved.
• Space complexity of an algorithm is the amount of memory required to run to its
completion.
• Big Oh is often used to describe the worst-case of an algorithm.
• Big Omega is used to describe the lower bound which is best way to solve the space
complexity.
• The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.
• The efficiency of an algorithm is defined as the number of computational resources
used by the algorithm.
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 42 21-12-2022 15:55:01
Points to remember:
• A way of designing algorithm is called algorithmic strategy.
• A space-time or time-memory tradeoff is a way of solving a problem or calculation in
less time by using more storage space.
• Asymptotic Notations are languages that uses meaningful statements about time and
space complexity.
• Bubble sort is a simple sorting algorithm. It compares each pair of adjacent items and
swaps them if they are in the unsorted order.
• The selection sort improves on the bubble sort by making only one exchange for every
pass through the list.
• Insertion sort is a simple sorting algorithm that builds the final sorted array or list one
item at a time. It always maintains a sorted sublist in the lower positions of the list.
• Dynamic programming is used when the solutions to a problem can be viewed as the
result of a sequence of decisions.
Evaluation
Part - I
43 Algorithmic Strategies
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 43 21-12-2022 15:55:01
5. Which of the following is used to describe the worst case of an algorithm?
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big Ω is the reverse of
(A) Big O (B) Big θ (C) Big A (D) Big S
7. Binary search is also called as
(A) Linear search (B) Sequential search
(C) Random search (D) Half-interval search
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
1. What is an Algorithm?
2. Write the phases of performance evaluation of an algorithm.
3. What is Insertion sort?
4. What is Sorting?
5. What is searching? Write its types.
Part - III
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 44 21-12-2022 15:55:01
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?
Part - IV
Reference Books
Web References
www.wickipedia.org
1. Create an algorithm for grading systems of your class student’s Quarterly examination
marks by satisfying all necessary conditions.
45 Algorithmic Strategies
www.freetnbooks.com
12th Computer Science_EM Chapter 4.indd 45 21-12-2022 15:55:01
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,
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.
www.freetnbooks.com
12th Std - CS EM Python Interleaf Page.indd 46 22-12-2022 11:18:11
CHAPTER 5
Unit II
PYTHON – VARIABLES AND OPERATORS
Learning Objectives
5.1 Introduction
47
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 47 26-12-2022 17:27:28
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.
(Or)
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 48 26-12-2022 17:27:28
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
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 49 26-12-2022 17:27:28
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)
b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 50 26-12-2022 17:27:28
(ii) Saving Python Script
(1) Choose File → Save or Press Ctrl + S
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 51 26-12-2022 17:27:28
(3) In the Save As dialog box, select the location where you want to save your Python code,
and type the file name in File Name box. Python files are by default saved with extension
.py. Thus, while creating Python scripts using Python Script editor, no need to specify
the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5
a=100
b=350
c=a+b
print ("The Sum=", c)
(2) If your code has any error, it will be shown in red color in the IDLE window, and Python
describes the type of error occurred. To correct the errors, go back to Script editor, make
corrections, save the file using Ctrl + S or File → Save and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in
Figure 5.8
Output
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 52 26-12-2022 17:27:28
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 53 26-12-2022 17:27:28
Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable. If prompt string is not given in input( ) no message is
displayed on the screen, thus, the user will not know what is to be typed as input.
>>> city=input()
Rajarajan
>>> print (“I am from”, city)
I am from Rajarajan
Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input( ).
The input ( ) accepts all data as string 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
Enter Number 2: 56
The sum = 90
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 54 26-12-2022 17:27:28
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.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.
5.7.1. Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 55 26-12-2022 17:27:28
• An identifier must start with an alphabet (A..Z and 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.
5.7.2. Keywords
Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Table 5.1 Python’s Keywords
as elif if or yield
5.7.3 Operators
In computer programming languages operators are special symbols which represent
computations, conditional matching etc. The value of an operator used is called operands.
Operators are categorized as Arithmetic, Relational, Logical, Assignment etc. Value and
variables when used with operator are known as operands.
(i) Arithmetic operators
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
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 56 26-12-2022 17:27:28
Python supports the following Arithmetic operators.
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 57 26-12-2022 17:27:28
Python supports following relational operators
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 58 26-12-2022 17:27:29
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
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 59 26-12-2022 17:27:29
Taken modulus(Remainder) using two
%= operands and assign the result >>> x%=3 # x=x%3
to left operand
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 60 26-12-2022 17:27:29
The Syntax conditional operator is,
Example :
Output:
The Minimum of A and B is 20
5.7.4 Delimiters
Delimiters are sequence of one or more characters used to specify the boundary between
seperate, independent regions in plain text or other data streams. 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 to a variable or constant. In Python, there are various types
of literals.
1) Numeric
2) String
3) Boolean
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 61 26-12-2022 17:27:29
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 :")
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.14j) Imaginary part of x = 3.14 Real part of x = 1.0
Output:
This is Python
C
This is a multiline string with more than one line code.
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 62 26-12-2022 17:27:29
(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
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 63 26-12-2022 17:27:29
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 digit 0 (Zero)
followed by letter 'o' to denote octal digits and hexadecimal integer use 0X (Zero and either
uppercase or lowercase X) and L (only upper case) to denote long integer.
Example :
102, 4567, 567 # Decimal integers
0o102, 0o876, 0o432 # Octal integers
0X102, 0X876, 0X432 # Hexadecimal integers
34L, 523L # Long decimal integers
Example :
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data
Complex number is made up of two floating point values, one each for the real and
imaginary parts.
5.8.2 Boolean Data type
A Boolean data can have any of the two values: True or False.
Example :
Bool_var1=True
Bool_var2=False
Example :
Char_data = ‘A’
String_data= "Computer Science"
Multiline_data= ”””String data can be enclosed in single quotes or
double quotes or triple quotes.”””
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 64 26-12-2022 17:27:29
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
C) Keyword D) Operators
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 65 26-12-2022 17:27:29
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)
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
www.freetnbooks.com
12th Computer Science_EM Chapter 5.indd 66 26-12-2022 17:27:29
CHAPTER 6
Unit II
CONTROL STRUCTURES
Learning Objectives
• To learn through the syntax how to use conditional construct to improve the efficiency of
the program flow.
• To apply iteration structures to develop code to repeat the program segment for specific
number of times or till the condition is satisfied.
6.1 Introduction
Programs may contain set of statements. These statements are the executable segments
that yield the result. In general, statements are executed sequentially, that is the statements
are executed one after another. There may be situations in our real life programming where
we need to skip a segment or set of statements and execute another segment based on the test
of a condition. This is called alternative or branching. Also, we may need to execute a set of
statements multiple times, called iteration or looping. In this chapter we are to focus on the
various control structures in Python, their syntax and learn how to develop the programs
using them.
67
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 67 26-12-2022 16:44:45
There are three important control structures
Sequential
Alternative or
Branching
Iterative or Looping
Example 6.1
# Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 68 26-12-2022 16:44:45
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.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
69 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 69 26-12-2022 16:44:45
Entry
if condition is if condition is
true condition false
Statement Statement
block -1 block -2
Exit
Fig. 6.1 if..else statement execution
if..else statement thus provides two possibilities and the condition determines which
BLOCK is to be executed.
An alternate method to rewrite the above program is also available in Python. The
complete if..else can also written as:
Syntax:
variable = variable1 if condition else variable 2
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 70 26-12-2022 16:44:45
Note
The condition specified in the if statement is checked, if it is true, the value of
variable1 is stored in variable on the left side of the assignment, otherwise variable2 is
taken as the value.
71 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 71 26-12-2022 16:44:45
Test false
Expression
of if
True
Body of else
Body of elif
Note
if..elif..else statement is similar to nested if statement which you have learnt in C++.
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 72 26-12-2022 16:44:45
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
Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D
Output 2 :
Enter mark in first subject : 67
Enter mark in second subject : 73
Grade : B
Note
In the above example of if and elif 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.
73 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 73 26-12-2022 16:44:45
Example 6.5a: #Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)
Output 1:
Enter a character :e
e is a vowel
Output 2:
Enter a character :x
x the letter is not a/b/c
Iteration or loop are used in situation when the user need to execute a block of code
several of times or till the condition is satisfied. A loop statement allows to execute a statement
or group of statements multiple times.
False
Condition
True else
Statement 1
Statement 1 Statement 2
Statement 2 ...
... Statementn
Statementn
Further
Statements
of Program
Fig 6.3 Diagram to illustrate how looping construct gets executed
Python provides two types of looping constructs:
• while loop
• for loop
XII Std Computer Science 74
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 74 26-12-2022 16:44:45
(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
Example 6.6: program to illustrate the use of while loop - to print all numbers
from 10 to 15
Output:
10 11 12 13 14 15
75 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 75 26-12-2022 16:44:46
Note
In the above example, the control variable is i, which is initialized to 10. Next the
condition i<=15 is tested, if the value is true 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 returned as False and this will terminate the loop.
Note
print can have end, sep as parameters. end parameter can be used when we need to give
any escape sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be
used to specify any special characters like, (comma) ; (semicolon) as separator between
values (Recall the concept which you have learnt in previous chapter about the formatting
options in print()).
Example 6.7: program to illustrate the use of while loop - with else part
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
The for .... in statement is a looping statement used in Python to iterate over a sequence
of objects, i.e., it goes through each item in a sequence. Here the sequence is the collection of
ordered or unordered values or even a string.
XII Std Computer Science 76
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 76 26-12-2022 16:44:46
The control variable accesses each item of the sequence on each iteration until it reaches the
last item in the sequence.
In the above example 6.8(a), we have created a string “Hello World”, as the sequence.
Initially, the value of x is set to the first element of the string, (i.e. ‘H’), so the print statement
inside the loop is executed. Then, the control variable x is updated with the next element of
the string and the print statement is executed again. In this way the loop runs until the last
element of the string is accessed.
In the same way, example 6.8(b) prints the string “Hello World”, five times, until the control
variable x reaches last element of the given sequence.
Instead of creating sequence of values manually, we can use range().
The range() is a built-in function, to generate series of values between two numeric intervals.
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.
77 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 77 26-12-2022 16:44:46
for each item
in sequence
Yes
Last item
reached?
No
Body of for
Exit loop
Fig 6.5 for loop execution
Example 6.9: #program to illustrate the use of for loop - to print single
digit even number
for i in range (2,10,2):
print (i, end=' ')
Output:
2468
Note
In Python, indentation is important in loop and other control statements. Indentation
only creates blocks and sub-blocks like how we create blocks within a set of { } in languages
like C, C++ etc.
Here is another program which illustrates the use of range() to find the sum of numbers
1 to 100
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 78 26-12-2022 16:44:46
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
of counter variable and stored in sum. Note that the for loop will iterate from 1 till
the upper limit -1 (ie. Value of n is set as 100, so this loop will iterate for values from
1 to 99 only, that is the reason why we have set the upper limit as n+1)
Note
for loop can also take values from string, list, dictionary etc. which will be dealt
in the later chapters.
79 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 79 26-12-2022 16:44:46
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
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
False
Condition
True else
Statement 1
Statement 1 Statement 2
... ...
break Statementn
...
continue Further
... Statements
Statementn of Program
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 80 26-12-2022 16:44:46
(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.
If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Syntax:
break
Enter loop
false
Condition
true
break?
yes
Exit loop
no
Remaining body of loop
81 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 81 26-12-2022 16:44:46
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:
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
loop and start with next iteration.
Syntax:
continue
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 82 26-12-2022 16:44:46
Enter loop
Test false
Expression
of loop
true
yes
continue?
Exit loop
no
Remaining body of loop
The working of continue statement in for and while loop is shown below.
for var in sequence:
# code inside for loop
if condition:
continue
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
continue
#code inside while loop
#code outside while loop
83 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 83 26-12-2022 16:44:46
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.
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
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
output will be as follows:
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 84 26-12-2022 16:44:46
Example 6.18: Program to illustrate the use of pass statement in for loop
for val in “Computer”:
pass
print (“End of the loop, loop structure will be built in future”)
Output:
End of the loop, loop structure will be built in future.
Points to remember:
85 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 85 26-12-2022 16:44:46
Hands on Experience
Evaluation
Part - I
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 86 26-12-2022 16:44:46
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 of the following is known as definite 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) 1
9. Which amongst this is not a jump statement ?
A) for B) pass
C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) :
C) :: D) !
87 Control Structures
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 87 26-12-2022 16:44:46
Part -II
Part -III
Part -IV
www.freetnbooks.com
12th Computer Science_EM Chapter 6.indd 88 26-12-2022 16:44:46
CHAPTER 7
Unit II
PYTHON FUNCTIONS
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 89 21-12-2022 15:21:23
• If any input parameters are present should
Recursion Functions that calls
functions itself is known as be placed within these parentheses when
recursive. you define a function.
Table – 7.1 – Python Functions and it's • The code block always comes after a
Description colon (:) and is indented.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 90 21-12-2022 15:21:23
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: 7.2.1
def hello():
print (“hello - Python”)
return
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: 7.3.2
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.
91 Python Functions
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 91 21-12-2022 15:21:23
The above function will output the following.
Output:
hello – Python
None
Syntax:
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: 7.4
# assume w = 3 and h = 5
def area(w,h):
return w * h
print (area (3,5))
The above code assigns the width and height values to the parameters w and h. These
parameters are used in the creation of the function “area”. When you call the above function,
it returns the product of width and height as output.
The value of 3 and 5 are passed to w and h respectively, the function will return 15 as
output.
We often use the terms parameters and arguments interchangeably. However, there
is a slight difference between them. Parameters are the variables used in the function
definition whereas arguments are the values we pass to the function parameters
Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 92 21-12-2022 15:21:23
Function Arguments
1 Required arguments
2 Keyword arguments
3 Default arguments
4 Variable-length arguments
Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is
Output:
Example - Required arguments
Welcome
93 Python Functions
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 93 21-12-2022 15:21:23
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: 7.5.2 (a)
def printdata (name):
print (“Example-1 Keyword arguments”)
print (“Name :”,name)
return
# Now you can call printdata() function
printdata(name = “Gshan”)
Output:
Example-1 Keyword arguments
Name :Gshan
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 94 21-12-2022 15:21:23
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
Example: 7.5.3
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Mani”)
Output:
Name: Mani
Salary: 3500
Output:
Name: Ram
Salary: 2000
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
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 95 21-12-2022 15:21:23
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: 7.5.4
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15,20,25)
Example: 7.5.4. 1
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 ?
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 96 21-12-2022 15:21:24
In Variable Length arguments we can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
Non-keyword variable arguments are called tuples. You will learn more about tuples in
the later chapters. The Program given is an illustration for non keyword variable argument.
Note
Keyword variable arguments are beyond the scope of this book.
Note
filter(), map() and reduce() functions are beyond the scope of this book.
Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.
97 Python Functions
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 97 21-12-2022 15:21:24
7.6.1 Syntax of Anonymous Functions
The syntax for anonymous functions is as follows:
The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().
• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return
This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 98 21-12-2022 15:21:24
Example : 7.7.1
# 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
99 Python Functions
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 99 21-12-2022 15:21:24
Example : 7.8.1 (a) Create a Local Variable
def loc():
y=0 # local scope
print(y)
loc()
Output:
0
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 100 21-12-2022 15:21:24
Example : 7.8.2 (b) Modifying Global Variable From Inside the Function
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
UnboundLocal 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.
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 101 21-12-2022 15:21:24
7.8.3 Global and local variables
Here, we will show how to use global variables and local variables in the same code.
Example : 7.8.3 (a) 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 : 7.8.3 (b) 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().
The output :- local x: 10, is called local scope of variable.
The output:- global x: 5, is called global scope of variable.
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 102 21-12-2022 15:21:24
7.9 Functions using libraries
7.9.1 Built-in and Mathematical functions
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 103 21-12-2022 15:21:24
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.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 104 21-12-2022 15:21:24
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.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 105 21-12-2022 15:21:24
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
Specify import math module before using all mathematical
functions in a program
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 106 21-12-2022 15:21:24
ceil ( ) Returns the smallest math.ceil (x) import math
integer greater than or x= 26.7
equal to x y= -26.7
z= -23.2
print (math.ceil (x))
print (math.ceil (y))
print (math.ceil (z))
Output:
27
-26
-23
sqrt ( ) Returns the square root math.sqrt (x ) import math
of x a= 30
Note: x must be greater b= 49
than 0 (zero) c= 25.5
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 : 7.9. 2
# 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
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 107 21-12-2022 15:21:24
recursion.
A recursive function calls itself. Imagine a process would iterate indefinitely if not
stopped by some condition! Such a process is known as infinite iteration. The condition that
is applied in any recursive function is known as base condition. A base condition is must in
every recursive function otherwise it will continue to execute like an infinite loop.
Example : 7.10
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 Recursion Error after 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:
return n * fact(n-1)
print(fact (2000))
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 108 21-12-2022 15:21:24
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 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.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 109 21-12-2022 15:21:24
Hands on Experience
1. Try the following code in the above program
1 eval(‘25*2-5*4')
2 math.sqrt(abs(-81))
3 math.ceil(3.5+4.6)
4 math.floor(3.5+4.6)
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 110 21-12-2022 15:21:24
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
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot)
(c) : (colon) (d) $ (dollar)
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 111 21-12-2022 15:21:24
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
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 112 21-12-2022 15:21:24
Part - III
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from tutorialspoint.com
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert
www.freetnbooks.com
12th Computer Science_EM Chapter 7.indd 113 21-12-2022 15:21:24
CHAPTER 8
Unit II
STRINGS AND STRING MANIPULATION
Learning Objectives
8.1 Introduction
String is a data type in python, which is used to handle array of characters. String is
a sequence of Unicode characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.
Example
In python, strings are immutable, it means, once you define a string, it cannot be
changed during execution.
8.2 Creating Strings
As we learnt already, a string in Python can be created using single or double or even
triple quotes. String in single quotes cannot hold any other single quoted string in it, because
the interpreter 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
triple quotes. Defining strings within triple quotes also allows creation of multiline strings.
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 114 21-12-2022 15:28:38
Example
#A string defined within single quotes
>>> print (‘Greater Chennai Corporation’)
Greater Chennai Corporation
#single quoted string defined within single quotes
>>> print ('Greater Chennai Corporation's student')
SyntaxError: invalid syntax
The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.
Example
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 115 21-12-2022 15:28:38
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
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 116 21-12-2022 15:28:38
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 temporarily change all occurrences of a particular character in a string.
The changes done through replace () does not affect the original 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
Similar as modification, python will not allow deleting a particular character in a string.
Whereas you can remove entire string variable using del command.
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 117 21-12-2022 15:28:38
Example 3: Code lines to delete a particular character in a string:
(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.
Example
>>> str1="Welcome to "
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 118 21-12-2022 15:28:38
>>> 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"
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 119 21-12-2022 15:28:38
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
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
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 120 21-12-2022 15:28:38
Example
>>> str1 = "Welcome to learn Python"
>>> print(str1[::-2])
nhy re teolW
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
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 121 21-12-2022 15:28:39
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?"
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 122 21-12-2022 15:28:39
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
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 123 21-12-2022 15:28:39
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.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 124 21-12-2022 15:28:39
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
Output : 2
Enter a string: Govt G HSS, Ashok Nagar
Not Found
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 125 21-12-2022 15:28:39
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
*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)
i+=1
Output
*
* *
* * *
* * * *
* * * * *
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 126 21-12-2022 15:28:39
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
elif i.isalpha():
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 13 consonants
Example 8.11.5 : 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)
Output
Enter a String: Mathematical fundations of Computer Science
The string without vowels: Mthmtcl fndtns f Cmptr Scnc
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 127 21-12-2022 15:28:39
Example 8.11.6 : 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.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 128 21-12-2022 15:28:39
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 image of the given string. For example, “wel” = “lew“.
9. Write a program to replace a string with another string without using replace().
10. Write a program to count the number of characters, words and lines in a given string.
Evaluation
Part - I
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 129 21-12-2022 15:28:39
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) %f (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
www.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 130 21-12-2022 15:28:39
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
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.freetnbooks.com
12th Computer Science_EM Chapter 8.indd 131 21-12-2022 15:28:39
CHAPTER 9
Unit III
LISTS, TUPLES, SETS AND DICTIONARY
Learning Objectives
Python programming language has four collections of data types such as List, Tuples,
Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an
ordered collection of values enclosed within square brackets [ ]. Each value of a list is called
as element. It can be of any type such as numbers, characters, strings and even the nested lists
as well. The elements can be modified or mutable which means the elements can be replaced,
added or removed. Every element rests at some position in the list. The position of an element
is indexed with numbers beginning with zero which is used to locate and access a particular
element. Thus, lists are similar to arrays, what you learnt in XI std.
9.1.1 Create a List in Python
In python, a list is simply created by using square bracket. The elements of list should
be specified within square brackets. The following syntax explains the creation of list.
Syntax:
Variable = [element-1, element-2, element-3 …… element-n]
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 132 21-12-2022 15:37:02
Example
Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]
In the above example, the list Marks has four integer elements; second list Fruits has
four string elements; third is an empty list. The elements of a list need not be homogenous type
of data. The following list contains multiple type elements.
In the above example, Mylist contains another list as an element. This type of list is
known as “Nested List”.
Example
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1
Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).
To access an element from a list, write the name of the list, followed by the index of the
element enclosed within square brackets.
Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 133 21-12-2022 15:37:02
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.
Note
A negative index can be used to access an element in reverse order.
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
the test condition is i < 4, as long as the test condition is true, the loop executes and prints the
corresponding output.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 134 21-12-2022 15:37:02
During the first iteration, the value of i is 0, where the condition is true. Now, the
following statement print (Marks [i]) gets executed and prints the value of Marks [0] element
ie. 10.
The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of
control shifts to the while statement for checking the test condition. The process repeats to
print the remaining elements of Marks list until the test condition of while loop becomes false.
The following table shows that the execution of loop and the value to be print.
print
Iteration i while i < 4 i=i+1
(Marks[i])
5 4 4 < 4 False -- --
Example
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1
Output
75
41
23
10
The following table shows the working process of the above python coding
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 135 21-12-2022 15:37:02
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 -- --
Syntax:
for index_var in list:
print (index_var)
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 136 21-12-2022 15:37:02
Here, index_var represents the index value of each element in the list. Python reads
this “for” statement like English: “For (every) element in (the list of) list and print (the name of
the) list items”
Example
In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The
Python reads the for loop and print statements like English: “For (every) element (represented
as x) in (the list of) Marks and print (the values of the) elements”.
Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed
Where, index from is the beginning index of the range; index to is the upper limit of
the range which is excluded in the range. For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to
4, it should be specified as [1:5].
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 137 21-12-2022 15:37:02
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
6
8
10
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 138 21-12-2022 15:37:02
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]
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']
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 139 21-12-2022 15:37:02
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 elements whose index is known 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
the python.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 140 21-12-2022 15:37:02
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.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 141 21-12-2022 15:37:02
Example
>>> MyList.pop(1)
34
>>> print(MyList)
[12, 'Kannan', 'Gowrisankar', 'Lenin']
In the above code, pop() function is used to delete a particular element using its index
value, as soon as the element is deleted, the pop() function shows the element which is deleted.
pop() function is used to delete only one element from a list. Remember that, del statement
deletes multiple elements.
Example
>>> MyList.clear( )
>>> print(MyList)
[ ]
In the above code, clear() function removes only the elements and retains the list. When
you try to print the list which is already cleared, an empty square bracket is displayed without
any elements, which means the list is empty.
where,
• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of
values.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 142 21-12-2022 15:37:02
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
Syntax:
List_Varibale = list ( range ( ) )
Note
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 143 21-12-2022 15:37:02
Example
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]
In the above code, list() function takes the result of range() as Even_List elements. Thus,
Even_List list has the elements of first five even numbers.
Similarly, we can create any series of values using range() function. The following example
explains how to create a list with squares of first 10 natural numbers.
In the above program, an empty list is created named “squares”. Then, the for loop
generates natural numbers from 1 to 10 using range() function. Inside the loop, the current
value of x is raised to the power 2 and stored in the variables. Each new value of square is
appended to the list “squares”. Finally, the program shows the following values as output.
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Syntax:
List = [ expression for variable in range ]
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 144 21-12-2022 15:37:02
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 145 21-12-2022 15:37:02
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
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 146 21-12-2022 15:37:02
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(j+1,subjects[j],marks[j]))
print("Total Marks = ", sum(marks))
Output
Enter Mark = 45
Enter Mark = 98
Enter Mark = 76
Enter Mark = 28
Enter Mark = 46
Enter Mark = 15
1. Tamil Mark = 45
2. English Mark = 98
3. Physics Mark = 76
4. Chemistry Mark = 28
5. Comp. Science Mark = 46
6. Maths Mark = 15
Total Marks = 308
items=[]
prod=1
for i in range(5):
print ("Enter price for item { } : ".format(i+1))
p=int(input())
items.append(p)
for j in range(len(items)):
print("Price for item { } = Rs. { }".format(j+1,items[j]))
prod = prod * items[j]
print("Sum of all prices = Rs.", sum(items))
print("Product of all prices = Rs.", prod)
print("Average of all prices = Rs.",sum(items)/len(items))
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 147 21-12-2022 15:37:02
Output:
Enter price for item 1 :
5
Enter price for item 2 :
10
Enter price for item 3 :
15
Enter price for item 4 :
20
Enter price for item 5 :
25
Price for item 1 = Rs. 5
Price for item 2 = Rs. 10
Price for item 3 = Rs. 15
Price for item 4 = Rs. 20
Price for item 5 = Rs. 25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0
count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))
s=int(input())
salary.append(s)
for j in range(len(salary)):
annual_salary = salary[j] * 12
print ("Annual Salary of Employee { } is:Rs. { }".format(j+1,annual_salary))
if annual_salary >= 100000:
count = count + 1
print("{ } Employees out of { } employees are earning more than Rs. 1 Lakh per annum".
format(count, n))
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 148 21-12-2022 15:37:02
Output:
Enter no. of employees: 5
No. of Employees 5
Enter Monthly Salary of Employee 1 Rs.:
3000
Enter Monthly Salary of Employee 2 Rs.:
9500
Enter Monthly Salary of Employee 3 Rs.:
12500
Enter Monthly Salary of Employee 4 Rs.:
5750
Enter Monthly Salary of Employee 5 Rs.:
8000
Annual Salary of Employee 1 is:Rs. 36000
Annual Salary of Employee 2 is:Rs. 114000
Annual Salary of Employee 3 is:Rs. 150000
Annual Salary of Employee 4 is:Rs. 69000
Annual Salary of Employee 5 is:Rs. 96000
2 Employees out of 5 employees are earning more than Rs. 1 Lakh per annum
Output
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 149 21-12-2022 15:37:02
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, ...,
2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are
enclosed by paranthesis.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 150 21-12-2022 15:37:02
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 = ( )
Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')
Syntax:
Tuple_Name = tuple( [list elements] )
Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
>>> type (MyTup3)
<class ‘tuple’>
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 151 21-12-2022 15:37:02
Note
Type ( ) function is used to know the data type of a python object.
Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>
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)
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 152 21-12-2022 15:37:02
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)
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 153 21-12-2022 15:37:02
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.
Output:
Maximum value = 99
Minimum value = 1
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 154 21-12-2022 15:37:02
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
Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)
Note
Some of the functions used in List can be applicable even for tuples.
Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
Value of A = 38
Value of B = 54
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 155 21-12-2022 15:37:02
Program 2: Write a program using a function that returns the area and
circumference of a circle whose radius is passed as an argument.two values
using tuple assignment
pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)
Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002
Program 3: Write a program that has a list of positive and negative numbers.
Create a new tuple that has only positive numbers from the list
Output:
Positive Numbers: (5, 6, 8, 3, 1)
9.3 Sets
Introduction
In python, a set is another type of collection data type. A Set is a mutable and an unordered
collection of elements without duplicates. That means the elements within a set cannot be
repeated. This feature used to include membership testing and eliminating duplicate elements.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 156 21-12-2022 15:37:02
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.
Example
MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)
Output:
{2, 4, 6, 8, 10}
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 157 21-12-2022 15:37:02
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.
Set A Set B
In python, the operator | is used to union of two sets. The function union() is also used
to join two sets in python.
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 158 21-12-2022 15:37:02
(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.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)
Output:
{'A', 'D'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.intersection(set_B))
Output:
{'A', 'D'}
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 159 21-12-2022 15:37:02
(iii) Difference
It includes all elements that are in first set (say set A) but not in the second set (say set B)
Set A Set B
The minus (-) operator is used to difference set operation in python. The function
difference() is also used to difference operation.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.difference(set_B))
Output:
{2, 4}
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 160 21-12-2022 15:37:03
(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.
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A.symmetric_difference(set_B))
Output:
{2, 4, 'B', 'C'}
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 161 21-12-2022 15:37:03
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
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.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 162 21-12-2022 15:37:03
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.
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
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 163 21-12-2022 15:37:03
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
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.
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
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 164 21-12-2022 15:37:03
Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary
Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{ }
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined
(2) The index values can be used to access a particular element. But, in dictionary key
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 165 21-12-2022 15:37:03
Points to remember:
• Python programming language has four collections of data types such as List, Tuple,
Set and Dictionary.
• A list is known as a “sequence data type”. Each value of a list is called as element.
• The elements of list should be specified within square brackets.
• Each element has a unique value called index number begins with zero.
• Python allows positive and negative values as index.
• Loops are used access all elements from a list.
• The “for” loop is a suitable loop to access all the elements one by one.
• The append ( ), extend ( ) and insert ( ) functions are used to include more elements
in a List.
• The del, remove ( ) and pop ( ) are used to delete elements from a list.
• The range ( ) function is used to generate a series of values.
• Tuples consists of a number of values separated by comma and enclosed within
parentheses.
• Iterating tuples is faster than list.
• The tuple ( ) function is also used to create Tuples from a list.
• Creating a Tuple with one element is called “Singleton” tuple.
• A Set is a mutable and an unordered collection of elements without duplicates.
• A set is created by placing all the elements separated by comma within a pair of curly
brackets.
• A dictionary is a mixed collection of elements.
Hands on Experience
3. Write a program that finds the sum of all the numbers in a Tuples using while loop.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 166 21-12-2022 15:37:03
5. Write a program that reverse a list using a loop.
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
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 167 21-12-2022 15:37:03
7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
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
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 168 21-12-2022 15:37:03
4. Differentiate del with remove() function of List.
5. Write the syntax of creating a Tuple with n number of elements.
6. What is set in Python?
Part - III
Part - IV
References
1. https://docs.python.org/3/tutorial/index.html
2. https://www.techbeamers.com/python-tutorial-step-by-step/#tutorial-list
3. Python programming using problem solving approach – Reema Thareja – Oxford
University press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.
www.freetnbooks.com
12th Computer Science_EM Chapter 9.indd 169 21-12-2022 15:37:03
CHAPTER 10
Unit III
PYTHON CLASSES AND OBJECTS
Learning Objectives
10.1 Introduction
Python is an Object Oriented Programming language. Classes and Objects are the key
features of Object Oriented Programming. Theoretical concepts of classes and objects are very
similar to that of C++. But, creation and implementation of classes and objects is very simple
in Python compared to C++.
Class is the main building block in Python. Object is a collection of data and function
that act on those data. Class is a template for the object. According to the concept of Object
Oriented Programming, objects are also called as instances of a class. 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
…………..
…………..
statement_n
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 170 26-12-2022 16:45:44
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.
Syntax:
Object_name = class_name( )
Note that the class instantiation uses function notation ie. class_name with ()
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 171 26-12-2022 16:45:44
In the above code, the name of the class is Sample. Inside the class, we have assigned
the variables x and y with initial value 10 and 20 respectively. These two variables are called as
class variables or member variables of the class. In class instantiation process, we have created
an object S to access the members of the class. The first two print statements simply print the
value of class variable x and y and the last print statement add the two values and print the
result.
Note
• The statements defined inside the class must be properly indented.
• Parameters are the variables in the function definition.
• Arguments are the values passed to the function definition.
class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable
S=Student()
S.process()
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
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 172 26-12-2022 16:45:44
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:
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
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 173 26-12-2022 16:45:44
Example : Program to illustrate Constructor
class name
class Sample: Parameter
def __init__(self, num):
print("Constructor of class Sample...")
self.num=num Instance variable
print("The value is :", num)
S=Sample(10)
The above class “Sample”, has only a constructor with one parameter 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 instance variable
self.num = 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.
Note
Instance variables are the variables whose value varies from object to object.
For every object, a separate copy of the instance variable will be created.
Instance variables are declared inside a method using the self keyword. In
the above example, we use constructor to define instance variable.
S1=Sample(15)
S2=Sample(35)
S3=Sample(45)
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 174 26-12-2022 16:45:44
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
Destructor is also a special method to destroy the objects. In Python, _ _del_ _( )
method is used as destructor. It is just opposite to constructor.
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 = ", self.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)
del S1, S2, S3
Note
The __del__ method gets called automatically when we deleted the object
reference using the del.
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.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 175 26-12-2022 16:45:44
Example : Program to illustrate private and public variables
class Sample:
n1 = 12
__n2 = 14
def display(self):
print("Class variable 1 = ", self.n1)
print("Class variable 2 = ", self.__n2)
S=Sample()
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
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 176 26-12-2022 16:45:45
10.8 Sample Programs to illustrate classes and objects
Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 177 26-12-2022 16:45:45
if (ch.isspace()):
self.space+=1
self.consonant = self.upper+self.lower - self.
vowel
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.upper)
print("%d Lowercase letters"%self.lower)
print("%d Vowels"%self.vowel)
print("%d Consonants"%self.consonant)
print("%d Spaces"%self.space)
S = String()
S.getstr()
S.count()
S.display()
Output:
Enter a String:Welcome To Learn Computer Science
The given string contains...
4 Uppercase letters
25 Lowercase letters
12 Vowels
13 Consonants
4 Spaces
Points to remember
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 178 26-12-2022 16:45:45
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
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 179 26-12-2022 16:45:45
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
print (self.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
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?
5. What is the purpose of Destructor?
www.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 180 26-12-2022 16:45:45
Part -III
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.freetnbooks.com
12th Computer Science_EM Chapter 10.indd 181 26-12-2022 16:45:45
CHAPTER 11
Unit IV
DATABASE CONCEPTS
11.2 Information
Learning Objectives
Information is processed data, which
At the completion of this chapter, the student allows to be utilized in a significant way.
will be able to know Example
• the concept of a database and relational SCERT
database. College Road
• different components of the database. DPI Campus
Chennai 600006
• types of database models.
As you can see
• types of relationship.
from the example above,
• the concepts of relational algebra. data appears as a set of
Introduction words and numbers. However, when the
data is processed, organized and formatted,
A database is an organized collection it gives a meaningful information about the
of data, generally stored and accessed SCERT institution contact address.
electronically from a computer system. The
11.3 Database
term "database" is also used to refer to any
Database is a repository collection of
of the DBMS, the database system or an
related data organized in a way that data can
application associated with the database.
be easily accessed, managed and updated.
Because of the close relationship between
Database can be a software or hardware
them, the term "database" is often used
based, with one sole purpose of storing data.
casually to refer to both a database and
the DBMS used to manipulate it. A school 11.4 DataBase Management
class register is a database where names are System (DBMS)
arranged alphabetically. Databases have A DBMS is a software that allows us
been around since people started recording to create, define and manipulate database,
things. Here we tend to focus on electronic allowing users to store, process and analyze
ones. data easily. DBMS provides us with an
interface or a tool, to perform various
11.1 Data operations to create a database, storing of
Data are raw facts stored in a data and for updating data, etc. DBMS also
computer. A data may contain any character, provides protection and security to the
text, word or a number. databases. It also maintains data consistency
Example : 600006, DPI Campus, SCERT, in case of multiple users.
Chennai, College Road Examples of DBMS softwares : Foxpro, dbase.
182
182
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 182 26-12-2022 16:46:12
11.4.1 Relational Database Management System (RDBMS)
RDBMS is more advanced version of DBMS, that allows to data in a more efficient way.
It is used to store and manupulate the data that are in the form of tables.
Examaple of RDBMS: MySQL,Oracle, MS-Access etc.,
11.4.2 Characteristics of Relational Database Management System
1.
Ability to manipulate RDBMS provides the facility to manipulate data (store, modify
data and delete)in a data base.
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 RDBMS follows
Normalisation which divides the data in such a way that
repetition is minimum.
4. Support Multiple user RDBMS 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 RDBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and updated
in a database.
6. Security The RDBMS also takes care of the security of data, protecting
the data from unauthorized access. In a typical RDBMS, 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.
183
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 183 26-12-2022 16:46:12
11.4.4 Components of DBMS 3. Data: It is the 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 2.Software instructions to use a database management
system such as installation of DBMS,
3.Data 4.Procedures/Methods
manage databases to take backups, report
5.Database Access Languages generation, etc.
5. DataBase Access Languages: They are
the languages used to write commands to
access, insert, update and delete data stored
Hardware in any database.
Examples of popular DBMS: Dbase,
FoxPro
Software
11.5 Database Structure
Data Base Procedures
/ Methods Table is the entire collection of
Access
related data in one table, referred to as a File
DATA
Languages
or Table where the data is organized as row
USER and column.
Components of DBMS
Each row in a table represents a
Figure 11.1 record, which is a set of data for each
database entry.
1. Hardware: The computer, hard disk, I/O
channels for data, and any other physical Each table column represents a Field,
component involved in storage of data which groups each piece or item of data
2. Software: This main component is among the records into specific categories or
a program that controls everything. The types of data. Eg. StuNo., StuName, StuAge,
DBMS software is capable of understanding StuClass, StuSec.
the Database Access Languages and A Table is known as a RELATION
interprets into database commands for
execution. A Row is known as a TUPLE
A column is known as an ATTRIBUTE
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 184 26-12-2022 16:46:12
Attribute / Column Tuple / Row
Table / Relation
DataBase Structure
Fig 11.2
11.6 Data Model
• A data model describes how the data can be represented and accessed from a software after
complete implementation
• It is a simple abstraction of complex real world data gathering environment.
• The main purpose of data model is to give an idea as how the final system or software will
look like after development is completed.
• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model
1. Hierarchical Model
Hierarchical model was developed by IBM as Information Management System.
In Hierarchical model, data is represented as a simple tree like structure form. This
model represents a one-to-many relationship i.e 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.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 185 26-12-2022 16:46:12
School
Course Resources
Theory Lab
2. Relational Model
The Relational Database model was first proposed by E.F. Codd in 1970 . Nowadays, it
is the most widespread data model used for database applications around the world.
The basic structure of data in relational model is tables (relations). All the information’s
related to a particular type is stored in rows of that table. Hence tables are also known as
relations in a relational model. A relation key is an attribute which uniquely identifies a
particular tuple (row in a relation (table)).
3. Network Model
Network database model is an extended form of hierarchical data model. The difference
between hierarchical and Network data model is :
• In hierarchical model, a child record has only one parent node,
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 186 26-12-2022 16:46:12
• In a Network model, a child may have many parent nodes. It represents the data in many-
to-many relationships.
• This model is easier and faster to access the data.
School
Library Office Staff Room This child has one parent node
Network Model
Fig. 11.5
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 187 26-12-2022 16:46:12
Doctor Diagnosis Patient
5. Object Model
Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance. This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing. It is used in file
Management System. It represents real world objects, attributes and behaviors. It provides a
clear modular structure. It is easy to maintain and modify the existing code.
Shape
get_area()
get_perimeter()
An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects
in this model.
• Circle has the attribute radius.
• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
• The objects Circle, Rectangle and Triangle inherit from the object Shape.
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 188 26-12-2022 16:46:12
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.
Database normalization was first proposed by Dr. Edgar F Codd as an integral part
of RDBMS in order to reduce data redundancy and improve data integrity. These rules are
known as E F Codd Rules.
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 189 26-12-2022 16:46:12
11.8 Types of Relationships staff members.
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
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 190 26-12-2022 16:46:13
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 : ∏)
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 191 26-12-2022 16:46:13
STUDENT
Table 11.1
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical subset of
Relation.
Course
Big Data
R language
Python Programming
Note
duplicate row is removed in the result
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 192 26-12-2022 16:46:13
Example 2 (using Table 11.1)
Πstudno, course (STUDENT)
Result
Studno Course
cs1 Big Data
cs2 R language
cs3 Big Data
cs4 Python Programming
Table A Table B
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 193 26-12-2022 16:46:13
Result
Table A - B
cs4 Padmaja
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.
A∩B
cs1 Kannan
cs3 Lenin
1 S 1 S
2 1 R
R
3 2 S
2 R
Table A = 3
Table B = 2 3 S
Table A x B = 3 x 2 = 6
3 R
Cartesian Product
Fig. 11.12
Table A Table B
studno name course subject
cs1 Kannan cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs4 Padmaja cs25 python programming
Table 11.3
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 194 26-12-2022 16:46:13
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-many
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
• ER model consists of entities, attributes and relationships
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 195 26-12-2022 16:46:13
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 - I
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 196 26-12-2022 16:46:13
7. Which of the following is an RDBMS?
a) Dbase b) Foxpro
c) Microsoft Access d) Microsoft Excel
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 -II
www.freetnbooks.com
12th Computer Science_EM Chapter 11.indd 197 26-12-2022 16:46:13
CHAPTER 12
Unit IV
STRUCTURED QUERY LANGUAGE (SQL)
Learning Objectives
Note
Latest SQL standard as of now is SQL 2008, released in 2008.
RDBMS stands for Relational DataBase Management System. Oracle, MySQL, MS SQL
Server, IBM DB2 and Microsoft Access are RDBMS packages. SQL is a language used to access
data in such databases.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 198 22-12-2022 11:54:46
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 199 22-12-2022 11:54:46
12.4 Creating Database
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.
The DDL provides a set of definitions to specify the storage structure and access
methods used by the database system.
1. It should identify the type of data division such as data item, segment, record and database
file.
2. It gives a unique name to each data item type, record type, file type and data base.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 200 22-12-2022 11:54:46
3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values that a data item may use.
6. It may specify privacy locks for preventing unauthorized data entry.
SQL commands which comes under Data Definition Language are:
Create To create tables in the database.
Truncate Remove all records from a table, also release the space occupied by those records.
Delete Deletes all records from a table, but not the space occupied by them.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 201 22-12-2022 11:54:46
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.
The data in a database is stored based on the kind of value stored in it. This is identified
as the data type of the data or by assigning each field a data type. All the values in a given field
must be of same type.
The ANSI SQL standard recognizes only Text and Number data type, while some
commercial programs use other datatypes like Date and Time etc. The ANSI data types are
listed in the following Table 12.1
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 202 22-12-2022 11:54:46
Data Type Description
char Fixed width string value. Values of this type is enclosed in single quotes.
(Character) For ex. Anu’s will be written as ‘Anu’ ‘s’.
Variable width character string. This is similar to char except the size of the
varchar
data entry vary considerably.
It represents a fractional number such as 15.12, 0.123 etc. Here the size
argument consist of two parts : precision and scale. The precision indicates
dec (Decimal) how many digits the number may have and the scale indicates the maximum
number of digits to the right of the decimal point. The size (5, 2) indicates
precision as 5 and scale as 2. The scale cannot exceed the precision.
It is same as decimal except that the maximum number of digits may not
numeric
exceed the precision argument.
int It represents a number without a decimal point. Here the size argument is
(Integer) not used.
smallint It is same as integer but the default size may be smaller than Integer.
It is same as float, except the size argument is not used and may define a
real
precision up to a maximum of 64.
Tables are the only way to store data, therefore all the information has to be arranged in
the form of tables. The SQL provides a predetermined set of commands to work on databases.
Keywords They have a special meaning in SQL. They are understood as instructions.
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.
Arguments They are the values given to make the clause complete.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 203 22-12-2022 11:54:46
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 :
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:
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 204 22-12-2022 11:54:46
The syntax for a table created with constraint is given as below:
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
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 205 22-12-2022 11:54:47
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.
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.
12.7.2.3 DEFAULT Constraint
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 206 22-12-2022 11:54:47
Example showing DEFAULT Constraint in the student table:
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.
12.7.2.4 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 PRIMARY KEY
Name char(20)NOT NULL,
Gender char(1),
Age integer CHECK (Age <=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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 207 22-12-2022 11:54:47
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.
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
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:
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 208 22-12-2022 11:54:47
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 209 22-12-2022 11:54:47
12.7.3.3 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:
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 210 22-12-2022 11:54:47
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 <table-name> MODIFY<column-name><data type><size>;
For example to rename the column Address to City, the command is used as :
ALTER TABLE Student CHANGE Address City char(20);
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 <table-name> DROP COLUMN <column-name>;
To remove the column City from the Student table, the command is used as :
For example to delete all the records of the student table and delete the table the SQL statement
is given as follows:
TRUNCATE TABLE Student;
The table Student is removed and the space is freed.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 211 22-12-2022 11:54:47
The table can be deleted by DROP TABLE command in the following way:
The DELETE command deletes only the rows from the table based on
the condition given in the where clause or deletes all the rows from the
DELETE
table if no condition is specified. But it does not free the space containing
the table.
The TRUNCATE command is used to delete all the rows, the structure
TRUNCATE
remains in the table and free the space containing the table.
The DROP command is used to remove an object from the database. If you
DROP drop a table, all the rows in the table is deleted and the table structure is
removed from the database. Once a table is dropped we cannot get it back.
SELECT <column-list>FROM<table-name>;
• Table-name is the name of the table from which the information is retrieved.
For example to view only admission number and name of students from the Student table the
command is given as follows:
If the Student table has the following data:
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 212 22-12-2022 11:54:47
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;
12.7.5.1 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 :
Place
Chennai
Bangalore
Delhi
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 213 22-12-2022 11:54:47
12.7.5.2 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 eliminating 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᾿;
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 214 22-12-2022 11:54:47
can also be used to connect search conditions in the WHERE clause. For example :
SELECT Admno, Name, Age, Place FROM Student WHERE (Age>=18 AND Place = ῾Delhi᾿);
The NOT BETWEEN is reverse of the BETWEEN operator where the records not satisfying
the condition are displayed.
SELECT Admno, Name, Age FROM Student WHERE Age NOT BETWEEN 18 AND 19;
12.7.5.4 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.
For example :
SELECT Admno, Name, Place FROM Student WHERE Place IN (῾Chennai᾿, ῾Delhi᾿);
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 215 22-12-2022 11:54:47
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 Place
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 216 22-12-2022 11:54:47
For example :
To display the students in alphabetical order of their names, the command is used as
Note
The ORDER BY clause does not affect the original table.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 217 22-12-2022 11:54:47
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 218 22-12-2022 11:54:47
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.
Place count
Chennai 2
The above output shows the no. of students belongs to chennai.
COMMIT;
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 219 22-12-2022 11:54:47
12.7.6.3 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;
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 220 22-12-2022 11:54:47
INSERT INTO Student VALUES(108, 'Jisha', 'F', 19, 'Delhi');
SAVEPOINT B;
ROLLBACK TO A;
Points to remember:
• SQL is a language that helps to create and operate relational databases.
• MySQL is a database management system.
• The various components of SQL are Data Definition Language (DDL), Data
Manipulation Language (DML), Data Query Language (DQL), Transactional
Control Language (TCL), Data Control Language (DCL).
• The DDL provides statements for creation and deletion of tables.
• The DML provides statements to insert, update and delete data of a table.
• The DCL provides authorization commands to access data.
• The TCL commands are used to manage transactions in a database.
• The DQL commands help to generate queries in a database.
• The CREATE TABLE command creates a new table.
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 221 22-12-2022 11:54:47
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.
Evaluation
Part - I
Part -II
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 222 22-12-2022 11:54:47
Part -III
Part -IV
www.freetnbooks.com
12th Computer Science_EM Chapter 12.indd 223 22-12-2022 11:54:47
CHAPTER 13
Unit IV
PYTHON AND CSV FILES
Learning Objectives
13.1 Introduction
Python has a vast library of modules that are included with its distribution. One among
the module is the CSV module which gives the Python programmer the ability to parse CSV
(Comma Separated Values) files. A CSV file is a human readable text file where each line
has a number of fields, separated by commas or some other delimiter. You can assume each
line as a row and each field as a column. The CSV module will be able to read and write the vast
majority of CSV files.
13.2 Difference between CSV and XLS file formats
The difference between Comma-Separated Values (CSV) and eXceL Sheets(XLS) file
formats is
Excel CSV
Excel is a binary file that holds information CSV format is a plain text format with a
about all the worksheets in a file, including series of values separated by commas.
both content and formatting
XLS files can only be read by applications CSV can be opened with any text editor
that have been especially written to read their in Windows like notepad, MS Excel,
format, and can only be written in the same OpenOffice, etc.
way.
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv
Excel consumes more memory while Importing CSV files can be much faster, and
importing data it also consumes less memory
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 224 23-12-2022 15:39:36
Files saved in excel cannot be opened or edited by text editors.
CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
Since they're plain text, they're easier to import into a spreadsheet or another storage database,
regardless of the specific software you're using.
You can open CSV files in a spreadsheet program like Microsoft Excel or in a text editor
or through a database which make them easier to read.
Note
CSV File cannot store charts or graphs. It stores data but does not contain
formatting, formulas, macros, etc.
A CSV file is also known as a Flat File. Files in the CSV format can be
imported to and exported from programs that store data in tables, such as Microsoft
Excel or OpenOfficeCalc
13.4 Creating a CSV file using Notepad (or any text editor)
A CSV file is a text file, so it can be created and edited using any text editor, But more
frequently a CSV file is created by exporting a spreadsheet or database in the program that
created it.
Save this content in a file with the extension .csv . You can then open the same using
Microsoft Excel or any other spreadsheet program. Here we have opened using Microsoft
Excel. It would create a table of data similar to the following:
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 225 23-12-2022 15:39:36
Topic1 Topic2 Topic3
In the above CSV file, you can observe the fields of data were separated by commas. But
what happens if the data itself contains commas in it?
If the fields of data in your CSV file contain commas, you can protect them by enclosing
those data fields in double-quotes (“). The commas that are part of your data will then be kept
separate from the commas which delimit the fields themselves.
To retain the commas in “Address” column, you can enclose the fields in quotation
marks. For example:
RollNo, Name, Address
12101, Nivetha, “Mylapore, Chennai”
12102, Lavanya, “Adyar, Chennai”
12103, Ram, “Gopalapuram, Chennai”
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
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 226 23-12-2022 15:39:36
Roll No Name Address
12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai
The same goes for newlines (display data in more than one line example Address
column) 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
Mylapore,
12101 Nivetha
Chennai
Adyar,
12102 Lavanya
Chennai
Gopalapuram,
12103 Ram
Chennai
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 227 23-12-2022 15:39:37
The Result will look like this
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:
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 228 23-12-2022 15:39:37
Roll No Name Favorite Sports Address
12101 Nivetha "Cricket", "Football" Mylapore, Chennai
12102 Lavanya "Basketball", "Cricket" Adyar, Chennai
12103 Ram "Soccer", "Hockey" Gopalapuram, Chennai
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
aaa,bbb,ccc
zzz,yyy,xxx CRLF( Carriage Return and Line Feed)
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 229 23-12-2022 15:39:37
4. Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored. The last field in the record
must not be followed by a comma. For example: Red , Blue
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes. For example:
Red, “,”, Blue CRLF # comma itself is a field value.so it is enclosed with double quotes
Red, Blue , Green
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field
must be preceded with another double quote. For example:
““Red””, ““Blue””, ““Green”” CRLF # since double quotes is a field value it is enclosed with another
double quotes
, , White
Note
The last row in the above example (, , White ) begins with two commas because the first
two fields of that row were empty in our spreadsheet. Don't delete them — the two commas
are required so that the fields correspond from row to row. They cannot be omitted.
To create a CSV file using Microsoft Excel, launch Excel and then open the file you
want to save in CSV format. For example, below is the data contained in our sample Excel
worksheet:
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 230 23-12-2022 15:39:37
Item Name Cost - Rs Quantity Profit
Keyboard 480 12 1152
Monitor 5200 10 10400
Mouse 200 50 2000
Total Profit 13552
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 231 23-12-2022 15:39:37
Item Name, Cost-Rs, Quantity, Profit
Keyboard, 480, 12, 1152
Monitor, 5200, 10, 10400
Mouse, 200, 50, 2000
,,Total Profit =,13552
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 232 23-12-2022 15:39:37
When you want to read from or write to a file ,you need to open it. Once the reading
is over it needs to be closed. So that, resources that are tied with the file are freed. Hence, in
Python, a file operation takes place in the following order
Note
File name or the complete path name can be represented either with in “ “ or in ‘ ‘
in the open command.
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
For Example
You can specify the mode while opening a file. In mode, you can specify whether you
want to read 'r', write 'w' or append 'a' to the file. you can also specify “text or binary” in which
the file is to be opened.
The default is reading in text mode. In this mode, while reading from the file the data
would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 233 23-12-2022 15:39:37
'a' Open for appending at the end of the file without truncating it. Creates a new file
if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
f=open("sample.txt")
#equivalent to 'r' or 'rt'
f = open("sample.txt",'w') # write in text mode
f = open("image1.bmp",'r+b') # read and write in binary mode
Python has a garbage collector to clean up unreferenced objects but, one must not
rely on it to close the file.
The above method is not entirely safe. If an exception occurs when you are performing
some operation with the file, the code exits without closing the file. The best way to do this is
using the “with” statement. This ensures that the file is closed when the block inside with is
exited. You need not to explicitly call the close() method. It is done internally.
with open("test.txt",’r’) as f:
# f is file object to perform file operations
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
f = open("sample.txt")
# perform file operations
f.close()
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 234 23-12-2022 15:39:37
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
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 235 23-12-2022 15:39:37
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
As you can see in “sample2.csv” there are spaces after the delimiter due to which the
output is also displayed with spaces.
Note
By default “skipinitialspace” has a value false
The following program reads “sample2.csv” file, which contains spaces after the delimiter.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 236 23-12-2022 15:39:37
Note
A dialect is a class of csv module which helps to define parameters for
reading and writing CSV. It allows you to create, store, and re-use various formatting
parameters for your data.
SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."
3, "Work hard dream big never give up and believe yourself."
4, "Failure is the opportunity to begin again more intelligently."
5, "The successful warrior is the average man, with laser-like focus."
The following Program read “quotes.csv” file, where delimiter is comma (,) but the
quotes are within quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',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. ']
In the above program, register a dialect with name myDialect. Then, we used csv.
QUOTE_ALL to display all the characters after double quotes.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 237 23-12-2022 15:39:37
13.6.1.1.4 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)
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', newline‘=’) as f: ['RollNo', 'Name', 'City']
reader = csv.reader(f, dialect='myDialect') ['12101', 'Arun', 'Chennai']
for row in reader: ['12102', 'Meena', 'Kovai']
print(row) ['12103', 'Ram', 'Nellai']
f.close()
In the above program, a new dialects called myDialect is registered. Use the delimiter=|
where a pipe (|) is considered as column separator.
import csv
#opening the csv file which is in different location with read mode
f=open("c:\pyprg\ch13sample5.csv",'r')
#reading the File with the help of csv.reader()
readFile=csv.reader(f)
#printing the selected column
for col in readFile :
print (col[0],col[3])
f.close()
sample5.csv File in Excel
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 238 23-12-2022 15:39:37
A B C D
OUTPUT
Item Name Profit
Keyboard 1152
Monitor 10400
Mouse 2000
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.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 239 23-12-2022 15:39:37
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
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.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 240 23-12-2022 15:39:37
Item Name Cost - Rs Quantity Profit
Keyboard 480 12 1152
Monitor 5200 10 10400
Mouse 200 50 2000
Fig 13.6.4 CSV file Data for a selected column for sorting
Since the row heading is also get sorted, to avoid that the first row should be skipped.
This is can be done by using the command “next()”. The list is sorted and displayed.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 241 23-12-2022 15:39:37
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 between 0 to 3:-“))
# sorting a particular column-cost
for row in reader:
arrayValue.append(row[a])
arrayValue.sort(reverse=True)
for row in arrayValue:
print (row)
F.close()
OUTPUT
Enter the column number between 0 to 3:- 2
50
12
10
Read a specific column in a csv file and display its result in Ascending
order
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 242 23-12-2022 15:39:37
sample8.csv in Excel screen
sample8.csv in Notepad
ItemName ,Quantity
Keyboard, 48
Monitor,52
Mouse ,20
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 243 23-12-2022 15:39:38
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)
OUTPUT
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’, ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}
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 244
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 244 23-12-2022 15:39:38
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’, newline‘=’) as csvfile:
reader = csv.DictReader(csvfile, dialect=’myDialect’)
for row in reader:
print(dict(row))
csvfile.close()
OUTPUT
{‘ItemName’:‘Keyboard’,‘Quantity’: 48}
{‘ItemName’ :‘Monitor’:‘Quantity’:52}
{‘ItemName’: ‘Mouse’:‘Quantity’: 20}
Note
DictReader() gives OrderedDict by default in its output. An OrderedDict is a
dictionary subclass which saves the order in which its contents are added. To remove the
OrderedDict use dict().
As you know Python provides an easy way to work with CSV file and has csv module
to read and write data in the csv file. In the previous topics, You have learned how to read CSV
files in Python. In similar way, You can also write a new or edit an existing CSV files in Python.
245 Python and CSV Files
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 245 23-12-2022 15:39:38
Creating A New Normal CSV File
1
The csv.writer() function returns a writer object which converts the user’s data into
delimited strings on the given file-like object. The writerow() function 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() function of csv module having
default delimiter comma (,)
Here’s an example.
The following Python program converts a List of data to a CSV file called “Pupil.csv”
that uses, (comma) as a value separator.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 246 23-12-2022 15:39:38
Import csv
csvData = [[‘Student’, ‘Age’], [‘Dhanush’, ‘17’], [‘Kalyani’, ‘18’], [‘Ram’, ‘15’]]
with open(‘c:\pyprg\ch13\Pupil.csv’, ‘w’, newline‘=’) 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
Dhanush, 17
Kalyani, 18
Ram, 15
In the above program, csv.writer() function converts all the data in the list “csvData” to
strings and create the content as file like object. The writerows () function writes all the data in
to the new CSV file “Pupil.csv”.
Note
The writerow() function writes one row at a time. If you need to write all the data at
once you can use writerows() method.
The following program modify the “student.csv” file by modifying the value of an
existing row in student.csv
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 247 23-12-2022 15:39:38
import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, ‘r’, newline‘=’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines[3] = row
with open(‘student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile)
#writerows()method writes multiple rows to a csv file
writer.writerows(lines)
readFile.close()
writeFile.close()
When we open the student.csv file with text editor, then it will show:
1, Harshini, Chennai
2, Adhith, Mumbai
3, Meena, Bangalore
4, Krishna, 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.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 248 23-12-2022 15:39:38
import csv
row = [‘6’, ‘Sajini ‘, ‘Madurai’]
with open(‘student.csv’, ‘a’, newline‘=’) as CF: # append mode to add data at the end
writer = csv.writer(CF)
writer.writerow(row) # writerow() method write a single row of data in file
CF.close()
1, Harshini, Chennai
2, Adhith, Mumbai
3, Meena, Bangalore
4, Krishna, 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.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 249 23-12-2022 15:39:38
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’, newline‘=’) 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’, newline‘=’) as f:
writer = csv.writer(f, dialect=’myDialect’)
for row in info:
writer.writerow(row)
f.close()
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 250 23-12-2022 15:39:38
When we open “dob.csv” file, we get the 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 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.
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’, newline‘=’) 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
displays the data after one blank line in Notepad.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 251 23-12-2022 15:39:38
Note
Python’s CSV module only accepts \r\n, \n or \r as line terminator
import csv
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], [‘3’,’Pencil’]]
csv.register_dialect(‘myDialect’,delimiter = ‘|’,quotechar = ‘”’,
quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\quote.csv’, ‘w’, newline‘=’) 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:
“SNO”|“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’, newline‘=’) as CF:
fields = [‘MOUNTAIN’, ‘HEIGHT’]
w = csv.DictWriter(CF, fieldnames=fields)
w.writeheader()
w.writerows(data)
print(“writing completed”)
CF.close()
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 252 23-12-2022 15:39:38
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’, newline‘=’) as csvfile:
fieldnames = [‘Name’, ‘Grade’]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=”myDialect”)
writer.writeheader()
writer.writerows([{‘Grade’: ‘B’, ‘Name’: ‘Anu’},
{‘Grade’: ‘A’, ‘Name’: ‘Beena’},
{‘Grade’: ‘C’, ‘Name’: ‘Tarun’}])
print(“writing completed”)
“Name”|”Grade”
”Anu”|”B”
”Beena”|”A”
“Tarun”|”C”
In the above program, a custom dialect called myDialect with pipe (|) as delimiter uses
the fieldnames as headings of each column to write in a csv file. Finally, we use a DictWriter()
to write dictionary data into “grade.csv” file.
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 253 23-12-2022 15:39:38
import csv
with open(‘c:\pyprg\ch13\dynamicfile.csv’, ‘w’, newline‘=’) 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
Name?: Padma
Date of birth: 18/08/2001
Place: Kumbakonam
Do you want to enter more y/n?: n
[‘Nivethitha’, ‘12/12/2001’, ‘Chennai’]
[]
[‘Leena’, ‘15/10/2001’, ‘Nagercoil’]
[]
[‘Padma’, ‘18/08/2001’, ‘Kumbakonam’]
MS Excel output
H8 fx
>
A B C
1 Nivethitha 12/12/2001 Chennai
2
3 Leena 15/10/2001 Nagercoil
4
5 Padma 18/08/2001 Kumbakonam
6
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 254 23-12-2022 15:39:38
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 with order.
• The csv.writer() function returns a writer object which converts the user’s data into
delimited strings.
• The writerow() function 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.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 255 23-12-2022 15:39:38
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
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 256 23-12-2022 15:39:38
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
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 257 23-12-2022 15:39:38
Part - II
Part - III
Part - IV
REFERENCES
1. Python for Data Analysis, Data Wrangling with Pandas, NumPy, and IPython By
William McKinney
2. CSV File Reading and Writing - Python 3.7.0 documentation
3. https://docs.python.org
www.freetnbooks.com
12th Computer Science_EM Chapter 13.indd 258 23-12-2022 15:39:38
CHAPTER 14
Unit V
IMPORTING C++ PROGRAMS IN PYTHON
Learning Objectives
14.1 Introduction
Python and C++ are general-purpose programming language. However, Python is
quite different from C++.
Yet these two languages complement one another perfectly. Python is mostly used as a
scripting or "glue", language. That is, the top level program mostly calls routines written in C
or C++. This is useful when the logic can be written in terms of existing code (For example a
program written in C++) but can be called and manipulated through Python program.
259
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 259 23-12-2022 11:08:38
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.
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 260 23-12-2022 11:08:38
14.4 Features of Python over C++
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.
261
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 261 23-12-2022 11:08:38
Python program that contains the C++ coding can be executed through either by using
command prompt or by using run terminal.
g++ is a program that calls GCC (GNU C Compiler) and automatically links the
required C++ library files to the object code.
c:\>
c:\>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
2. In the figure 14.1 the prompt shows the "C:\>”. See that highlighted area in the above
window. To change a directory 'cd' command is used. For example to goto the directory pyprg,
type the command 'cd pyprg' in the command prompt.
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
Not”. For example the entered input number is 232 the output displayed will be “Palindrome”.
The C++ program Pali is typed in notepad and saved as pali.cpp. Same way the Python
program pycpp.py code is also typed in notepad and saved as pycpp.py.
3. To execute our program double click the run terminal change the path to the Python
folder location. The syntax to execute the Python program is
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 262 23-12-2022 11:08:38
Where,
-i input mode
For example type Python pycpp.py –i pali in the command prompt and press enter key.
If the compilation is successful you will get the desired output. Otherwise the error will be
displayed.
Note
In the execution command, the input file doesn’t require its extension. For
example, it is enough to mention just the name “pali” instead of “pali.cpp”.
Now let us will see the execution through our example pycpp.py and pali.cpp. These
two programs are stored in the folder c:\pyprg. If the programs are not located in same folder
then the complete path must be specified for the files during execution. The output is displayed
below
C:\>cd Pyprg
C:\Pyprg>
Fig 14.2
263
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 263 23-12-2022 11:08:38
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 function name would be fact (). We use modules to break down large programs
into small manageable and organized program. 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.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 264 23-12-2022 11:08:38
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
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.
14.6.2.1 Python’s sys module
This module provides access to builtin variables used by the interpreter. One among the
variable in sys module is argv
sys.argv
sys.argv is the list of command-line arguments passed to the Python program. argv
contains all the items that come via the command-line input, it's basically a list holding the
command-line arguments of the program.
To use sys.argv, import sys should be used. The first argument, sys.argv[0] contains the
name of the python program (example pali.py) and sys.argv [1]is the next argument passed to
the program (here it is the C++ file), which will be the argument passed through main (). For
example
265
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 265 23-12-2022 11:08:38
main(sys.argv[1]) The input file (C++ file) is send along with its path as a list(array)
using argv[1]. argv[0] contains the Python program which need
not be passed because by default __main__ contains source code
reference.
Name of the C++ file along with its path and without extension
variable_name1:-
in string format
For example the command to compile and execute C++ program is given below
Note
‘+’ in os.system() indicates that all strings are concatenated as a single
string Therfore give a space after each word for the above argument. For example
'g++ ' + cpp_file + ' -o ' + exe_file
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 266 23-12-2022 11:08:38
14.6.2.3.3 Python getopt module
The getopt module of Python helps you to parse (split) command-line options and
arguments. This module provides getopt() method to enable command-line argument parsing.
getopt.getopt function
This function parses command-line options and parameter list. Following is the syntax
for this method −
<opts>,<args>=getopt.getopt(argv, options, [long_options])
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 [].
>>>print(args)
[]
267
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 267 23-12-2022 11:08:38
Note
You can check out the full list of Python standard modules and what they are
for. These files are in the Lib directory inside the location where Python is installed.
if __name__=='__main__':
main(sys.argv[1:])
if __name__ == '__main__':
main (sys.argv[1:])
If the command line Python program itself is going to execute first, then __name__
contains the string " __main__". The condition if " __main__"==" __main__": is true then the
main function is called.
Note
sys.argv[1:] - get everything after the script name(file name).
sys.argv[0] is the script name (python program)
Remember “string slicing” you have studied in chapter 8.
Now let us write a Python program to read a C++ coding and execute its result. The steps
for executing the C++ program to check a given number is palindrome or not is given below
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 268 23-12-2022 11:08:38
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”.
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
269
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 269 23-12-2022 11:08:38
#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):
opts, args = getopt.getopt(argv, "i:")
for o, a in opts:
if o in "-i":
run(a)
def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
os.system('g++ ' + inp_file + ' -o ' + exe_file)
os.system(exe_file)
if __name__=='__main__':
main(sys.argv[1:])
Output 2
C:\Users\Dell>python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
Enter a positive number: 56756
The reverse of the number is: 65765
The number is not a palindrome
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 270 23-12-2022 11:08:38
Python code How does it works
import sys, os, getopt include sys , os and getopt modules to
use the required function
def main(argv): Function main() is defined and 'argv'
contains the 'input mode and the c++
program file' in the form of list i.e ['-i',
'c:\ pyprg \pali_cpp']
opts, args = getopt.getopt(argv, "i:") getopt() splits the command as option
and argument. ‘opts’ contains
[('-i', 'c:\pyprg\pali_cpp')]. Since no error
‘args’ shows []
for o, a in opts: ‘o’ contains the mode and ‘a’ contains the
path of c++ program i.e
print("o = ",o) shows o = -i
print("a = ",a) shows a = c:\pyprg\pali_cpp
if o in ("-i"): Checks o == ‘i’ if true
run(a) Calls the function run() passed along
with the c++ program
def run(a): Definition of run() function begins here
inp_file=a+'.cpp' Variable ‘inp_file’ contains the joined c++
program name and .cpp
print( inp_file) shows c:\pyprg\pali_cpp.cpp
exe_file=a+'.exe' Variable ’exe_file’ contains the joined c++
program name and .exe
print( exe_file) shows c:\pyprg\pali_cpp.exe
os.system('g++ ' + inp_file + ' -o ' + exe_file) g++ compiler compiles the c++ program
in inp_file and store the executable file in
exe_file
os.system(exe_file) Executes the exe file
if __name__=='__main__': __name__ stores name of the python
program
__ main__ also stores the name of the
python program.
main(sys.argv[1:]) If 'name' and 'main' are equal then main()
is called and passed with the command line
argument omitting the python program name
argv[1:] contains –i c:\pyprg\pali_cpp
271
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 271 23-12-2022 11:08:38
The Python script(program) is mainly used to read the C++ file along with the type
of mode like ‘i’/’o’. ‘getopt()’ Parses(splits) each value of the command line and passes the
options(values) as list to ‘opt’ and since no error ‘args’ generates empty list[]. Using ‘for loop’
the tuple in the list is unpacked - ‘o’ stores the mode and ‘a’ stores the name along with the path
of the c++ file.
The variable ‘inp_file’ store the c++ file along with its extension and ‘exe_file’ stores the
executable file with .exe extension. ‘+’ usd in this program helps to concatenate the file name
with the extensions. ‘os.system()’ along with ‘g++’ compiles the inp_file. Mode ‘o’ sends the
executable file to ‘exe_file’.
‘__name__’ variable directs the program to start from the beginning of the Python
script(zero’th line) The “main()” definition does the Parsing and calling the run(). The “run()”
invoke the “g++” compiler and creates the exe file. The system() of “os” module executes the
.exe file and the desired output will be displayed on the output screen. The file extensions are
added by the Python script so it is even possible to execute C programs.
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;
}
// Save this file as hello.cpp
# 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):
opts, args = getopt.getopt(argv, "i:")
for o, a in opts:
if o in "-i":
run(a)
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 272 23-12-2022 11:08:39
def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
os.system('g++ ' + inp_file + ' -o ' + exe_file)
os.system(exe_file)
if __name__=='__main__':
main(sys.argv[1:])
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 the beginning of
the C++ program
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
273
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 273 23-12-2022 11:08:39
Points to remember:
• 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
void Writemark(); To display the marks
Create a class called Sports with the following detail
Protected members
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
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 274 23-12-2022 11:08:39
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
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
275
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 275 23-12-2022 11:08:39
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
Part - III
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 276 23-12-2022 11:08:39
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
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
277
Importing C++ Programs in Python
www.freetnbooks.com
12th Computer Science_EM Chapter 14.indd 277 23-12-2022 11:08:39
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 application software 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 within 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 ()
• 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.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 278 23-12-2022 15:33:41
• 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
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.
279
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 279 23-12-2022 15:33:41
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 Rollno 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.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 280 23-12-2022 15:33:41
Example 15.3.2 -1
import sqlite3
cursor = connection.cursor()
sql_command = """
cursor.execute(sql_command)
cursor.execute(sql_command)
cursor.execute(sql_command)
connection.commit()
connection.close()
OUTPUT
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
Academy.db and a table Student. We have a list with data of persons which will be used in the
INSERT statement:
281
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 281 23-12-2022 15:33:41
Example 15.3.2-2
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
In the above program {gr} is a place holder (variable) to get the value.
format_str.format() is a function used to format the value to the required datatype.
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
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 Tuples.
XII Std Computer Science 282
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 282 23-12-2022 15:33:41
If you run the program 15.4.1-1, 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 15.4.1-1
#save the file as “sql_Academy_query.py”
import sqlite3
connection = sqlite3.connect("Academy.db")
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)
Example 15.4.1.1-2
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')
(6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
283
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 283 23-12-2022 15:33:41
Note
cursor.fetchall() -fetchall () method is to fetch all rows from the database table
cursor.fetchone() - The fetchone () method returns the next row of a query result set or
None in case there is no row left.
cursor.fetchmany() method that returns the next number of rows (n) of the result set
Example 15.4.1.2-1
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student")
print("\nfetch one:")
res = cursor.fetchone()
print(res)
OUTPUT
fetch one:
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
Example 15.4.1.3 -1
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')
print(result) (6, 'PRIYA', 'A', 'F', 98.6, '2002-01-01')
result = cursor.fetchone() (7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 284 23-12-2022 15:33:41
15.4.1.4 Displaying Specified number of records using fetchmany(n)
Displaying specified number of records is done by using fetchmany(n). This method
returns the number of rows of the result set.
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')]
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") # * is used for unpacking a tuple.
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
elements in new lines or separated by space use sep= "\n" or sep= "," respectively.
285
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 285 23-12-2022 15:33:41
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
Example 15.4.2.1-1
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 example displays 7 records instead of 4,
since in the original table there are actually 7 records and some are with the duplicate values.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 286 23-12-2022 15:33:41
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
('B',)
('A',)
('C',)
('D',)
Example 15.4.2.3 -1
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)
287
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 287 23-12-2022 15:33:41
Example 15.4.2.4 -1
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno,sname FROM student Order BY sname")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(6, 'PRIYA')
(4, 'SAJINI')
(7, 'TARUN')
(5, 'VARUN')
The WHERE clause can be combined with AND, OR, and NOT operators. The AND
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”
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 288 23-12-2022 15:33:41
Example for WHERE WITH NOT Operator
Example 15.5 -1
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM student where NOT Grade='A' and NOT
Grade='B'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno, Sname, 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)
289
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 289 23-12-2022 15:33:41
Example 15.5 -3
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno, Sname FROM student WHERE (Average<60
OR Average>70)")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(4, 'SAJINI')
(5, 'VARUN')
(6, 'PRIYA')
In this example we are going to display the rollno, name and grade of students who have
born in the year 2001
Example 15.6 -1
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT Rollno, Sname, grade FROM student
WHERE(Birth_date>='2001-01-01' AND Birth_date<='2001-12-31')")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay', 'B')
(5, 'VARUN', 'B')
These functions are used to do operations from the values of the column and a single
value is returned.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 290 23-12-2022 15:33:41
• 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 15.7.1-1
EXAMPLE 15.7.1-2
Output:
[(7,)]
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
291
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 291 23-12-2022 15:33:41
15.7.2AVG():
The following SQL statement in the python program finds the average mark of all
students.
Example 15.7.2-1
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 15.7.1-3
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
NULL values are ignored.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 292 23-12-2022 15:33:41
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 15.7.4-1
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)]
293
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 293 23-12-2022 15:33:41
Example 15.8 -1
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.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 294 23-12-2022 15:33:41
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 15.9-1
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')
295
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 295 23-12-2022 15:33:41
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 15.10 -1
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 296 23-12-2022 15:33:41
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. Use placeholders instead of SQL literals). The sqlite3 module
supports two kinds of placeholders: question marks? (“qmark style”) and named
placeholders :name (“named style”).
297
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 297 23-12-2022 15:33:41
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 “Appointment” which contain the details of students Rollno, Duty, Age is
created. The tables “student” and “Appointment” are joined and displayed the result with the
column headings.
Example 15.11-1
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
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. From index
1 onwards the values of the column(Records) are refered. Using this command you can
display the table’s Field names.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 298 23-12-2022 15:33:41
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 15.12 -1
import sqlite3
import csv
# CREATING CSV FILE
d=open('c:/pyprg/sql.csv','w, newline= ' ')
c=csv.writer(d)
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
299
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 299 23-12-2022 15:33:41
Example 15.12 -2 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 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', newline= ' ')
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()
Note
By default while writing in a csv file each record ends with \n (newline) to
eliminate this newline replace () is used during the reading of csv file.
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 300 23-12-2022 15:33:41
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
To show (display) the list of tables created in a database the following program (Example
15.3 – 1) can be used.
Example 15.3 – 1
import sqlite3
con = sqlite3.connect('Academy.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
OUTPUT
[('Student',), ('Appointment',), ('Person',)]
301
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 301 23-12-2022 15:33:42
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.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 302 23-12-2022 15:33:42
Hands on Experience
1. Create an interactive program to accept the details from user and store it in a csv file using
Python for the following table.
Database name;- DB1
Table name : Customer
2. Consider the following table GAMES. Write a python program to display the records for
question (i) to (v)
Table: GAMES
(i) To display the name of all Games with their Gcodes in descending order of their schedule
date.
(ii) To display details of those games which are having Prize Money more than 7000.
(iii) To display the name and gamename of the Players in the ascending order of Gamename.
(iv) To display sum of PrizeMoney for each of the Numberof participation groupings (as
shown in column Number 4)
(v) Display all the records based on GameName
303
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 303 23-12-2022 15:33:42
Evaluation
Part - I
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 304 23-12-2022 15:33:42
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
1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
305
Data Manipulation Through SQL
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 305 23-12-2022 15:33:42
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 :-
Rate :- Integer
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40
References
1. The Definitive Guide to SQLite by Michael Owens
2. Programming for Beginners: 2 Manuscripts: SQL & Python by Byron Francis
3. Tutorialspoint.com
www.freetnbooks.com
12th Computer Science_EM Chapter 15.indd 306 23-12-2022 15:33:42
CHAPTER 16
Unit V DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART
Learning Objectives
307
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 307 23-12-2022 11:35:36
• It makes complex data understandable and usable.
• Various Charts in Data Visualization helps to show relationship in the data for one or more
variables.
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 Package manager software for installing
python packages.
308
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 308 23-12-2022 11:35:36
Note
Detailed installation procedures given in Annexure - II
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() function 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
Figure 16.1
309
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 309 23-12-2022 11:35:36
You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you
provide a single list or array to the plot () command, matplotlib assumes it is a sequence of y
values, and automatically generates the x values for you. Since python ranges start with 0, the
default x vector has the same length as y but starts with 0. Hence the x data are [0, 1, 2, 3].
plot() is a versatile command, and will take an arbitrary number of arguments.
Program
This .plot takes many arguments, but the first two here are 'x' and 'y' coordinates. This
means, you have 4 co-ordinates according to these lists: (1,1), (2,4), (3,9) and (4,16).
16
14
12
10
Figure 16.2
310
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 310 23-12-2022 11:35:36
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
X - Axis
Figure 16.3
311
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 311 23-12-2022 11:35:36
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
Figure 16.4
Home Button → The Home Button will help once you have begun navigating your chart. If
you ever want to return back to the original view, you can click on this.
Forward/Back buttons → These buttons can be used like the Forward and Back buttons in
your browser. You can click these to move back to the previous point you were at, or forward
again.
Pan Axis → This cross-looking button allows you to click it, and then click and drag your
graph around.
Zoom → The Zoom button lets you click on it, then click and drag a square that you would like
to zoom into specifically. Zooming in will require a left click and drag. You can alternatively
zoom out with a right click and drag.
Configure Subplots → This button allows you to configure various spacing options with your
figure and plot.
Save Figure → This button will allow you to save your figure in various forms.
Matplotlib allows you to create different kinds of plots ranging from histograms and
scatter plots to bar graphs and bar charts.
Line Chart
A Line Chart or Line Graph is a type of chart which displays information as a series of
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.
312
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 312 23-12-2022 11:35:37
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
8955000
Total Population
8950000
8945000
8940000
Figure 16.5
Bar Chart
A BarPlot (or BarChart) is one of the most common type of plot. It shows the
relationship between a numerical data and a categorical values.
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.
313
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 313 23-12-2022 11:35:37
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
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 314 23-12-2022 11:35:37
Bar Graph and Histogram are the two ways to display data in the form of a diagram.
Example
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
plt.show()
315
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 315 23-12-2022 11:35:37
Output
English
Tamil
18.43
20.51
Maths 20.74
17.28
23.04 Social
Science
Figure 16.7
Hands on Practice
1. Plot a line chart for the given data and set the title for x and y axis.
Average Pulse: 80, 85, 90, 95, 100
Calorie Burnage: 240, 250, 260, 270, 280
4. Plot a bar chart for the number of computer science periods in a week.
316
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 316 23-12-2022 11:35:37
Evaluation
Part - I
317
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 317 23-12-2022 11:35:37
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
318
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 318 23-12-2022 11:35:37
Part - II
Part - III
319
Data Visualization using Pyplot
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 319 23-12-2022 11:35:37
Part - IV
Reference
1. https://towards datascience.com / data - science - with - python - intro -to- data
-visualization-and-matplotlib-5f799b7c6d82.
2. https://heartbeat.fritz.ai/introduction-to-matplotlib-data-visualization-in-python-
d9143287ae39.
3. https://python programming.net / legends - titles - labels - matplotlib - tutorial/?
completed=/matplotlib-intro-tutorial/.
4. https://keydifferences.com/difference-between-histogram-and-bar-graph.html.
320
XII Std Computer Science
www.freetnbooks.com
12th Computer Science_EM Chapter 16.indd 320 23-12-2022 11:35:37
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
Alternative One of two choices
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
create a database connection to the SQLite database
‘test.db’. You can also supply the special name :memory:
c = sqlite3.connect('test. db') 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
Executes all SQL commands .Accepts two kinds of
placeholders: question marks ? (“qmark style”) and
c.execute() 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
321
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 321 23-12-2022 11:35:04
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
elif else…if
Embedded Firmly attached
Enter key Enter key or newline is used to create rows in a csv file
322
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 322 23-12-2022 11:35:04
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
tuple that are in both A and B.
Key Data that is mapped to a value in a dictionary
323
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 323 23-12-2022 11:35:04
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
same arguments are passed in
Python prompt >>>
324
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 324 23-12-2022 11:35:04
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
string sequence of letters, numbers or symbols
subscript an index number
325
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 325 23-12-2022 11:35:05
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
326
www.freetnbooks.com
12th Std - CS EM Glossary Pages.indd 326 23-12-2022 11:35:05
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
next() Retrieves Next Element from Iterator
object() Creates a Featureless Object
oct() converts integer to octal
327
341
www.freetnbooks.com
12th Std - CS
Annexure I &EM Annexure
2.indd 341 Pages.indd 327 23-12-2022 14:35:27
20-02-2019 13:16:59
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
www.freetnbooks.com
Annexure
12th StdI-&CS2.indd 342
EM Annexure Pages.indd 328 20-02-2019
23-12-202214:35:27
13:16:59 Anne
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
329
343
www.freetnbooks.com
Annexure
12th Std - CS
I &EM
2.indd
Annexure
343 Pages.indd 329 20-02-2019
23-12-2022 14:35:27
13:16:59
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.
344
330
www.freetnbooks.com
Annexure
12th Std - ICS
& EM
2.indd 344 Pages.indd 330
Annexure 20-02-2019
23-12-2022 14:35:27
13:16:59
PRACTICAL EXERCISES
331
www.freetnbooks.com
12th Computer Science_EM Practical.indd 331 26-12-2022 17:50:31
Computer Science
Practical Guide
Instructions:
1. Eight exercises from Python and two exercises from MySQL are practiced in the
practical classes
3. Distribution of Marks
Total 20 Marks
332
www.freetnbooks.com
12th Computer Science_EM Practical.indd 332 26-12-2022 17:50:31
INDEX
Question Page
S No Program Name
Number Number
333
www.freetnbooks.com
12th Computer Science_EM Practical.indd 333 26-12-2022 17:50:31
PY1(a) – Calculate Factorial
Write a program to calculate the factorial of the given number using for loop (Don’t
1(a)
use built-in function factorial).
Aim: To calculate the factorial of the given number using for loop.
Coding:
Enter a Number: 5
Factorial of 5 is 120
Result:
Thus the Python program to calculate factorial has been done and the output is verified.
1(b) Write a program to sum the series 11 /1 + 22/2 + 33/3 + ……. nn/n
Aim
To calculate the sum of the series : 11 /1 + 22/2 + 33/3 + ……. nn/n
Coding:
Enter a value of n: 4
The sum of the series is 76
334
www.freetnbooks.com
12th Computer Science_EM Practical.indd 334 26-12-2022 17:50:31
PY2(a) – Odd or Even
2(a) Write a program using functions to check whether a number is even or odd.
Aim: To check whether a number is even or odd using user defined function.
Coding:
def oddeven(a):
if (a%2==0):
return "Even"
else:
return "Odd"
num = int(input("Enter a number: "))
print("The given number is ", oddeven(num))
Output:
Enter a number: 7
The given number is Odd
Enter a number: 6
The given number is Even
Result:
Thus the Python program to check whether a number is odd or even has been done and the
output is verified.
PY2(b) – Reverse the string
Coding:
def reverse(str1):
str2=''
for i in str1:
str2 = i + str2
return str2
word = input("\n Enter a String: ")
print("\n The reverse of the given string is: ", reverse(word))
335
www.freetnbooks.com
12th Computer Science_EM Practical.indd 335 26-12-2022 17:50:31
Output:
Thus the Python program to reverse the string has been done and the output is verified.
Write a program to generate values from 1 to 10 and then remove all the odd
3 numbers from the list.
Aim: To generate values from 1 to 10 and then remove all the odd numbers from the list.
Coding:
num = list(range(1,11))
print("Numbers from 1 to 10.....\n",num)
for i in num:
if(i%2 == 1):
num.remove(i)
print("The values after removing odd numbers.....\n",num)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The values after removed odd numbers.....
[2, 4, 6, 8, 10]
Result:
Thus the Python program to generate values from 1 to 10 and then remove all the odd numbers
from the list has been done and the output is verified.
336
www.freetnbooks.com
12th Computer Science_EM Practical.indd 336 26-12-2022 17:50:31
PY4 – Generate prime numbers and set operations
Write a Program that generate a set of prime numbers and another set of odd
4. numbers. Display the result of union, intersection, difference and symmetric
difference operations.
Aim: To generate a set of prime numbers and another set of odd numbers, and to display
the result of union, intersection, difference and symmetric difference operations.
Coding:
odd = set(range (1,10,2))
prime=set()
for i in range(2,10):
for j in range (2,i):
if (i%j==0):
break
else:
prime.add(i)
print("Odd Numbers: ", odd)
print("Prime Numbers: ", prime)
print("Union: ", odd.union(prime))
print("Intersection: ", odd.intersection(prime))
print("Difference: ", odd.difference(prime))
Thus the Python program to generate prime numbers and set operations has been done and
the output is verified.
337
www.freetnbooks.com
12th Computer Science_EM Practical.indd 337 26-12-2022 17:50:32
PY5 – Display a string elements – using class
Aim: o accept a string and print the number of uppercase, lowercase, vowels, consonants
T
and spaces in the given string using Class.
Coding:
class String:
def __init__(self):
self.upper=0
self.lower=0
self.vowel=0
self.consonant=0
self.space=0
self.string=""
def getstr(self):
self.string=str(input("Enter a String: "))
def count(self):
for ch in self.string:
if (ch.isupper()):
self.uppercase+=1
if (ch.islower()):
self.lowercase+=1
if (ch in ('AEIOUaeiou')):
self.vowel+=1
if (ch==""):
self.spaces+=1
self.consonant=self.upper+self.lower-self.vowel
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%self.upper)
print("%d Lowercase letters"%self.lower)
print("%d Vowels"%self.vowel)
print("%d Consonants"%self.consonant)
print("%d Spaces"%self.space)
338
www.freetnbooks.com
12th Computer Science_EM Practical.indd 338 26-12-2022 17:50:32
S = String()
S.getstr()
S.execute()
S.display()
Output:
Thus the Python program to display a string elements – using class has been done and the
output is verified.
339
www.freetnbooks.com
12th Computer Science_EM Practical.indd 339 26-12-2022 17:50:32
DB6 – MySQL – Employee table
Create an Employee Table with the fields Empno, Empname, Desig, Dept, Age
6. and Place. Enter five records into the table.
Add two more records to the table.
● Modify the table structure by adding one more field namely date of joining.
● Check for Null value in doj of any record.
● List the employees who joined after 01/01/2018.
Aim:
(1) To Create employee table with Empno, Empname, Desig, Dept, Age and Place fields.
(2) Insert five records
(3) Add two more records
(4) Modify table structure
(5) Check for NULL values
(6) List required subset of records
SQL QUERIES AND OUTPUT:
(i) Creating Table Employee
340
www.freetnbooks.com
12th Computer Science_EM Practical.indd 340 26-12-2022 17:50:32
(iii) Inserting Data into Table:
mysql> Insert into employee values(1221, 'Sidharth', 'Officer', 'Accounts', 45, 'Salem');
mysql> Insert into employee values(1222, 'Naveen', 'Manager', 'Admin', 32, 'Erode');
mysql> Insert into employee values(1223, 'Ramesh', 'Clerk', 'Accounts', 33, 'Ambathur');
mysql> Insert into employee values(1224, 'Abinaya', 'Manager', 'Admin', 28, 'Anna Nagar');
mysql> Insert into employee values(1225, 'Rahul', 'Officer', 'Accounts', 31, 'Anna Nagar');
mysql> Insert into employee values(3226, 'Sona', 'Manager', 'Accounts', 42, 'Erode');
mysql> Insert into employee values(3227, 'Rekha', 'Officer', 'Admin', 34, 'Salem');
341
www.freetnbooks.com
12th Computer Science_EM Practical.indd 341 26-12-2022 17:50:32
(vi) Adding one more Field:
342
www.freetnbooks.com
12th Computer Science_EM Practical.indd 342 26-12-2022 17:50:32
(viii) Checking null value in doj
343
www.freetnbooks.com
12th Computer Science_EM Practical.indd 343 26-12-2022 17:50:32
DB7 - MySQL – Student table
7 Create a table with following fields and enter data as given in the table below.
Reg_No char 5
Sname varchar 15
Age int 2
Dept varchar 10
Class char 3
Data to be entered :
344
www.freetnbooks.com
12th Computer Science_EM Practical.indd 344 26-12-2022 17:50:32
SQL QUERIES AND OUTPUT
mysql> Insert into Student values ('M1001', 'Harish', 19, 'ME', 'ME1');
mysql> Insert into Student values ('M1002', 'Akash', 20, 'ME', 'ME2');
mysql> Insert into Student values ('C1001', 'Sneha', 20, 'CSE', 'CS1');
mysql> Insert into Student values ('C1002', 'Lithya', 19, 'CSE', 'CS2');
mysql> Insert into Student values ('E1001', 'Ravi', 20, 'ECE', 'EC1');
mysql> Insert into Student values ('E1002', 'Leena', 21, 'EEE', 'EE1');
mysql> Insert into Student values ('E1003', 'Rose', 20, 'ECE', 'EC2');
345
www.freetnbooks.com
12th Computer Science_EM Practical.indd 345 26-12-2022 17:50:32
Reg_No Sname Age Dept Class
346
www.freetnbooks.com
12th Computer Science_EM Practical.indd 346 26-12-2022 17:50:32
(iii) List the students department wise:
347
www.freetnbooks.com
12th Computer Science_EM Practical.indd 347 26-12-2022 17:50:32
(v) Check for the uniqueness of Register no.
Reg_No
M1001
M1002
C1001
C1002
E1001
E1002
E1003
348
www.freetnbooks.com
12th Computer Science_EM Practical.indd 348 26-12-2022 17:50:32
PY8 – Python with CSV
8 Write a program using python to get 10 players name and their score. Write the
input in a csv file. Accept a player name using python. Read the csv file to
display the name and the score. If the player name is not found give an appropriate
message.
Aim: To get 10 players name and their score. Write the input in a csv file. Accept a player
name using python. Read the csv file to display the name and the score. If the player
name is not found give an appropriate message.
Coding:
import csv
with open('c:\\pyprg\\player.csv', 'w', newline=’’ ) as f:
w = csv.writer(f)
n=1
while (n<=10):
name = input("Player Name?:" )
score = int(input("Score: "))
w.writerow([name,score])
n+=1
print("Player File created")
f.close()
searchname=input("Enter the name to be searched ")
f=open('c:\\pyprg\\player.csv','r')
reader =csv.reader(f)
lst=[]
for row in reader:
lst.append(row)
q=0
for row in lst:
if searchname in row:
349
www.freetnbooks.com
12th Computer Science_EM Practical.indd 349 26-12-2022 17:50:32
print(row)
q+=1
if(q==0):
print("string not found")
f.close()
f.close()
Output:
350
www.freetnbooks.com
12th Computer Science_EM Practical.indd 350 26-12-2022 17:50:32
PY9 – Python with SQL
9 Create a sql table using python and accept 10 names and age .sort in descending
order of age and display.
Aim: To create a sql table using python and accept 10 names and age. sort in descending
order of age and display.
Coding:
import sqlite3
connection = sqlite3.connect("info.db")
cursor = connection.cursor()
for i in range(10):
n =len(who)
for i in range(n):
print("Displaying All the Records From student Table in Descending order of age")
print (*cursor.fetchall(),sep='\n' )
351
www.freetnbooks.com
12th Computer Science_EM Practical.indd 351 26-12-2022 17:50:32
Output:
352
www.freetnbooks.com
12th Computer Science_EM Practical.indd 352 26-12-2022 17:50:32
PY10 – Python Graphics with Pip
10 Write a program to get five marks using list and display the marks in pie chart.
Aim: To get five marks using list and display the marks in pie chart using matplot.
Coding:
importmatplotlib.pyplot as plt
marks=[]
i=0
subjects = ["Tamil", "English", "Maths", "Science", "Social"]
while i<5:
marks.append(int(input("Enter Mark = ")))
i+=1
for j in range(len(marks)):
print("{}.{} Mark = {}".format(j+1, subjects[j],marks[j]))
plt.show()
Output:
English
Enter Mark = 67
Tamil
Enter Mark = 31 10.16
21.97
Enter Mark = 45
Maths 14.75
Enter Mark = 89
23.93
Enter Mark = 73 29.18 Social
1.Tamil Mark = 67
Science
2.English Mark = 31
3.Maths Mark = 45
4.Science Mark = 89
5.Social Mark = 73
353
www.freetnbooks.com
12th Computer Science_EM Practical.indd 353 26-12-2022 17:50:32
COMPUTER SCIENCE – XII
List of Authors and Reviewers
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. Dr. Vidhya H
Anna University, Chennai Post Graduate Teacher,
DAV Boys Senior Secondary School,
Content Expert Gopalapuram, Chennai.
Layout
THY designers and computers
Chennai
Typist
In-House
Mrs. Meena T
SCERT, Chennai.
QC - Rajesh Thangapan
- Mathan Raj R
- Balasubramani. R
- Wrapper Design - Kathir Arumugam
Co-ordination
Ramesh Munisamy
This book has been printed on 80 G.S.M.
Elegant Maplitho paper.
354
www.freetnbooks.com
12th Computer Science_EM Practical.indd 354 26-12-2022 17:50:32