12th Computer Science EM Text WWW - Tntextbooks.in
12th Computer Science EM Text WWW - Tntextbooks.in
in
GOVERNMENT OF TAMILNADU
HIGHER SECONDARY
SECOND YEAR
COMPUTER SCIENCE
Content Creation
The wise
possess all
II
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
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.tntextbooks.in
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.tntextbooks.in
23-12-2022 13:19:01
www.tntextbooks.in
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
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:
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
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
5 Function
monochromatize (a, b, c)
Now let’s see the example of a pure
function to determine the greatest common
-- inputs : a = A, b = B, c = C, a = b
divisor (gcd) of two positive integer numbers.
-- outputs : a = b = 0, c = A+B+C
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) 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
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
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
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
Part - IV
REFERENCES
CHAPTER 2
Unit I
DATA ABSTRACTION
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
city value passed as parameter city value passed as parameter city value passed as parameter
13 Data Abstraction
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
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
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
Points to remember:
• A concrete data type is a data type whose representation is known and in abstract data
type the representation of a data type is unknown
• Pair is a compound structure which is made up of list or Tuple
• List is constructed by placing expressions within square brackets separated by commas
• The elements of a list can be accessed in two ways. The first way is via multiple
assignment and the second method is by the element selection operator
• Bundling two values together into one can be considered as a pair
• List does not allow to name the various parts of a multi-item object.
Evaluation
Part - I
Part - II
Part - III
19 Data Abstraction
Part - IV
Reference Books
1. Data structure and algorithmic thinking with python by narasimha karumanchi
2. sign and analysis of algorithms by s sridhar
3. Data Structures and Algorithms in Python by Goodrich, Tamassia & Goldwasser
4. https://www.tutorialspoint.com
CHAPTER 3
Unit I
SCOPING
21
BUILT-IN
GLOBAL
ENCLOSED
LOCAL
2. a:=7 7
Disp( ):
3. print a a:=7
print a
4. Disp() Disp ( )
23 Scoping
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()
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
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-
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
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
Part - II
Part - III
29 Scoping
Part - IV
REFERENCES
CHAPTER 4
Unit I
ALGORITHMIC STRATEGIES
31
33 Algorithmic Strategies
Analysis of an algorithm usually deals with gives the running time and/or the storage
the running and execution time of various space required by the algorithm in terms of
operations involved. The running time of n as the size of input data.
an operation is calculated as how many
programming instructions executed per 4.2.1 Time Complexity
operation. The Time complexity of an algorithm
Analysis of algorithms and is given by the number of steps taken by the
performance evaluation can be divided into algorithm to complete the process.
two different phases:
4.2.2. Space Complexity
1. A Priori estimates: This is a theoretical Space complexity of an algorithm
performance analysis of an algorithm. is the amount of memory required to run
Efficiency of an algorithm is measured to its completion. The space required by
by assuming the external factors. an algorithm is equal to the sum of the
following two components:
2. A Posteriori testing: This is called
performance measurement. In this A fixed part is defined as the total
analysis, actual statistics like running space required to store certain data and
time and required for the algorithm variables for an algorithm. For example,
executions are collected. simple variables and constants used in an
algorithm.
An estimation of the time and
space complexities of an algorithm A variable part is defined as the
for varying input sizes is called total space required by variables, which sizes
algorithm analysis. depends on the problem and its iteration.
For example: recursion used to calculate
factorial of a given value n.
4.2 Complexity of an
Algorithm 4.3 Efficiency of an algorithm
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
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
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
2. Now we move on to the second element 4. This is repeated, until the array is
position, and look for smallest element completely sorted.
present in the sub-array, from starting
Let's consider an array with values {13, 16,
index to till the last index of sub - array.
11, 18, 14, 15}
3. Now replace the second smallest
identified in step-2 at the second position Below, we have a pictorial representation of
in the or original array, or also called first how selection sort will sort the given array.
position in the sub array.
11 13 16 14 14 14
18 18 18 18 15 15
14 14 14 16 16 16
15 15 15 15 18 18
In the first pass, the smallest element will be Finally we will get the sorted array
11, so it will be placed at the first position. end of the pass as shown above diagram.
Step 3 − Compare with all elements in the Step 5 − Insert the value
sorted sub-list
Step 6 − Repeat until list is sorted
Step 4 − Shift all the elements in the sorted
sub-list that is greater than the value to be
sorted
Assume 44 is a 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
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.
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
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
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
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.
CHAPTER 5
Unit II
PYTHON – VARIABLES AND OPERATORS
Learning Objectives
5.1 Introduction
47
(Or)
Example 1: Example 2:
>>> 5 + 10 >>>print (“Python Programming Language”)
15 Python Programming Language
>>>x=10
>>> 5 + 50 *10
>>>y=20
505 >>>z=x + y
>>> 5 ** 2 >>>print (“The Sum”, z)
25 The Sum = 30
b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)
(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
A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions. The input() function helps to enter data at run time
by the user and the output function print() is used to display the result of the program on the
screen after execution.
5.4.1 The print() function
In Python, the print() function is used to display result on the screen. The syntax for
print() is as follows:
Example
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
Example
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11
The print ( ) evaluates the expression before printing it on the monitor. The print
() displays an entire statement which is specified within print ( ). Comma ( , ) is used as a
separator in print ( ) to print more than one item.
Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable. If prompt string is not given in input( ) no message is
displayed on the screen, thus, the user will not know what is to be typed as input.
>>> city=input()
Rajarajan
>>> print (“I am from”, city)
I am from Rajarajan
Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input( ).
The input ( ) accepts all data as string 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
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.
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
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
Output:
This is Python
C
This is a multiline string with more than one line code.
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.”””
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
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
CHAPTER 6
Unit II
CONTROL STRUCTURES
Learning Objectives
• To learn through the syntax how to use conditional construct to improve the efficiency of
the program flow.
• To apply iteration structures to develop code to repeat the program segment for specific
number of times or till the condition is satisfied.
6.1 Introduction
Programs may contain set of statements. These statements are the executable segments
that yield the result. In general, statements are executed sequentially, that is the statements
are executed one after another. There may be situations in our real life programming where
we need to skip a segment or set of statements and execute another segment based on the test
of a condition. This is called alternative or branching. Also, we may need to execute a set of
statements multiple times, called iteration or looping. In this chapter we are to focus on the
various control structures in Python, their syntax and learn how to develop the programs
using them.
67
Sequential
Alternative or
Branching
Iterative or Looping
Example 6.1
# Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN
Syntax:
if <condition>:
statements-block1
In the above syntax if the condition is true statements - block 1 will be executed.
Example 6.2
# Program to check the age and print whether eligible for voting
x=int (input("Enter your age :"))
if x>=18:
print ("You are eligible for voting")
Output 1:
Enter your age :34
You are eligible for voting
Output 2:
Enter your age :16
>>>
As you can see in the second execution no output will be printed, only the Python
prompt will be displayed because the program does not check the alternative process when the
condition is failed.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
69 Control Structures
Entry
if condition is if condition is
true condition false
Statement Statement
block -1 block -2
Exit
Fig. 6.1 if..else statement execution
if..else statement thus provides two possibilities and the condition determines which
BLOCK is to be executed.
An alternate method to rewrite the above program is also available in Python. The
complete if..else can also written as:
Syntax:
variable = variable1 if condition else variable 2
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
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++.
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
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
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
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
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
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
Note
for loop can also take values from string, list, dictionary etc. which will be dealt
in the later chapters.
79 Control Structures
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
Enter loop
false
Condition
true
break?
yes
Exit loop
no
Remaining body of loop
81 Control Structures
The above program will repeat the iteration with the given “Jump Statement” as string.
Each letter of the given string sequence is tested till the letter ‘e’ is encountered, when it is
encountered the control is transferred outside the loop block or it terminates. As shown in the
output, it is displayed till the letter ‘e’ is checked after which the loop gets terminated.
One has to note an important point here is that ‘if a loop is left by break, the else part
is not executed’. To explain this lets us enhance the previous program with an ‘else’ part and
see what output will be:
Note that the break statement has even skipped the ‘else’ part of the loop and has
transferred the control to the next line following the loop block.
(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
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
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.
Example 6.18: Program to illustrate the use of pass statement in for loop
for val in “Computer”:
pass
print (“End of the loop, loop structure will be built in future”)
Output:
End of the loop, loop structure will be built in future.
Points to remember:
85 Control Structures
Hands on Experience
Evaluation
Part - I
Part -II
Part -III
Part -IV
CHAPTER 7
Unit II
PYTHON FUNCTIONS
Table – 7.1 – Python Functions and it's • The code block always comes after a
Description colon (:) and is indented.
Now let’s check out functions in action so you can visually see how they work within a
program. Here is an example for a simple function to display the given string.
Example: 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
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.
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
Output:
Example-1 Keyword arguments
Name :Gshan
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
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.
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
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.
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
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.
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.
Example : 7.8.2(c) C
hanging Global Variable From Inside a Function
using global keyword
x = 0 # global variable
def add():
global x
x = x + 5 # increment by 5
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5
In the above program, x is defined as a global variable. Inside the add() function, global
keyword is used for x and we increment the variable x by 5. Now We can see the change on the
global variable x outside the function i.e the value of x is 5.
In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.
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.
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
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))
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.
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)
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)
Part - II
Part - III
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from tutorialspoint.com
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert
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.
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
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.
(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 "
str1="COMPUTER"
index=0
for i in str1:
print (str1[:index+1])
index+=1
Output
C
CO
COM
COMP
COMPU
COMPUT
COMPUTE
COMPUTER
Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er
>>> print (str1[::3])
Wceoenyo
Example
>>> str1 = "Welcome to learn Python"
>>> print(str1[::-2])
nhy re teolW
Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))
Example
name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))
Output
Name: Rajarajan and Marks: 98
Example
# String within triple quotes to display a string with single quote
>>> print ('''They said, "What's there?"''')
They said, "What's there?"
# String within single quotes to display a string with single quote using escape sequence
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
# String within double quotes to display a string with single quote using escape sequence
>>> print ("They said, \"What's there?\"")
He said, "What's there?"
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
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
*
* *
* * *
* * * *
* * * * *
str1=' * '
i=1
while i<=5:
print (str1*i)
i+=1
Output
*
* *
* * *
* * * *
* * * * *
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
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
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
Part -II
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.
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]
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])
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.
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
Syntax:
for index_var in list:
print (index_var)
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].
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.
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.
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.
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.
Syntax:
List_Varibale = list ( range ( ) )
Note
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 ]
In the above example, x ** 2 in the expression is evaluated each time it is iterated. This
is the shortcut method of generating series of values.
MyList=[21,76,98,23]
Returns the maximum print(max(MyList))
max( ) max(list)
value in a list. Output:
98
MyList=[21,76,98,23]
Returns the minimum print(min(MyList))
min( ) min(list)
value in a list. Output:
21
MyList=[21,76,98,23]
Returns the sum of print(sum(MyList))
sum( ) sum(list)
values in a list. Output:
218
9.1.12 Programs using List
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))
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))
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]
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.
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’>
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)
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.
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
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
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.
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}
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'}
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'}
(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}
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'}
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 { }.
Key in the dictionary must be unique case sensitive and can be of any valid Python type.
Syntax
Dict = { expression for variable in sequence [if condition] }
The if condition is optional and if specified, only those values in the sequence are evaluated
using the expression which satisfy the condition.
Example
Note that, the first print statement prints all the values of the dictionary. Other statements
are printing only the specified values which is given within square brackets.
In an existing dictionary, you can add more values by simply assigning the value along
with key. The following syntax is used to understand adding more elements in a dictionary.
dictionary_name [key] = value/element
Modification of a value in dictionary is very similar as adding elements. When you assign
a value to a key, it will simply overwrite the old value.
In Python dictionary, del keyword is used to delete a particular element. The clear()
function is used to delete all the elements in a dictionary. To remove the dictionary, you can
use del keyword with dictionary name.
XII Std Computer Science 164
Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
Dict.clear() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary
Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{ }
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined
(2) The index values can be used to access a particular element. But, in dictionary key
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.
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.
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
Part - II
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.
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
Syntax:
Object_name = class_name( )
Note that the class instantiation uses function notation ie. class_name with ()
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
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
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)
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.
In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is defined to
show the values passed to these two variables.
The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method
defined inside the class. But, when we try to access the value of n2 from outside the class
Python throws an error. Because, private variable cannot be accessed from outside the class.
Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12
Output:
Enter Radius: 5
The Area = 78.5
The Circumference = 31.400000000000002
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
Hands on Experience
1. Write a program using class to store name and marks of students in list and print total
marks.
2. Write a program using class to accept three sides of a triangle and print its area.
3. Write a menu driven program to read, display, add and subtract two distances.
Evaluation
Part - I
Part -II
1. What is class?
2. What is instantiation?
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
4. How will you create constructor in Python?
5. What is the purpose of Destructor?
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.
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
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
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
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.
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,
• In a Network model, a child may have many parent nodes. It represents the data in many-
to-many relationships.
• This model is easier and faster to access the data.
School
Library Office Staff Room This child has one parent node
Network Model
Fig. 11.5
5. Object Model
Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance. This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing. It is used in file
Management System. It represents real world objects, attributes and behaviors. It provides a
clear modular structure. It is easy to maintain and modify the existing code.
Shape
get_area()
get_perimeter()
An example of the Object model is Shape, Circle, Rectangle and Triangle are all objects
in this model.
• Circle has the attribute radius.
• Rectangle has the attributes length and breadth.
• Triangle has the attributes base and height .
• The objects Circle, Rectangle and Triangle inherit from the object Shape.
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.
2. One-to-Many Relationship
Computer Bindhu
3. Many-to-One Relationship
4. Many-to-Many Relationship Tamil Radha
1. One-to-One Relationship
In One-to-One Relationship, one Maths Ramesh
entity is related with only one other entity.
One row in a table is linked with only one
row in another table and vice versa. Malaiarasu
STUDENT
Table 11.1
PROJECT (symbol : Π)
The projection eliminates all attributes of the input relation but those mentioned in
the projection list. The projection method defines a relation that contains a vertical subset of
Relation.
Course
Big Data
R language
Python Programming
Note
duplicate row is removed in the result
Table A Table B
Result
Table A - B
cs4 Padmaja
INTERSECTION (symbol : ∩) A ∩ B
Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.
A∩B
cs1 Kannan
cs3 Lenin
1 S 1 S
2 1 R
R
3 2 S
2 R
Table A = 3
Table B = 2 3 S
Table A x B = 3 x 2 = 6
3 R
Cartesian Product
Fig. 11.12
Table A Table B
studno name course subject
cs1 Kannan cs28 Big Data
cs2 Gowri Shankar cs62 R language
cs4 Padmaja cs25 python programming
Table 11.3
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
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
Part -II
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.
XII Std Computer Science 198
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.
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.
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.
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
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.
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.
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
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.
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.
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:
In the INSERT command the fields that are omitted will have either default value
defined or NULL value.
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.
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:
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.
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᾿;
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᾿);
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.
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.
Note
Sorting can be done on multiple fields.
Gender count(*)
M 5
F 3
Note
The * is used with the COUNT to include the NULL values.
The GROUP BY applies the aggregate functions independently to a series of groups that
are defined by having a field value in common. The output of the above SELECT statement
gives a count of the number of Male and Female students.
Place count
Chennai 2
The above output shows the no. of students belongs to chennai.
COMMIT;
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.
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
Part -III
Part -IV
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
CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
Since they're plain text, they're easier to import into a spreadsheet or another storage database,
regardless of the specific software you're using.
You can open CSV files in a spreadsheet program like Microsoft Excel or in a text editor
or through a database which make them easier to read.
Note
CSV File cannot store charts or graphs. It stores data but does not contain
formatting, formulas, macros, etc.
A CSV file is also known as a Flat File. Files in the CSV format can be
imported to and exported from programs that store data in tables, such as Microsoft
Excel or OpenOfficeCalc
13.4 Creating a CSV file using Notepad (or any text editor)
A CSV file is a text file, so it can be created and edited using any text editor, But more
frequently a CSV file is created by exporting a spreadsheet or database in the program that
created it.
Save this content in a file with the extension .csv . You can then open the same using
Microsoft Excel or any other spreadsheet program. Here we have opened using Microsoft
Excel. It would create a table of data similar to the following:
In the above CSV file, you can observe the fields of data were separated by commas. But
what happens if the data itself contains commas in it?
If the fields of data in your CSV file contain commas, you can protect them by enclosing
those data fields in double-quotes (“). The commas that are part of your data will then be kept
separate from the commas which delimit the fields themselves.
To retain the commas in “Address” column, you can enclose the fields in quotation
marks. For example:
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
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
13.4.3 Creating CSV File That contains Double Quotes With Data
If your fields contain double-quotes as part of their data, the internal quotation
marks need to be doubled so that they can be interpreted correctly. For Example, given the
following data:
2. The last record in the file may or may not have an ending line break. For example:
ppp, qqq
yyy, xxx
3. There may be an optional header line appearing as the first line of the file with the same
format as normal record lines. The header will contain names corresponding to the fields
in the file and should contain the same number of fields as the records in the rest of the
file. For example:
field_name1,field_name2,field_name3
aaa,bbb,ccc
zzz,yyy,xxx CRLF( Carriage Return and Line Feed)
4. Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored. The last field in the record
must not be followed by a comma. For example: Red , Blue
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes. For example:
Red, “,”, Blue CRLF # comma itself is a field value.so it is enclosed with double quotes
Red, Blue , Green
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field
must be preceded with another double quote. For example:
““Red””, ““Blue””, ““Green”” 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:
Python provides a module named CSV, using this you can do several operations on the
CSV files. The CSV library contains objects and other code to read, write, and process data
from and to CSV files.
When you want to read from or write to a file ,you need to open it. Once the reading
is over it needs to be closed. So that, resources that are tied with the file are freed. Hence, in
Python, a file operation takes place in the following order
Note
File name or the complete path name can be represented either with in “ “ or in ‘ ‘
in the open command.
Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
For Example
You can specify the mode while opening a file. In mode, you can specify whether you
want to read 'r', write 'w' or append 'a' to the file. you can also specify “text or binary” in which
the file is to be opened.
The default is reading in text mode. In this mode, while reading from the file the data
would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.
'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()
csv.reader(fileobject,delimiter,fmtparams)
where
file object :- passes the path and the mode of the file
delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
fmtparams: optional parameter which help to override the default values of the dialects like
skipinitialspace,quoting etc. Can be omitted
The following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
As you can see in “sample2.csv” there are spaces after the delimiter due to which the
output is also displayed with spaces.
Note
By default “skipinitialspace” has a value false
The following program reads “sample2.csv” file, which contains spaces after the delimiter.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']
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.
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
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
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.
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.
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
sample8.csv in Notepad
ItemName ,Quantity
Keyboard, 48
Monitor,52
Mouse ,20
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
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
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.
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
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.
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.
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()
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.
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()
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.
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
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.
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
chennai,mylapore
mumbai,andheri
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
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
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.
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
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
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
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
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
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
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
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
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
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
271
Importing C++ Programs in Python
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)
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
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
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
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
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
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.
• 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
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.
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
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
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
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')
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
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.
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
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”
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
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.
• 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
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.
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
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
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
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
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
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.
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
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.
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
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’.
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
Evaluation
Part - I
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
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
CHAPTER 16
Unit V DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART
Learning Objectives
307
Data Visualization using Pyplot
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
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
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
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
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
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
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
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
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
Evaluation
Part - I
317
Data Visualization using Pyplot
a. Epic Info b.
16 1 info
16
14 14
12
12
Y axis
y axis
10
8
10
2 6
4
8
2
2 3 4 5 6 7
6
8 11
3 x axis
5 6 7 9 10
X axis
c.
d.
2.100
4.0
2.075
3.5
2.050
some numbers
2.025 3.0
2.000 2.5
1.975 2.0
1.950
1.5
1.925
1.0
1.900
0.0 0.0 0.5 1.5 2.0 2.5 3.0
2.85 2.90 2.95 3.00 3.05 3.10 3.15
318
XII Std Computer Science
Part - II
Part - III
319
Data Visualization using Pyplot
Part - IV
Reference
1. https://towards datascience.com / data - science - with - python - intro -to- data
-visualization-and-matplotlib-5f799b7c6d82.
2. https://heartbeat.fritz.ai/introduction-to-matplotlib-data-visualization-in-python-
d9143287ae39.
3. https://python programming.net / legends - titles - labels - matplotlib - tutorial/?
completed=/matplotlib-intro-tutorial/.
4. https://keydifferences.com/difference-between-histogram-and-bar-graph.html.
320
XII Std Computer Science
GLOSSARY
Terminology Meaning
Access control security technique that regulates who or what can view
or use resources in a computing environment
Access modifiers Private , Protected and Public
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
322
323
324
325
326
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
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
www.tntextbooks.in
Annexure
12th StdI-&CS2.indd 342
EM Annexure Pages.indd 328 20-02-2019
23-12-202214:35:27
13:16:59 Anne
www.tntextbooks.in
329
343
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
www.tntextbooks.in
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
Annexure
12th Std - ICS
& EM
2.indd 344 Pages.indd 330
Annexure 20-02-2019
23-12-2022 14:35:27
13:16:59
www.tntextbooks.in
PRACTICAL EXERCISES
331
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
INDEX
Question Page
S No Program Name
Number Number
333
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
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
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
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
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
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
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
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
342
343
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
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
346
347
Reg_No
M1001
M1002
C1001
C1002
E1001
E1002
E1003
348
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
print(row)
q+=1
if(q==0):
print("string not found")
f.close()
f.close()
Output:
350
9 Create a sql table using python and accept 10 names and age .sort in descending
order of age and display.
Aim: o create a sql table using python and accept 10 names and age. sort in descending
T
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
Output:
352
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
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