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

Python Material

Chapter 5 of the document covers Python variables and operators, focusing on the use of Graphical User Interface (GUI) and Integrated Development Environment (IDE) for programming. It explains programming modes (Interactive and Script), input/output functions, comments, indentation, tokens, identifiers, keywords, and various types of operators including arithmetic and relational. The chapter also provides examples and syntax for creating and executing Python scripts.

Uploaded by

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

Python Material

Chapter 5 of the document covers Python variables and operators, focusing on the use of Graphical User Interface (GUI) and Integrated Development Environment (IDE) for programming. It explains programming modes (Interactive and Script), input/output functions, comments, indentation, tokens, identifiers, keywords, and various types of operators including arithmetic and relational. The chapter also provides examples and syntax for creating and executing Python scripts.

Uploaded by

r2kgamingboyz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 5

Unit II
PYTHON – VARIABLES AND OPERATORS

Learning Objectives

After studying this lesson, students will be able to:


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

5.1 Introduction

Python is a general purpose


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

5.2 Key features of Python


99 It is a general purpose programming language which can be used for both scientific
and non-scientific programming.
99 It is a platform independent programming language.
99 The programs written in Python are easily readable and understandable.

47

12th Computer Science_EM Chapter [Link] 47 26-12-2022 17:27:28


The version 3.x of Python IDLE (Integrated Development Learning Environment)
is used to develop and run Python code. It can be downloaded from the web resource
[Link].

5.3 Programming in Python


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

5.3.1 Interactive mode Programming


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

(i) Invoking Python IDLE


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

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

(Or)

Click python Icon on the Desktop if available.

Now Python IDLE window appears as shown in the Figure 5.1


Menu Bar Tilte Bar

Python prompt (>>>)

Python IDLE Window


The prompt (>>>) indicates that Interpreter is ready to accept instructions. Therefore,
the prompt on screen means IDLE is working in interactive mode. Now let us try as a simple
calculator by using a simple mathematical expressions.

XII Std Computer Science 48

12th Computer Science_EM Chapter [Link] 48 26-12-2022 17:27:28


Example 1: Example 2:
>>> 5 + 10 >>>print (“Python Programming Language”)
15 Python Programming Language
>>>x=10
>>> 5 + 50 *10
>>>y=20
505 >>>z=x + y
>>> 5 ** 2 >>>print (“The Sum”, z)
25 The Sum = 30

Python Interactive Window

5.3.2 Script mode Programming


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

(i) Creating Scripts in Python


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

49 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 49 26-12-2022 17:27:28


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

Figure 5.3(a) Untitled, blank Python script editor


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

b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)

Figure 5.4 – Python Sample code

XII Std Computer Science 50

12th Computer Science_EM Chapter [Link] 50 26-12-2022 17:27:28


(ii) Saving Python Script
(1) Choose File → Save or Press Ctrl + S

Figure 5.5 – To Save the file First time


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

File Name (demo1)

File Type (Python file (.py))

Figure 5.6 – Save As Dialog Box

51 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 51 26-12-2022 17:27:28


(3) In the Save As dialog box, select the location where you want to save your Python code,
and type the file name in File Name box. Python files are by default saved with extension
.py. Thus, while creating Python scripts using Python Script editor, no need to specify
the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5

a=100
b=350
c=a+b
print ("The Sum=", c)

Figure 5.7 – To Execute Python Script

(2) If your code has any error, it will be shown in red color in the IDLE window, and Python
describes the type of error occurred. To correct the errors, go back to Script editor, make
corrections, save the file using Ctrl + S or File → Save and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in
Figure 5.8

Output

Figure 5.8 –Python Script Output Window

XII Std Computer Science 52

12th Computer Science_EM Chapter [Link] 52 26-12-2022 17:27:28


5.4 Input and Output Functions

A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions. The input() function helps to enter data at run time
by the user and the output function print() is used to display the result of the program on the
screen after execution.
5.4.1 The print() function
In Python, the print() function is used to display result on the screen. The syntax for
print() is as follows:
Example
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)

Example
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11

The print ( ) evaluates the expression before printing it on the monitor. The print
() displays an entire statement which is specified within print ( ). Comma ( , ) is used as a
separator in print ( ) to print more than one item.

5.4.2 input() function


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

Variable = input (“prompt string”)

53 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 53 26-12-2022 17:27:28


Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable. If prompt string is not given in input( ) no message is
displayed on the screen, thus, the user will not know what is to be typed as input.

Example 1:input( ) with prompt string

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


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

Example 2:input( ) without prompt string

>>> city=input()
Rajarajan
>>> print (“I am from”, city)
I am from Rajarajan

Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input( ).

The input ( ) accepts all data as string 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

XII Std Computer Science 54

12th Computer Science_EM Chapter [Link] 54 26-12-2022 17:27:28


Example 4: Alternate method for the above program
x,y=int (input("Enter Number 1 :")),int(input("Enter Number 2:"))
print ("X = ",x," Y = ",y)
Output:
Enter Number 1 :30
Enter Number 2:50
X = 30 Y = 50

5.5 Comments in Python


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

5.6 Indentation
Python uses whitespace such as spaces and tabs to define program blocks whereas
other languages like C, C++, java use curly braces { } to indicate blocks of codes for class,
functions or body of the loops and block of selection command. The number of whitespaces
(spaces and tabs) in the indentation is not fixed, but all statements within the block must be
indented with same amount spaces.

5.7 Tokens
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens.

5.7.1. Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.

55 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 55 26-12-2022 17:27:28


• An identifier must start with an alphabet (A..Z and a..z) or underscore ( _ ).
• Identifiers may contain digits (0 .. 9)
• Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
• Identifiers must not be a python keyword.
• Python does not allow punctuation character such as %,$, @ etc., within identifiers.

Example of valid identifiers


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

5.7.2. Keywords
Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Table 5.1 Python’s Keywords

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

5.7.3 Operators
In computer programming languages operators are special symbols which represent
computations, conditional matching etc. The value of an operator used is called operands.
Operators are categorized as Arithmetic, Relational, Logical, Assignment etc. Value and
variables when used with operator are known as operands.
(i) Arithmetic operators
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

12th Computer Science_EM Chapter [Link] 56 26-12-2022 17:27:28


Python supports the following Arithmetic operators.

Operator - Operation Examples Result

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


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

Program 5.1 To test Arithmetic Operators:


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

(ii) Relational or Comparative operators


A Relational operator is also called as Comparative operator which checks the
relationship between two operands. If the relation is true, it returns True; otherwise it returns
False.

57 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 57 26-12-2022 17:27:28


Python supports following relational operators

Operator - Operation Examples Result


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

Coding 5.2 To test Relational Operators:


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

(iii) Logical operators


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

XII Std Computer Science 58

12th Computer Science_EM Chapter [Link] 58 26-12-2022 17:27:29


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

Program 5.3 To test Logical Operators:

Example – Code Example - Result

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


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

(iv) Assignment operators


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

Operator Description Example


Assume x=10
>>> x=10
= Assigns right side operands to left variable
>>> b=”Computer”
Added and assign back the result
+= >>> x+=20 # x=x+20
to left operand
Subtracted and assign back the
-= >>> x-=5 # x=x-5
result to left operand
Multiplied and assign back the
*= >>> x*=5 # x=x*5
result to left operand
Divided and assign back the
/= >>> x/=2 # x=x/2
result to left operand

59 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 59 26-12-2022 17:27:29


Taken modulus(Remainder) using two
%= operands and assign the result >>> x%=3 # x=x%3
to left operand

Performed exponential (power) calculation on


**= >>> x**=2 # x=x**2
operators and assign value to the left operand

Performed floor division on operators and


//= >>> x//=3
assign value to the left operand

Program 5.4 To test Assignment Operators:

Program Coding Output

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


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

(v) Conditional operator


Ternary operator is also known as conditional operator that evaluate something based
on a condition being true or false. It simply allows testing a condition in a single line replacing
the multiline if-else making the code compact.

XII Std Computer Science 60

12th Computer Science_EM Chapter [Link] 60 26-12-2022 17:27:29


The Syntax conditional operator is,

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

Example :

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


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

Program 5.5 To test Conditional (Ternary) Operator:


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

Output:
The Minimum of A and B is 20

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

(i) Numeric Literals


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

61 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 61 26-12-2022 17:27:29


Program 5.6 : To demonstrate Numeric literals
# Program to demonstrate Numeric Literals
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal
print ("Integer Literals :",a,b,c,d)
#Float Literal
float_1 = 10.5
float_2 = 1.5e2
print ("Float Literals :",float_1,float_2)
#Complex Literal
x = 1 + 3.14 j
print ("Complex Literals :")
Print ("x = ", x , "Imaginary part of x = ", [Link], "Real part of x = ", [Link])
#End of the Program
Output:
Integer Literals : 10 100 200 300
Float Literals : 10.5 150.0
Complex Literals :
x = (1+3.14j) Imaginary part of x = 3.14 Real part of x = 1.0

(ii) String Literals


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

Program 5.7 To test String Literals


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

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

XII Std Computer Science 62

12th Computer Science_EM Chapter [Link] 62 26-12-2022 17:27:29


(iii) Boolean Literals
A Boolean literal can have any of the two values: True or False.
Program 5.8 To test Boolean Literals:
# Demo Program to test String Literals
boolean_1 = True
boolean_2 = False
print ("Demo Program for Boolean Literals")
print ("Boolean Value1 :",boolean_1)
print ("Boolean Value2 :",boolean_2)
# End of the Program
Output:
Demo Program for Boolean Literals
Boolean Value1 : True
Boolean Value2 : False

(iv) Escape Sequences


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

Escape sequence Description Example Output


character

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

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


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

5.8 Python Data types


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

12th Computer Science_EM Chapter [Link] 63 26-12-2022 17:27:29


5.8.1 Number Data type
The built-in number objects in Python supports integers, floating point numbers and
complex numbers.
Integer Data can be decimal, octal or hexadecimal. Octal integer use digit 0 (Zero)
followed by letter 'o' to denote octal digits and hexadecimal integer use 0X (Zero and either
uppercase or lowercase X) and L (only upper case) to denote long integer.
Example :
102, 4567, 567 # Decimal integers
0o102, 0o876, 0o432 # Octal integers
0X102, 0X876, 0X432 # Hexadecimal integers
34L, 523L # Long decimal integers

A floating point data is represented by a sequence of decimal digits that includes a


decimal point. An Exponent data contains decimal digit part, decimal point, exponent part
followed by one or more digits.

Example :
123.34, 456.23, 156.23 # Floating point data
12.E04, 24.e04 # Exponent data

Complex number is made up of two floating point values, one each for the real and
imaginary parts.
5.8.2 Boolean Data type
A Boolean data can have any of the two values: True or False.
Example :
Bool_var1=True
Bool_var2=False

5.8.3 String Data type


String data can be enclosed in single quotes or double quotes or triple quotes.

Example :
Char_data = ‘A’
String_data= "Computer Science"
Multiline_data= ”””String data can be enclosed in single quotes or
double quotes or triple quotes.”””

XII Std Computer Science 64

12th Computer Science_EM Chapter [Link] 64 26-12-2022 17:27:29


Points to remember:
• Python is a general purpose programming language created by Guido Van Rossum.
• Python shell can be used in two ways, viz., Interactive mode and Script mode.
• Python uses whitespace (spaces and tabs) to define program blocks
• Whitespace separation is necessary between tokens, identifiers or keywords.
• A Program needs to interact with end user to accomplish the desired task, this is done
using Input-Output facility.
• Python breaks each logical line into a sequence of elementary lexical components
known as Tokens.
• Keywords are special words that are used by Python interpreter to recognize the
structure of program.

Evaluation
Part - I
Choose the best answer (1 Marks)
1. Who developed Python ?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<<
C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F
C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($)
C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers
C) Keyword D) Operators

65 Python – Variables and Operators

12th Computer Science_EM Chapter [Link] 65 26-12-2022 17:27:29


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

Part - II
Answer the following questions : (2 Marks)
1. What are the different modes that can be used to test Python Program ?
2. Write short notes on Tokens.
3. What are the different operators that can be used in Python ?
4. What is a literal? Explain the types of literals ?
5. Write short notes on Exponent data?

Part - III
Answer the following questions : (3 Marks)
1. Write short notes on Arithmetic operator with examples.
2. What are the assignment operators that can be used in Python?
3. Explain Ternary operator with examples.
4. Write short notes on Escape sequences with examples.
5. What are string literals? Explain.

Part - IV
Answer the following questions : (5 Marks)
1. Describe in detail the procedure Script mode programming.
2. Explain input() and print() functions with examples.
3. Discuss in detail about Tokens in Python

XII Std Computer Science 66

12th Computer Science_EM Chapter [Link] 66 26-12-2022 17:27:29


CHAPTER 6
Unit II
CONTROL STRUCTURES

Learning Objectives

After studying this lesson, students will be able to:

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

• To learn through the syntax how to use conditional construct to improve the efficiency of
the program flow.

• To apply iteration structures to develop code to repeat the program segment for specific
number of times or till the condition is satisfied.

6.1 Introduction

Programs may contain set of statements. These statements are the executable segments
that yield the result. In general, statements are executed sequentially, that is the statements
are executed one after another. There may be situations in our real life programming where
we need to skip a segment or set of statements and execute another segment based on the test
of a condition. This is called alternative or branching. Also, we may need to execute a set of
statements multiple times, called iteration or looping. In this chapter we are to focus on the
various control structures in Python, their syntax and learn how to develop the programs
using them.

6.2 Control Structures


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

67

12th Computer Science_EM Chapter [Link] 67 26-12-2022 16:44:45


There are three important control structures

Sequential

Alternative or
Branching

Iterative or Looping

6.2.1 Sequential Statement


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

Example 6.1
# Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN

6.2.2 Alternative or Branching Statement


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

Python provides the following types of alternative or branching statements:


• Simple if statement • if..else statement • if..elif statement

(i) Simple if statement


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

XII Std Computer Science 68

12th Computer Science_EM Chapter [Link] 68 26-12-2022 16:44:45


Syntax:
if <condition>:
statements-block1

In the above syntax if the condition is true statements - block 1 will be executed.

Example 6.2
# Program to check the age and print whether eligible for voting
x=int (input("Enter your age :"))
if x>=18:
print ("You are eligible for voting")
Output 1:
Enter your age :34
You are eligible for voting
Output 2:
Enter your age :16
>>>

As you can see in the second execution no output will be printed, only the Python
prompt will be displayed because the program does not check the alternative process when the
condition is failed.

(ii) if..else statement


The if .. else statement provides control to check the true block as well as the false
block. Following is the syntax of ‘if..else’ statement.

Syntax:
if <condition>:
statements-block 1
else:
statements-block 2

69 Control Structures

12th Computer Science_EM Chapter [Link] 69 26-12-2022 16:44:45


Entry

if condition is if condition is
true condition false

Statement Statement
block -1 block -2

Exit
Fig. 6.1 if..else statement execution

if..else statement thus provides two possibilities and the condition determines which
BLOCK is to be executed.

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


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

An alternate method to rewrite the above program is also available in Python. The
complete if..else can also written as:

Syntax:
variable = variable1 if condition else variable 2

XII Std Computer Science 70

12th Computer Science_EM Chapter [Link] 70 26-12-2022 16:44:45


Note
The condition specified in the if statement is checked, if it is true, the value of
variable1 is stored in variable on the left side of the assignment, otherwise variable2 is
taken as the value.

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


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

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


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

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


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

71 Control Structures

12th Computer Science_EM Chapter [Link] 71 26-12-2022 16:44:45


Test false
Expression
of if

True Test false


Expression
Body of if of elif

True

Body of else
Body of elif

Fig 6.2 if..elif..else statement execution

‘Multiple if..else statements can be combined to one if..elif…else. ‘elif ’ can be


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

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

XII Std Computer Science 72

12th Computer Science_EM Chapter [Link] 72 26-12-2022 16:44:45


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

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

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


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

Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D

Output 2 :
Enter mark in first subject : 67
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

12th Computer Science_EM Chapter [Link] 73 26-12-2022 16:44:45


Example 6.5a: #Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
# to check if the letter typed is not ‘a’ or ‘b’ or ‘c’
if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)
Output 1:
Enter a character :e
e is a vowel
Output 2:
Enter a character :x
x the letter is not a/b/c

6.2.3. Iteration or Looping constructs

Iteration or loop are used in situation when the user need to execute a block of code
several of times or till the condition is satisfied. A loop statement allows to execute a statement
or group of statements multiple times.

False
Condition

True else
Statement 1
Statement 1 Statement 2
Statement 2 ...
... Statementn
Statementn
Further
Statements
of Program
Fig 6.3 Diagram to illustrate how looping construct gets executed
Python provides two types of looping constructs:
• while loop
• for loop
XII Std Computer Science 74

12th Computer Science_EM Chapter [Link] 74 26-12-2022 16:44:45


(i) while loop
The syntax of while loop in Python has the following syntax:

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

while Expression:
Statement (s)
Condition

if conditions is true
if condition is
Conditional Code
false

Fig 6.4 while loop execution


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

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

i=10 # intializing part of the control variable


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

Output:
10 11 12 13 14 15

75 Control Structures

12th Computer Science_EM Chapter [Link] 75 26-12-2022 16:44:46


Note
In the above example, the control variable is i, which is initialized to 10. Next the
condition i<=15 is tested, if the value is true i gets printed, then the control variable i gets
updated as i=i+1 (this can also be written as i +=1 using shorthand assignment operator).
When i becomes 16, the condition is returned as False and this will terminate the loop.

Note
print can have end, sep as parameters. end parameter can be used when we need to give
any escape sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be
used to specify any special characters like, (comma) ; (semicolon) as separator between
values (Recall the concept which you have learnt in previous chapter about the formatting
options in print()).

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

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

i=10 # intializing part of the control variable


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

(ii) for loop


The for loop is usually known as a definite loop, because the programmer knows exactly
how many times the loop will be executed.

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

12th Computer Science_EM Chapter [Link] 76 26-12-2022 16:44:46


The control variable accesses each item of the sequence on each iteration until it reaches the
last item in the sequence.

Example 6.8 (a) Example 6.8 (b)


for x in "Hello World": for x in (1,2,3,4,5):
print(x, end=' ') print("Hello World")
Output:
Output: Hello World
Hello World Hello World
Hello World
Hello World
Hello World

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.

Example 6.8(c): Examples for range()


range (1,30,1) will start the range of values from 1 and end at 29
range (2,30,2) will start the range of values from 2 and end at 28
range (30,3,-3) - will start the range of values from 30 and end at 6
range (20) will consider this value 20 as the end value(or upper limit) and starts the
range count from 0 to 19 (remember always range() will work till stop -1
value only)

77 Control Structures

12th Computer Science_EM Chapter [Link] 77 26-12-2022 16:44:46


for each item
in sequence

Yes
Last item
reached?

No
Body of for

Exit loop
Fig 6.5 for loop execution

Example 6.9: #program to illustrate the use of for loop - to print single
digit even number
for i in range (2,10,2):
print (i, end=' ')

Output:
2468

Following is an illustration using else part in for loop


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

Note
In Python, indentation is important in loop and other control statements. Indentation
only creates blocks and sub-blocks like how we create blocks within a set of { } in languages
like C, C++ etc.

Here is another program which illustrates the use of range() to find the sum of numbers
1 to 100

XII Std Computer Science 78

12th Computer Science_EM Chapter [Link] 78 26-12-2022 16:44:46


Example 6.11: # program to calculate the sum of numbers 1 to 100
n = 100
sum = 0
for counter in range(1,n+1):
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum))
Output:
Sum of 1 until 100: 5050
In the above code, n is initialized to 100, sum is initialized to 0, the for loop
starts executing from 1, for every iteration the value of sum is added with the value
of counter variable and stored in sum. Note that the for loop will iterate from 1 till
the upper limit -1 (ie. Value of n is set as 100, so this loop will iterate for values from
1 to 99 only, that is the reason why we have set the upper limit as n+1)

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

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


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

(iii) Nested loop structure


A loop placed within another loop is called as nested loop structure. One can place a
while within another while; for within another for; for within while and while within for to
construct such nested loops.
Following is an example to illustrate the use of for loop to print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

79 Control Structures

12th Computer Science_EM Chapter [Link] 79 26-12-2022 16:44:46


Example 6.13: program to illustrate the use nested loop -for within while loop
i=1
while (i<=6):
for j in range (1,i):
print (j,end='\t')
print (end='\n')
i +=1

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

6.2.4 Jump Statements in Python


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

False
Condition

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

Fig 6.6 Use of break, continue statement in loop structure

XII Std Computer Science 80

12th Computer Science_EM Chapter [Link] 80 26-12-2022 16:44:46


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

Enter loop

false
Condition

true

break?
yes
Exit loop
no
Remaining body of loop

Fig 6.7 Working of break statement


The working of break statement in for loop and while loop is shown below.
for var in sequence:
if condition:
break
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
break
#code inside while loop
#code outside while loop

81 Control Structures

12th Computer Science_EM Chapter [Link] 81 26-12-2022 16:44:46


Example 6.14: Program to illustrate the use of break statement inside
for loop
for word in “Jump Statement”:
if word = = “e”:
break
print (word, end= ' ')
Output:
Jump Stat

The above program will repeat the iteration with the given “Jump Statement” as string.
Each letter of the given string sequence is tested till the letter ‘e’ is encountered, when it is
encountered the control is transferred outside the loop block or it terminates. As shown in the
output, it is displayed till the letter ‘e’ is checked after which the loop gets terminated.
One has to note an important point here is that ‘if a loop is left by break, the else part
is not executed’. To explain this lets us enhance the previous program with an ‘else’ part and
see what output will be:

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


for loop
for word in “Jump Statement”:
if word = = “e”:
break
print (word, end=' ')
else:
print (“End of the loop”)
print (“\n End of the program”)
Output:
Jump Stat
End of the program

Note that the break statement has even skipped the ‘else’ part of the loop and has
transferred the control to the next line following the loop block.
(ii) continue statement
Continue statement unlike the break statement is used to skip the remaining part of a
loop and start with next iteration.

Syntax:
continue

XII Std Computer Science 82

12th Computer Science_EM Chapter [Link] 82 26-12-2022 16:44:46


Enter loop

Test false
Expression
of loop

true

yes
continue?

Exit loop
no
Remaining body of loop

Fig 6.8 Working of continue statement

The working of continue statement in for and while loop is shown below.
for var in sequence:
# code inside for loop
if condition:
continue
#code inside for loop
#code outside for loop
while test expression:
#code inside while loop
if condition:
continue
#code inside while loop
#code outside while loop

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


for loop
for word in “Jump Statement”:
if word = = “e”:
continue
print (word, end = ' ')
print (“\n End of the program”)
Output:
Jump Statmnt
End of the program

83 Control Structures

12th Computer Science_EM Chapter [Link] 83 26-12-2022 16:44:46


The above program is same as the program we had written for ‘break’ statement except
that we have replaced it with ‘continue’. As you can see in the output except the letter ‘e’ all the
other letters get printed.

(iii) pass statement


pass statement in Python programming is a null statement. pass statement when
executed by the interpreter it is completely ignored. Nothing happens when pass is executed,
it results in no operation.

pass statement can be used in ‘if ’ clause as well as within loop construct, when you do
not want any statements or commands within that block to be executed.

Syntax:
pass

Example 6.17: Program to illustrate the use of pass statement


a=int (input(“Enter any number :”))
if (a==0):
pass
else:
print (“non zero value is accepted”)

Output:
Enter any number :3
non zero value is accepted
When the above code is executed if the input value is 0 (zero)
then no action will be performed, for all the other input values the
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.

XII Std Computer Science 84

12th Computer Science_EM Chapter [Link] 84 26-12-2022 16:44:46


Example 6.18: Program to illustrate the use of pass statement in for loop
for val in “Computer”:
pass
print (“End of the loop, loop structure will be built in future”)

Output:
End of the loop, loop structure will be built in future.

Points to remember:

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


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

85 Control Structures

12th Computer Science_EM Chapter [Link] 85 26-12-2022 16:44:46


Hands on Experience

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

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

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

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


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

Evaluation

Part - I

Choose the best answer 1 Marks


1. How many important control structures are there in Python?
A) 3 B) 4
C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else
C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control
C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break
C) pass D) goto

XII Std Computer Science 86

12th Computer Science_EM Chapter [Link] 86 26-12-2022 16:44:46


5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression
B) Arithmetic or Logical expression
C) Relational or Logical expression
D) Arithmetic
6. Which of the following is known as definite loop?
A) do..while B) while
C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end=' ')
i +=1
A) 12 B) 123
C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True
C) 0 D) 1
9. Which amongst this is not a jump statement ?
A) for B) pass
C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) :
C) :: D) !
87 Control Structures

12th Computer Science_EM Chapter [Link] 87 26-12-2022 16:44:46


Part -II

Answer the following questions 2 Marks


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

Part -III

Answer the following questions 3 Marks


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

Part -IV

Answer the following questions 5 Marks


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

XII Std Computer Science 88

12th Computer Science_EM Chapter [Link] 88 26-12-2022 16:44:46


CHAPTER 7
Unit II
PYTHON FUNCTIONS

Main advantages of functions are


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

• Understand the function arguments. 7.1.1 Types of Functions

• Know Anonymous functions. Basically, we can divide functions


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

that are designed to do specific job. When


Figure – 7.1 – Types of Python Functions
you want to perform a particular task that
you have defined in a function, you call
Functions Description
the name of the function responsible for it.
If you need to perform that task multiple User-defined Functions defined by
times throughout your program, you don’t functions the users themselves.
need to type all the code for the same task Built-in Functions that are
again and again; you just call the function functions inbuilt with in Python.
dedicated to handling that task, and the Lambda Functions that are
call tells Python to run the code inside the functions anonymous un-named
function. You’ll find that using functions function.
makes your programs easier to write, read,
test, and fix errors.
89

12th Computer Science_EM Chapter [Link] 89 21-12-2022 15:21:23


• If any input parameters are present should
Recursion Functions that calls
functions itself is known as be placed within these parentheses when
recursive. you define a function.

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

Defining Functions • The statement “return [expression]”


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

7.2.1 Syntax for User defined function

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


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

Block: Nested Block:


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

XII Std Computer Science 90

12th Computer Science_EM Chapter [Link] 90 21-12-2022 15:21:23


Now let’s check out functions in action so you can visually see how they work within a
program. Here is an example for a simple function to display the given string.
Example: 7.2.1
def hello():
print (“hello - Python”)
return

7.2.2 Advantages of User-defined Functions


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

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

12th Computer Science_EM Chapter [Link] 91 21-12-2022 15:21:23


The above function will output the following.

Output:
hello – Python
None

7.4 Passing Parameters in Functions

Parameters can be declared to functions

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

7.5 Function Arguments

Arguments are used to call a function and there are primarily 4 types of functions that
one can use: Required arguments, Keyword arguments, Default arguments and Variable-length
arguments.

XII Std Computer Science 92

12th Computer Science_EM Chapter [Link] 92 21-12-2022 15:21:23


Function Arguments

1 Required arguments

2 Keyword arguments

3 Default arguments

4 Variable-length arguments

7.5.1 Required Arguments


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

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


Traceback (most recent call last):
File "[Link]", line 10, in <module>
printstring()
TypeError: printstring() missing 1 required positional argument: 'str'

Instead of printstring() in the above code if we use printstring (“Welcome”) then the
output is

Output:
Example - Required arguments
Welcome

93 Python Functions

12th Computer Science_EM Chapter [Link] 93 21-12-2022 15:21:23


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

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

Output:
Example-1 Keyword arguments
Name :Gshan

Example: 7.5.2 (b)


def printdata (name):
print (“Example-2 Keyword arguments”)
print (“Name :”, name)
return
# Now you can call printdata() function
printdata (name1 = “Gshan”)

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

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

Example: 7.5.2 (c)


def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
# Now you can call printdata() function
printdata (age=25, name="Gshan")

XII Std Computer Science 94

12th Computer Science_EM Chapter [Link] 94 21-12-2022 15:21:23


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

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

Note
In the above program the parameters orders are changed

7.5.3 Default Arguments


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

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

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

Output:
Name: Mani
Salary: 3500

When the above code is changed as printinfo(“Ram”,2000) it produces the following


output:

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

12th Computer Science_EM Chapter [Link] 95 21-12-2022 15:21:23


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

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

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

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

[Link] Syntax - Variable-Length Arguments


def function_name(*args):
function_body
return_statement

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.

XII Std Computer Science 96

12th Computer Science_EM Chapter [Link] 96 21-12-2022 15:21:24


In Variable Length arguments we can pass the arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments
Non-keyword variable arguments are called tuples. You will learn more about tuples in
the later chapters. The Program given is an illustration for non keyword variable argument.

Note
Keyword variable arguments are beyond the scope of this book.

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


supports variable length arguments.

7.6 Anonymous Functions

What is anonymous function?


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

What is the use of lambda or anonymous function?


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

Note
filter(), map() and reduce() functions are beyond the scope of this book.

Lambda function can take any number of arguments and must return one
value in the form of an expression. Lambda function can only access global variables
and variables in its parameter list.

97 Python Functions

12th Computer Science_EM Chapter [Link] 97 21-12-2022 15:21:24


7.6.1 Syntax of Anonymous Functions
The syntax for anonymous functions is as follows:

lambda [argument(s)] :expression Example: 7.6.1


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

The above lambda function that adds argument arg1 with argument arg2 and stores the
result in the variable sum. The result is displayed using the print().

7.7 The return Statement

• The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
• The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
• Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.
7.7.1 Syntax of return

return [expression list ]

This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

XII Std Computer Science 98

12th Computer Science_EM Chapter [Link] 98 21-12-2022 15:21:24


Example : 7.7.1
# return statment
def usr_abs (n):
if n>=0:
return n
else:
return –n
# Now invoking the function
x=int (input(“Enter a number :”)
print (usr_abs (x))
Output 1:
Enter a number : 25
25
Output 2:
Enter a number : -25
25

7.8 Scope of Variables


Scope of variable refers to the part of the program, where it is accessible, i.e., area where
you can refer (use) it. We can say that scope holds the current set of variables and their values.
We will study two types of scopes - local scope and global scope.

7.8.1 Local Scope


A variable declared inside the function's body is known as local variable.
Rules of local variable
• A variable with local scope can be accessed only within the function that it is created in.
• When a variable is created inside the function the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal parameters are also local to function.

99 Python Functions

12th Computer Science_EM Chapter [Link] 99 21-12-2022 15:21:24


Example : 7.8.1 (a) Create a Local Variable
def loc():
y=0 # local scope
print(y)
loc()
Output:
0

Example : 7.8.1 (b)Accessing local variable outside the scope


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

When we run the above code, the output shows the following error:
The above error occurs because we are trying to access a local variable ‘y’ in a global
scope.

NameError: name 'y' is not defined

7.8.2 Global Scope


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

XII Std Computer Science 100

12th Computer Science_EM Chapter [Link] 100 21-12-2022 15:21:24


Example : 7.8.2 (b) Modifying Global Variable From Inside the Function
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
Output:
UnboundLocal Error: local variable 'c' referenced before assignment

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

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.

101 Python Functions

12th Computer Science_EM Chapter [Link] 101 21-12-2022 15:21:24


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

In the above program, we declare x as global and y as local variable in the function
loc().
After calling the function loc(), the value of x becomes 16 because we used x=x * 2.
After that, we print the value of local variable y i.e. local.

Example : 7.8.3 (b) Global variable and Local variable with same name

x=5
def loc():
x = 10
print ("local x:", x)
loc()
print ("global x:", x)

Output:
local x: 10
global x: 5

In above code, we used same name ‘x’ for both global variable and local variable. We get
different result when we print same variable because the variable is declared in both scopes, i.e.
the local scope inside the function loc() and global scope outside the function loc().
The output :- local x: 10, is called local scope of variable.
The output:- global x: 5, is called global scope of variable.

XII Std Computer Science 102

12th Computer Science_EM Chapter [Link] 102 21-12-2022 15:21:24


7.9 Functions using libraries
7.9.1 Built-in and Mathematical functions

Function Description Syntax Example


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

103 Python Functions

12th Computer Science_EM Chapter [Link] 103 21-12-2022 15:21:24


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

XII Std Computer Science 104

12th Computer Science_EM Chapter [Link] 104 21-12-2022 15:21:24


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

105 Python Functions

12th Computer Science_EM Chapter [Link] 105 21-12-2022 15:21:24


2. Second Output:1
argument x value is rounded to 18
(ndigits) y value is rounded to 22
is used to z value is rounded to -18
specify the n1=17.89
number print (round (n1,0))
of decimal print (round (n1,1))
digits print (round (n1,2))
desired after
rounding. Output:2
18.0
17.9
17.89
pow ( ) Returns the a= 5
computation of b= 2
ab i.e. (a**b ) c= 3.0
a raised to the print (pow (a,b))
power of b. print (pow (a,c))
pow (a,b) print (pow (a+b,3))

Output:
25
125.0
343

Mathematical Functions

Note
Specify import math module before using all mathematical
functions in a program

Function Description Syntax Example


floor ( ) Returns the largest integer [Link] (x) import math
less than or equal to x x=26.7
y=-26.7
z=-23.2
print ([Link] (x))
print ([Link] (y))
print ([Link] (z))
Output:
26
-27
-24

XII Std Computer Science 106

12th Computer Science_EM Chapter [Link] 106 21-12-2022 15:21:24


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

7.10 Python recursive functions


When a function calls itself is known as recursion. Recursion works like loop but
sometimes it makes more sense to use recursion than loop. You can convert any loop to

107 Python Functions

12th Computer Science_EM Chapter [Link] 107 21-12-2022 15:21:24


recursion.
A recursive function calls itself. Imagine a process would iterate indefinitely if not
stopped by some condition! Such a process is known as infinite iteration. The condition that
is applied in any recursive function is known as base condition. A base condition is must in
every recursive function otherwise it will continue to execute like an infinite loop.

Overview of how recursive function works


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

Example : 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 [Link]
(limit_value).

Example:
import sys
[Link](3000)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000))

XII Std Computer Science 108

12th Computer Science_EM Chapter [Link] 108 21-12-2022 15:21:24


Points to remember:

• Functions are named blocks of code that are designed to do one specific job.
• Types of Functions are User defined, Built-in, lambda and recursion.
• Function blocks begin with the keyword “def ” followed by function name and
parenthesis ().
• A “return” with no arguments is the same as return None. Return statement
is optional in python.
• In Python, statements in a block should begin with indentation.
• A block within a block is called nested block.
• Arguments are used to call a function and there are primarily 4 types of
functions that one can use: Required arguments, Keyword arguments, Default
arguments and Variable-length arguments.
• Required arguments are the arguments passed to a function in correct
positional order.
• Keyword arguments will invoke the function after the parameters are
recognized by their parameter names.
• A Python function allows to give the default values for parameters in the
function definition. We call it as Default argument.
• Variable-Length arguments are not specified in the function’s definition and
an asterisk (*) is used to define such arguments.
• Anonymous Function is a function that is defined without a name.
• Scope of variable refers to the part of the program, where it is accessible, i.e.,
area where you can refer (use) it.
• The value returned by a function may be used as an argument for another
function in a nested manner. This is called composition.
• A function which calls itself is known as recursion. Recursion works like a
loop but sometimes it makes more sense to use recursion than loop.

109 Python Functions

12th Computer Science_EM Chapter [Link] 109 21-12-2022 15:21:24


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

Slno code Result


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

2. Evaluate the following functions and write the output

Slno Function Output

1 eval(‘25*2-5*4')

2 [Link](abs(-81))

3 [Link](3.5+4.6)

4 [Link](3.5+4.6)

3. Evaluate the following functions and write the output


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

XII Std Computer Science 110

12th Computer Science_EM Chapter [Link] 110 21-12-2022 15:21:24


7 1) format(66, 'c')
2) format(10, 'x')
3) format(10, 'X')
4) format(0b110, 'd')
5) format(0xa, 'd')
8 1) pow(2,-3)
2) pow(2,3.0)
3) pow(2,0)
4) pow((1+2),2)
5) pow(-3,2)
6) pow(2*2,2)

Evaluation

Part - I
Choose the best answer: (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching
(c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion
(c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion
(c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for
(c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return
(c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot)
(c) : (colon) (d) $ (dollar)

111 Python Functions

12th Computer Science_EM Chapter [Link] 111 21-12-2022 15:21:24


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

Part - II

Answer the following questions: (2 Marks)


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

XII Std Computer Science 112

12th Computer Science_EM Chapter [Link] 112 21-12-2022 15:21:24


Part - III

Answer the following questions: (3 Marks)


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

Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
2. Explain the scope of variables with an example.
3. Explain the following built-in functions.
(a) id()
(b) chr()
(c) round()
(d) type()
(e) pow()
4. Write a Python code to find the L.C.M. of two numbers.
5. Explain recursive function with an example.
Reference Books
1. Python Tutorial book from [Link]
2. Python Programming: A modular approach by Pearson – Sheetal, Taneja
3. Fundamentals of Python –First Programs by Kenneth A. Lambert

113 Python Functions

12th Computer Science_EM Chapter [Link] 113 21-12-2022 15:21:24


CHAPTER 8
Unit II
STRINGS AND STRING MANIPULATION

Learning Objectives

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


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

8.1 Introduction

String is a data type in python, which is used to handle array of characters. String is
a sequence of Unicode characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.

Example

‘Welcome to learning Python’


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

In python, strings are immutable, it means, once you define a string, it cannot be
changed during execution.
8.2 Creating Strings
As we learnt already, a string in Python can be created using single or double or even
triple quotes. String in single quotes cannot hold any other single quoted 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.

XII Std Computer Science 114

12th Computer Science_EM Chapter [Link] 114 21-12-2022 15:28:38


Example
#A string defined within single quotes
>>> print (‘Greater Chennai Corporation’)
Greater Chennai Corporation
#single quoted string defined within single quotes
>>> print ('Greater Chennai Corporation's student')
SyntaxError: invalid syntax

#A string defined within double quotes


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

8.3 Accessing characters in a String


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

The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string. The negative index assigned from the last
character to the first character in reverse order begins with -1.

Example
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1

115 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 115 21-12-2022 15:28:38


Example 1 : Program to access each character with its positive subscript of
a giving string
str1 = input ("Enter a string: ")
index=0
for i in str1:
print ("Subscript[",index,"] : ", i)
index + = 1
Output
Enter a string: welcome
Subscript [ 0 ] : w
Subscript [ 1 ] : e
Subscript [ 2 ] : l
Subscript [ 3 ] : c
Subscript [ 4 ] : o
Subscript [ 5 ] : m
Subscript [ 6 ] : e

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


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

8.4 Modifying and Deleting Strings


As you already learnt, strings in python are immutable. That means, once you define
a string modifications or deletion is not allowed. However, we can replace the existing string
entirely with the new string.

XII Std Computer Science 116

12th Computer Science_EM Chapter [Link] 116 21-12-2022 15:28:38


Example
>>> str1="How are you"
>>> str1[0]="A"
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str1[0]="A"
TypeError: 'str' object does not support item assignment

In the above example, string variable str1 has been assigned with the string “How are
you” in statement 1. In the next statement, we try to update the first character of the string with
character ‘A’. But python will not allow the update and it shows a TypeError.
To overcome this problem, you can define a new string value to the existing string
variable. Python completely overwrite new string on the existing string.
Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> str1="How about you"
>>> print (str1)
How about you

Usually python does not support any modification in its strings. But, it provides a
function replace() to temporarily change all occurrences of a particular character in a string.
The changes done through replace () does not affect the original string.
General formate of replace function:

replace(“char1”, “char2”)
The replace function replaces all occurrences of char1 with char2.

Example
>>> str1="How are you"
>>> print (str1)
How are you
>>> print ([Link]("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.

117 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 117 21-12-2022 15:28:38


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

>>> str1="How are you"


>>> del str1[2]
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
del str1[2]
TypeError: 'str' object doesn't support item deletion

Example 4: Code lines to delete a string variable

>>> str1="How about you"


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

8.5 String Operators


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

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

Example
>>> str1="Welcome to "

XII Std Computer Science 118

12th Computer Science_EM Chapter [Link] 118 21-12-2022 15:28:38


>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating (*)
The multiplication operator (*) is used to display a string in multiple number of times.
Example
>>> str1="Welcome "
>>> print (str1*4)
Welcome Welcome Welcome Welcome
(iv) String slicing
Slice is a substring of a main string. A substring can be taken from the original string
by using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing operator.
Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Where start is the beginning index and end is the last index value of a character in the
string. Python takes the end value less than one from the actual index specified. For example,
if you want to slice first 4 characters from a string, you have to specify it as 0 to 5. Because,
python consider only the end value as n-1.
Example I : slice a single character from a string
>>> str1="THIRUKKURAL"

>>> print (str1[0])


T
Example II : slice a substring from index 0 to 4
>>> print (str1[0:5])
THIRU
Example III : slice a substring using index 0 to 4 but without specifying the beginning
index.
>>> print (str1[:5])
THIRU
Example IV : slice a substring using the start index alone without specifying the end index.
>>> print (str1[6:])
KURAL

119 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 119 21-12-2022 15:28:38


Example V : Program to slice substrings using for loop

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

(v) Stride when slicing string


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

Example
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:4])
r
>>> print (str1[10:16:2])
er
>>> print (str1[::3])
Wceoenyo

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


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

XII Std Computer Science 120

12th Computer Science_EM Chapter [Link] 120 21-12-2022 15:28:38


Example
>>> str1 = "Welcome to learn Python"
>>> print(str1[::-2])
nhy re teolW

8.6 String Formatting Operators


The string formatting operator is one of the most exciting feature of python. The
formatting operator % is used to construct strings, replacing parts of the strings with the data
stored in variables.

Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))

Example

name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))

Output
Name: Rajarajan and Marks: 98

8.7 Formatting characters


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

121 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 121 21-12-2022 15:28:39


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

Example
# String within triple quotes to display a string with single quote
>>> print ('''They said, "What's there?"''')
They said, "What's there?"
# String within single quotes to display a string with single quote using escape sequence
>>> print ('They said, "What\'s there?"')
They said, "What's there?"
# String within double quotes to display a string with single quote using escape sequence
>>> print ("They said, \"What's there?\"")
He said, "What's there?"

Escape sequences supported by python


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

8.8 The format( ) function


The format( ) function used with strings is very versatile and powerful function used
for formatting strings. The curly braces { } are used as placeholders or replacement fields which
get replaced along with format( ) function.

XII Std Computer Science 122

12th Computer Science_EM Chapter [Link] 122 21-12-2022 15:28:39


Example
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))
Out Put
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

8.9 Built-in String functions


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

Syntax Description Example


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

123 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 123 21-12-2022 15:28:39


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

XII Std Computer Science 124

12th Computer Science_EM Chapter [Link] 124 21-12-2022 15:28:39


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

Example
str1=input ("Enter a string: ")
str2="chennai"
if str2 in str1:
print ("Found")
else:
print ("Not Found")
Output : 1
Enter a string: Chennai G HSS, Saidapet
Found
Output : 2
Enter a string: Govt G HSS, Ashok Nagar
Not Found

125 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 125 21-12-2022 15:28:39


Example 8.11 Programs using Strings :
Example 8.11.1 : Program to check whether the given string is palindrome
or not
str1 = input ("Enter a string: ")
str2 = ' '
index=-1
for i in str1:
str2 += str1[index]
index -= 1
print ("The given string = { } \n The Reversed string = { }".format(str1, str2))
if (str1==str2):
print ("Hence, the given string is Palindrome")
else:
print ("Hence, the given is not a palindrome")
Output : 1
Enter a string: malayalam
The given string = malayalam
The Reversed string = malayalam
Hence, the given string is Palindrome
Output : 2
Enter a string: welcome
The given string = welcome
The Reversed string = emoclew
Hence, the given string is not a palindrome

Example 8.11.2 : Program to display the following pattern

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

XII Std Computer Science 126

12th Computer Science_EM Chapter [Link] 126 21-12-2022 15:28:39


Example 8.11.3 : Program to display the number of vowels and consonants
in the given string
str1=input ("Enter a string: ")
str2="aAeEiIoOuU"
v,c=0,0
for i in str1:
if i in str2:
v+=1
elif [Link]():
c+=1
print ("The given string contains { } vowels and { } consonants".format(v,c))

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

Example 8.11.4 : Program to create an Abecedarian series. (Abecedarian


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

Example 8.11.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

127 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 127 21-12-2022 15:28:39


Example 8.11.6 : Program that count the occurrences of a character in a
string
def count(s, c):
c1=0
for i in s:
if i == c:
c1+=1
return c1
str1=input ("Enter a String: ")
ch=input ("Enter a character to be searched: ")
cnt=count (str1, ch)
print ("The given character {} is occurs {} times in the given string".format(ch,cnt))
Out Put
Enter a String: Software Engineering
Enter a character to be searched: e
The given character e is occurs 3 times in the given string

Points to remember:
• String is a data type in python.
• Strings are immutable, that means once you define string, it cannot be changed during
execution.
• Defining strings within triple quotes also allows creation of multiline strings.
• In a String, python allocate an index value for its each character which is known as
subscript.
• The subscript can be positive or negative integer numbers.
• Slice is a substring of a main string.
• Stride is a third argument in slicing operation.
• Escape sequences starts with a backslash and it can be interpreted differently.
• The format( ) function used with strings is very versatile and powerful function used
for formatting strings.
• The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string
is present in another string.

Hands on Experience

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

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

XII Std Computer Science 128

12th Computer Science_EM Chapter [Link] 128 21-12-2022 15:28:39


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

4. Write a program to print integers with ‘*’ on the right of specified width.

5. Write a program to create a mirror image of the given string. For example, “wel” = “lew“.

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

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

8. Write a program to swap two strings.

9. Write a program to replace a string with another string without using replace().

10. Write a program to count the number of characters, words and lines in a given string.

Evaluation
Part - I

Choose the best answer (1 Mark)


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

129 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 129 21-12-2022 15:28:39


6. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in
upper case?
(a) %f (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced
along with format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative
(c) Both (a) and (b) (d) Either (a) or (b)

Part -II

Answer the following questions (2 Marks)


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

Answer the following questions (3 Marks)


1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

XII Std Computer Science 130

12th Computer Science_EM Chapter [Link] 130 21-12-2022 15:28:39


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

Part -IV

Answer the following questions (5 Marks)


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

Reference Books
1. [Link]
2. [Link]
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

131 Strings and String Manipulation

12th Computer Science_EM Chapter [Link] 131 21-12-2022 15:28:39


CHAPTER 9
Unit III
LISTS, TUPLES, SETS AND DICTIONARY

Learning Objectives

After studying this chapter, students will be able to:


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

9.1 Introduction to List

Python programming language has four collections of data types such as List, Tuples,
Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an
ordered collection of values enclosed within square brackets [ ]. Each value of a list is called
as element. It can be of any type such as numbers, characters, strings and even the nested lists
as well. The elements can be modified or mutable which means the elements can be replaced,
added or removed. Every element rests at some position in the list. The position of an element
is indexed with numbers beginning with zero which is used to locate and access a particular
element. Thus, lists are similar to arrays, what you learnt in XI std.
9.1.1 Create a List in Python
In python, a list is simply created by using square bracket. The elements of list should
be specified within square brackets. The following syntax explains the creation of list.

Syntax:
Variable = [element-1, element-2, element-3 …… element-n]

XII Std Computer Science 132

12th Computer Science_EM Chapter [Link] 132 21-12-2022 15:37:02


Example
Marks = [10, 23, 41, 75]
Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
MyList = [ ]

In the above example, the list Marks has four integer elements; second list Fruits has
four string elements; third is an empty list. The elements of a list need not be homogenous type
of data. The following list contains multiple type elements.

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

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

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

9.1.2 Accessing List elements


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

Example
Marks = [10, 23, 41, 75]
Marks 10 23 41 75
Index (Positive) 0 1 2 3
IndexNegative) -4 -3 -2 -1

Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).

To access an element from a list, write the name of the list, followed by the index of the
element enclosed within square brackets.

Syntax:
List_Variable = [E1, E2, E3 …… En]
print (List_Variable[index of a element])

133 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 133 21-12-2022 15:37:02


Example (Accessing single element):
>>> Marks = [10, 23, 41, 75]
>>> print (Marks[0])
10

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

Example: Accessing elements in revevrse order


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

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

(i) Accessing all elements of a list


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

Example
Marks = [10, 23, 41, 75]
i=0
while i < 4:
print (Marks[i])
i=i+1
Output
10
23
41
75

In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each
element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively.
Here, the while loop is used to read all the elements. The initial value of the loop is zero, and
the test condition is i < 4, as long as the test condition is true, the loop executes and prints the
corresponding output.

XII Std Computer Science 134

12th Computer Science_EM Chapter [Link] 134 21-12-2022 15:37:02


During the first iteration, the value of i is 0, where the condition is true. Now, the
following statement print (Marks [i]) gets executed and prints the value of Marks [0] element
ie. 10.

The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of
control shifts to the while statement for checking the test condition. The process repeats to
print the remaining elements of Marks list until the test condition of while loop becomes false.

The following table shows that the execution of loop and the value to be print.

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

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

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

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

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

5 4 4 < 4 False -- --

(ii) Reverse Indexing


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

Example
Marks = [10, 23, 41, 75]
i = -1
while i >= -4:
print (Marks[i])
i = i + -1
Output
75
41
23
10

The following table shows the working process of the above python coding

135 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 135 21-12-2022 15:37:02


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

9.1.3 List Length


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

Example :Accessing single element


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

Example : Program to display elements in a list using loop


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

9.1.4 Accessing elements using for loop


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

Syntax:
for index_var in list:
print (index_var)

XII Std Computer Science 136

12th Computer Science_EM Chapter [Link] 136 21-12-2022 15:37:02


Here, index_var represents the index value of each element in the list. Python reads
this “for” statement like English: “For (every) element in (the list of) list and print (the name of
the) list items”

Example

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


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

In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The
Python reads the for loop and print statements like English: “For (every) element (represented
as x) in (the list of) Marks and print (the values of the) elements”.

9.1.5 Changing list elements


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

Syntax:
List_Variable [index of an element] = Value to be changed
List_Variable [index from : index to] = Values to changed

Where, index from is the beginning index of the range; index to is the upper limit of
the range which is excluded in the range. For example, if you set the range [0:5] means, Python
takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to
4, it should be specified as [1:5].

137 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 137 21-12-2022 15:37:02


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

XII Std Computer Science 138

12th Computer Science_EM Chapter [Link] 138 21-12-2022 15:37:02


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

Syntax: In the above code, extend() function


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

Example
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> print(MyList)
[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
>>> [Link](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.

139 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 139 21-12-2022 15:37:02


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

Syntax:
del List [index of an element]
# to delete a particular element
del List [index from : index to]
# to delete multiple elements
del List
# to delete entire list

Example
>>> MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> print (MySubjects)
['Tamil', 'Hindi', 'Telugu', 'Maths']
>>> del MySubjects[1]
>>> print (MySubjects)
['Tamil', 'Telugu', 'Maths']

In the above example, the list MySubjects has been created with four elements. print
statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an
element whose index value is 1 and the following print shows the remaining elements of the
list.
Example
>>> del MySubjects[1:3]
>>> print(MySubjects)
['Tamil']

In the above codes, >>> del MySubjects[1:3] deletes the second and third elements
from the list. The upper limit of index is specified within square brackets, will be taken as -1 by
the python.

XII Std Computer Science 140

12th Computer Science_EM Chapter [Link] 140 21-12-2022 15:37:02


Example
>>> del MySubjects
>>> print(MySubjects)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
print(MySubjects)
NameError: name 'MySubjects' is not defined

Here, >>> del MySubjects, deletes the list MySubjects entirely. When you try to print the
elements, Python shows an error as the list is not defined. Which means, the list MySubjects
has been completely deleted.

As already stated, the remove() function can also be used to delete one or more elements
if the index value is not known. Apart from remove() function, pop() function can also be
used to delete an element using the given index value. pop() function deletes and returns the
last element of a list if the index is not given.

The function clear() is used to delete all the elements in list, it deletes only the elements
and retains the list. Remember that, the del statement deletes entire list.

Syntax:
[Link](element) # to delete a particular element
[Link](index of an element)
[Link]( )

Example
>>> MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']
>>> print(MyList)
[12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin']
>>> [Link](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 >>> [Link](89), deletes the element 89 from the list and the print statement
shows the remaining elements.

141 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 141 21-12-2022 15:37:02


Example
>>> [Link](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
>>> [Link]( )
>>> print(MyList)
[ ]

In the above code, clear() function removes only the elements and retains the list. When
you try to print the list which is already cleared, an empty square bracket is displayed without
any elements, which means the list is empty.

9.1.9 List and range ( ) function


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

Syntax of range ( ) function:


range (start value, end value, step value)

where,

• start value – beginning value of series. Zero is the default beginning value.
• end value – upper limit of series. Python takes the ending value as upper limit – 1.
• step value – It is an optional argument, which is used to generate different interval of
values.

XII Std Computer Science 142

12th Computer Science_EM Chapter [Link] 142 21-12-2022 15:37:02


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

Example : Generating first 10 even numbers


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

(i) Creating a list with series of values


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

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

Syntax:
List_Varibale = list ( range ( ) )

Note

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

143 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 143 21-12-2022 15:37:02


Example
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]

In the above code, list() function takes the result of range() as Even_List elements. Thus,
Even_List list has the elements of first five even numbers.

Similarly, we can create any series of values using range() function. The following example
explains how to create a list with squares of first 10 natural numbers.

Example : Generating squares of first 10 natural numbers


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

In the above program, an empty list is created named “squares”. Then, the for loop
generates natural numbers from 1 to 10 using range() function. Inside the loop, the current
value of x is raised to the power 2 and stored in the variables. Each new value of square is
appended to the list “squares”. Finally, the program shows the following values as output.
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

9.1.10 List comprehensions


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

Syntax:
List = [ expression for variable in range ]

Example : Generating squares of first 10 natural numbers using the


concept of List comprehension

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


>>> print (squares)
Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

XII Std Computer Science 144

12th Computer Science_EM Chapter [Link] 144 21-12-2022 15:37:02


In the above example, x ** 2 in the expression is evaluated each time it is iterated. This
is the shortcut method of generating series of values.

9.1.11 Other important list funcion

Function Description Syntax Example

MyList=[12, 12, 36]


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

sort ( ) Sorts the element in list [Link](reverse=True|False, key=myFunc)

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


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

145 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 145 21-12-2022 15:37:02


MyList=[21,76,98,23]
Returns the maximum print(max(MyList))
max( ) max(list)
value in a list. Output:
98
MyList=[21,76,98,23]
Returns the minimum print(min(MyList))
min( ) min(list)
value in a list. Output:
21
MyList=[21,76,98,23]
Returns the sum of print(sum(MyList))
sum( ) sum(list)
values in a list. Output:
218
9.1.12 Programs using List

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


that are divisible by 4
divBy4=[ ]
for i in range(21):
if (i%4==0):
[Link](i)
print(divBy4)
Output
[0, 4, 8, 12, 16, 20]

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


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

XII Std Computer Science 146

12th Computer Science_EM Chapter [Link] 146 21-12-2022 15:37:02


Program 3: Python program to read marks of six subjects and to print the
marks scored in each subject and show the total marks
marks=[]
subjects=['Tamil', 'English', 'Physics', 'Chemistry', 'Comp. Science', 'Maths']
for i in range(6):
m=int(input("Enter Mark = "))
[Link](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

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


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

items=[]
prod=1
for i in range(5):
print ("Enter price for item { } : ".format(i+1))
p=int(input())
[Link](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))

147 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 147 21-12-2022 15:37:02


Output:
Enter price for item 1 :
5
Enter price for item 2 :
10
Enter price for item 3 :
15
Enter price for item 4 :
20
Enter price for item 5 :
25
Price for item 1 = Rs. 5
Price for item 2 = Rs. 10
Price for item 3 = Rs. 15
Price for item 4 = Rs. 20
Price for item 5 = Rs. 25
Sum of all prices = Rs. 75
Product of all prices = Rs. 375000
Average of all prices = Rs. 15.0

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


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

count=0
n=int(input("Enter no. of employees: "))
print("No. of Employees",n)
salary=[]
for i in range(n):
print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))
s=int(input())
[Link](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))

XII Std Computer Science 148

12th Computer Science_EM Chapter [Link] 148 21-12-2022 15:37:02


Output:
Enter no. of employees: 5
No. of Employees 5
Enter Monthly Salary of Employee 1 Rs.:
3000
Enter Monthly Salary of Employee 2 Rs.:
9500
Enter Monthly Salary of Employee 3 Rs.:
12500
Enter Monthly Salary of Employee 4 Rs.:
5750
Enter Monthly Salary of Employee 5 Rs.:
8000
Annual Salary of Employee 1 is:Rs. 36000
Annual Salary of Employee 2 is:Rs. 114000
Annual Salary of Employee 3 is:Rs. 150000
Annual Salary of Employee 4 is:Rs. 69000
Annual Salary of Employee 5 is:Rs. 96000
2 Employees out of 5 employees are earning more than Rs. 1 Lakh per annum

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


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

for index, i in enumerate(Num):


if(i%2==0):
del Num[index]
print("The list after deleting even numbers = ", Num)

Output
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The list after deleting even numbers = [1, 3, 5, 7, 9]

149 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 149 21-12-2022 15:37:02


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

9.2 Tuples

Introduction to Tuples
Tuples consists of a number of values separated by comma and enclosed within
parentheses. Tuple is similar to list, values in a list can be changed but not in a tuple.

The term Tuple is originated from the Latin word represents an abstraction of the
sequence of numbers:
single(1), double(2), triple(3), quadruple(4), quintuple(5), sextuple(6), septuple(7),
octuple(8), ..., n‑tuple, ...,

9.2.1 Comparison of Tuples and list


1. The elements of a list are changeable (mutable) whereas the elements of a tuple are
unchangeable (immutable), this is the key difference between tuples and list.

2. The elements of a list are enclosed within square brackets. But, the elements of a tuple are
enclosed by paranthesis.

3. Iterating tuples is faster than list.

XII Std Computer Science 150

12th Computer Science_EM Chapter [Link] 150 21-12-2022 15:37:02


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

Syntax:
# Empty tuple
Tuple_Name = ( )

# Tuple with n number elements


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

# Elements of a tuple without parenthesis


Tuple_Name = E1, E2, E3 ….. En

Example
>>> MyTup1 = (23, 56, 89, 'A', 'E', 'I', "Tamil")
>>> print(MyTup1)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')

>>> MyTup2 = 23, 56, 89, 'A', 'E', 'I', "Tamil"


>>> print (MyTup2)
(23, 56, 89, 'A', 'E', 'I', 'Tamil')

(i) Creating tuples using tuple( ) function


The tuple() function is used to create Tuples from a list. When you create a tuple, from a
list, the elements should be enclosed within square brackets.

Syntax:
Tuple_Name = tuple( [list elements] )

Example
>>> MyTup3 = tuple( [23, 45, 90] )
>>> print(MyTup3)
(23, 45, 90)
>>> type (MyTup3)
<class ‘tuple’>

151 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 151 21-12-2022 15:37:02


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

(ii) Creating Single element tuple


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

Example
>>> MyTup4 = (10)
>>> type(MyTup4)
<class 'int'>
>>> MyTup5 = (10,)
>>> type(MyTup5)
<class 'tuple'>

9.2.3 Accessing values in a Tuple


Like list, each element of tuple has an index number starting from zero. The elements of
a tuple can be easily accessed by using index number.

Example
>>> Tup1 = (12, 78, 91, “Tamil”, “Telugu”, 3.14, 69.48)
# to access all the elements of a tuple
>>> print(Tup1)
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)
#accessing selected elements using indices
>>> print(Tup1[2:5])
(91, 'Tamil', 'Telugu')
#accessing from the first element up to the specified index value
>>> print(Tup1[:5])
(12, 78, 91, 'Tamil', 'Telugu')
# accessing from the specified element up to the last element.
>>> print(Tup1[4:])
('Telugu', 3.14, 69.48)
# accessing from the first element to the last element
>>> print(Tup1[:])
(12, 78, 91, 'Tamil', 'Telugu', 3.14, 69.48)

XII Std Computer Science 152

12th Computer Science_EM Chapter [Link] 152 21-12-2022 15:37:02


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

Example
# Program to join two tuples
Tup1 = (2,4,6,8,10)
Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
print(Tup3)

Output
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)

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

Syntax:
del tuple_name

Example
Tup1 = (2,4,6,8,10)
print("The elements of Tup1 is ", Tup1)
del Tup1
print (Tup1)

Output:
The elements of Tup1 is (2, 4, 6, 8, 10)
Traceback (most recent call last):
File "D:/Python/Tuple Examp [Link]", line 4, in <module>
print (Tup1)
NameError: name 'Tup1' is not defined

Note that, the print statement in the above code prints the elements. Then, the del statement
deletes the entire tuple. When you try to print the deleted tuple, Python shows the error.

9.2.5 Tuple Assignment


Tuple assignment is a powerful feature in Python. It allows a tuple variable on the left
of the assignment operator to be assigned to the values on the right side of the assignment

153 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 153 21-12-2022 15:37:02


operator. Each value is assigned to its respective variable.

a b c
= 34 90 76

Example
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
# expression are evaluated before assignment
>>> (x, y, z, p) = (2**2, 5/3+4, 15%2, 34>65)
>>> print(x,y,z,p)
4 5.666666666666667 1 False

Note that, when you assign values to a tuple, ensure that the number of values on both sides of
the assignment operator are same; otherwise, an error is generated by Python.

9.2.6 Returning multiple values in Tuples


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

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


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

Output:
Maximum value = 99
Minimum value = 1

XII Std Computer Science 154

12th Computer Science_EM Chapter [Link] 154 21-12-2022 15:37:02


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

Example

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


("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)

Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)

Note
Some of the functions used in List can be applicable even for tuples.

9.2.8 Programs using Tuples

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

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


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

Output:
Enter value of A: 54
Enter value of B: 38
Value of A = 54
Value of B = 38
Value of A = 38
Value of B = 54

155 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 155 21-12-2022 15:37:02


Program 2: Write a program using a function that returns the area and
circumference of a circle whose radius is passed as an [Link] values
using tuple assignment
pi = 3.14
def Circle(r):
return (pi*r*r, 2*pi*r)
radius = float(input("Enter the Radius: "))
(area, circum) = Circle(radius)
print ("Area of the circle = ", area)
print ("Circumference of the circle = ", circum)

Output:
Enter the Radius: 5
Area of the circle = 78.5
Circumference of the circle = 31.400000000000002

Program 3: Write a program that has a list of positive and negative numbers.
Create a new tuple that has only positive numbers from the list

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


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

Output:
Positive Numbers: (5, 6, 8, 3, 1)

9.3 Sets

Introduction
In python, a set is another type of collection data type. A Set is a mutable and an unordered
collection of elements without duplicates. That means the elements within a set cannot be
repeated. This feature used to include membership testing and eliminating duplicate elements.

XII Std Computer Science 156

12th Computer Science_EM Chapter [Link] 156 21-12-2022 15:37:02


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

Syntax:
Set_Variable = {E1, E2, E3 …….. En}

Example
>>> S1={1,2,3,'A',3.14}
>>> print(S1)
{1, 2, 3, 3.14, 'A'}

>>> S2={1,2,2,'A',3.14}
>>> print(S2)
{1, 2, 'A', 3.14}

In the above examples, the set S1 is created with different types of elements without
duplicate values. Whereas in the set S2 is created with duplicate values, but python accepts
only one element among the duplications. Which means python removed the duplicate value,
because a set in python cannot have duplicate elements.

Note
When you print the elements from a set, python shows the values in different order.

9.3.2 Creating Set using List or Tuple


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

Example

MyList=[2,4,6,8,10]
MySet=set(MyList)
print(MySet)

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

157 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 157 21-12-2022 15:37:02


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

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

Set A Set B

In python, the operator | is used to union of two sets. The function union() is also used
to join two sets in python.

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

set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}

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

set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
set_U=set_A.union(set_B)
print(set_U)
Output:
{'D', 2, 4, 6, 8, 'B', 'C', 'A'}

XII Std Computer Science 158

12th Computer Science_EM Chapter [Link] 158 21-12-2022 15:37:02


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

Set A Set B

The operator & is used to intersect two sets in python. The function intersection() is also
used to intersect two sets in python.

Example: Program to insect two sets using intersection operator

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

Output:
{'A', 'D'}

Example: Program to insect two sets using intersection function

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

Output:
{'A', 'D'}

159 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 159 21-12-2022 15:37:02


(iii) Difference
It includes all elements that are in first set (say set A) but not in the second set (say set B)

Set A Set B

The minus (-) operator is used to difference set operation in python. The function
difference() is also used to difference operation.

Example: Program to difference of two sets using minus operator

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

Output:
{2, 4}

Example: Program to difference of two sets using difference function

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

Output:
{2, 4}

XII Std Computer Science 160

12th Computer Science_EM Chapter [Link] 160 21-12-2022 15:37:03


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

Set A Set B

The caret (^) operator is used to symmetric difference set operation in python. The
function symmetric_difference() is also used to do the same operation.

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

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

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

Example: Program to difference of two sets using symmetric difference


function

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

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

161 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 161 21-12-2022 15:37:03


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

Example

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


primes=set()
for i in range(2,20):
j=2
f=0
while j<=i/2:
if i%j==0:
f=1
j+=1
if f==0:
[Link](i)
print("Even Numbers: ", even)
print("Prime Numbers: ", primes)
print("Union: ", [Link](primes))
print("Intersection: ", [Link](primes))
print("Difference: ", [Link](primes))
print("Symmetric Difference: ", even.symmetric_difference(primes))
Output:
Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Prime Numbers: {2, 3, 5, 7, 11, 13, 17, 19}
Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}
Intersection: {2}
Difference: {4, 6, 8, 10, 12, 14, 16, 18, 20}
Symmetric Difference: {3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20}

9.4 Dictionaries

Introduction
In python, a dictionary is a mixed collection of elements. Unlike other collection data
types such as a list or tuple, the dictionary type stores a key along with its element. The keys in
a Python dictionary is separated by a colon ( : ) while the commas work as a separator for the
elements. The key value pairs are enclosed with curly braces { }.

XII Std Computer Science 162

12th Computer Science_EM Chapter [Link] 162 21-12-2022 15:37:03


Syntax of defining a dictionary:
Dictionary_Name = { Key_1: Value_1,
Key_2:Value_2,
……..
Key_n:Value_n
}

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

9.4.1 Creating a Dictionary


# Empty dictionary
Dict1 = { }

# Dictionary with Key


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

9.4.2 Dictionary Comprehensions


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

Syntax
Dict = { expression for variable in sequence [if condition] }

The if condition is optional and if specified, only those values in the sequence are evaluated
using the expression which satisfy the condition.

Example

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


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

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


Accessing all elements from a dictionary is very similar as Lists and Tuples. Simple print
function is used to access all the elements. If you want to access a particular element, square
brackets can be used along with key.

163 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 163 21-12-2022 15:37:03


Example : Program to access all the values stored in a dictionary
MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS',
'Address' : 'Rotler St., Chennai 112' }
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])
Output:
{'Reg_No': '1221', 'Name': 'Tamilselvi', 'School': 'CGHSS', 'Address': 'Rotler St., Chennai 112'}
Register Number: 1221
Name of the Student: Tamilselvi
School: CGHSS
Address: Rotler St., Chennai 112

Note that, the first print statement prints all the values of the dictionary. Other statements
are printing only the specified values which is given within square brackets.
In an existing dictionary, you can add more values by simply assigning the value along
with key. The following syntax is used to understand adding more elements in a dictionary.
dictionary_name [key] = value/element

Example : Program to add a new value in the dictionary


MyDict = { 'Reg_No': '1221',
'Name' : 'Tamilselvi',
'School' : 'CGHSS', 'Address' : '
Rotler St., Chennai 112'}
print(MyDict)
print("Register Number: ", MyDict['Reg_No'])
print("Name of the Student: ", MyDict['Name'])
MyDict['Class'] = 'XII - A' # Adding new value
print("Class: ", MyDict['Class']) # Printing newly added value
print("School: ", MyDict['School'])
print("Address: ", MyDict['Address'])

Modification of a value in dictionary is very similar as adding elements. When you assign
a value to a key, it will simply overwrite the old value.
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

12th Computer Science_EM Chapter [Link] 164 21-12-2022 15:37:03


Syntax:
# To delete a particular element.
del dictionary_name[key]
# To delete all the elements
dictionary_name.clear( )
# To delete an entire dictionary
del dictionary_name

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


the dictionary.

Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1' : 98, 'Marl2' : 86}
print("Dictionary elements before deletion: \n", Dict)
del Dict['Mark1'] # Deleting a particular element
print("Dictionary elements after deletion of a element: \n", Dict)
[Link]() # Deleting all elements
print("Dictionary after deletion of all elements: \n", Dict)
del Dict
print(Dict) # Deleting entire dictionary

Output:
Dictionary elements before deletion:
{'Roll No': 12001, 'SName': 'Meena', 'Mark1': 98, 'Marl2': 86}
Dictionary elements after deletion of a element:
{'Roll No': 12001, 'SName': 'Meena', 'Marl2': 86}
Dictionary after deletion of all elements:
{ }
Traceback (most recent call last):
File "E:/Python/Dict_Test_02.py", line 8, in <module>
print(Dict)
NameError: name 'Dict' is not defined

9.4.4 Difference between List and Dictionary


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

(2) The index values can be used to access a particular element. But, in dictionary key
represents index. Remember that, key may be a number of a string.

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

165 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 165 21-12-2022 15:37:03


Points to remember:
• Python programming language has four collections of data types such as List, Tuple,
Set and Dictionary.
• A list is known as a “sequence data type”. Each value of a list is called as element.
• The elements of list should be specified within square brackets.
• Each element has a unique value called index number begins with zero.
• Python allows positive and negative values as index.
• Loops are used access all elements from a list.
• The “for” loop is a suitable loop to access all the elements one by one.
• The append ( ), extend ( ) and insert ( ) functions are used to include more elements
in a List.
• The del, remove ( ) and pop ( ) are used to delete elements from a list.
• The range ( ) function is used to generate a series of values.
• Tuples consists of a number of values separated by comma and enclosed within
parentheses.
• Iterating tuples is faster than list.
• The tuple ( ) function is also used to create Tuples from a list.
• Creating a Tuple with one element is called “Singleton” tuple.
• A Set is a mutable and an unordered collection of elements without duplicates.
• A set is created by placing all the elements separated by comma within a pair of curly
brackets.
• A dictionary is a mixed collection of elements.

Hands on Experience

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

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

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

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

XII Std Computer Science 166

12th Computer Science_EM Chapter [Link] 166 21-12-2022 15:37:03


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

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

7. Write a program that creates a list of numbers from 1 to 50 that are either divisible by 3 or
divisible by 6.

8. Write a program to create a list of numbers in the range 1 to 20. Then delete all the numbers
from the list that are divisible by 3.

9. Write a program that counts the number of times a value appears in the list. Use a loop to
do the same.

10. Write a program that prints the maximum and minimum value in a dictionary.

Evaluation

Part - I

Choose the best answer (1 Marks)


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

167 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 167 21-12-2022 15:37:03


7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
print(S)
(a) [0,1,2,4,5]   (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple
(b) To know the type of an element in tuple.
(c) To know the data type of python object.
(d) To create a list.
9. Which of the following statement is not correct?
(a) A list is mutable
(b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a list.
10. Let setA = {3,6,9}, setB = {1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}
11. Which of the following set operation includes all the elements that are in two sets but not
the one that are common to two sets?
(a) Symmetric difference (b) Difference
(c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c) + (d) :

Part - II

Answer the following questions (2 Marks)


1. What is List in Python?
2. How will you access the list elements in reverse order?
3. What will be the value of x in following python code?
List1=[2,4,6[1,3,5]]
x=len(List1)
XII Std Computer Science 168

12th Computer Science_EM Chapter [Link] 168 21-12-2022 15:37:03


4. Differentiate del with remove() function of List.
5. Write the syntax of creating a Tuple with n number of elements.
6. What is set in Python?

Part - III

Answer the following questions (3 Marks)


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

Part - IV

Answer the following questions (5 Marks)


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

References
1. [Link]
2. [Link]
3. Python programming using problem solving approach – Reema Thareja – Oxford
University press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

169 Lists, Tuples, Sets and Dictionary

12th Computer Science_EM Chapter [Link] 169 21-12-2022 15:37:03


CHAPTER 10
Unit III
PYTHON CLASSES AND OBJECTS

Learning Objectives

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

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


Objects, Constructor and Destructor.

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

• Create classes with Constructors.

• Write complex programs in Python using classes.

10.1 Introduction

Python is an Object Oriented Programming language. Classes and Objects are the key
features of Object Oriented Programming. Theoretical concepts of classes and objects are very
similar to that of C++. But, creation and implementation of classes and objects is very simple
in Python compared to C++.
Class is the main building block in Python. Object is a collection of data and function
that act on those data. Class is a template for the object. According to the concept of Object
Oriented Programming, objects are also called as instances of a class. 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

XII Std Computer Science 170

12th Computer Science_EM Chapter [Link] 170 26-12-2022 16:45:44


Where, statement in a class definition may be a variable declaration, decision control,
loop or even a function definition. Variables defined inside a class are called as “Class Variable”
and functions are called as “Methods”. Class variable and methods are together known as
members of the class. The class members should be accessed through objects or instance of
class. A class can be defined anywhere in a Python program.
Example: Program to define a class
class Sample:
x, y = 10, 20 # class variables
In the above code, name of the class is Sample and it has two variables x and y having
the initial value 10 and 20 respectively. To access the values defined inside the class, you need
an object or instance of the class.

10.3 Creating Objects


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

Syntax:
Object_name = class_name( )

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

10.4 Accessing Class Members


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

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


class Sample:
x, y = 10, 20 #class variables
S=Sample( ) # class instantiation
print("Value of x = ", S.x)
print("Value of y = ", S.y)
print("Value of x and y = ", S.x+S.y)
Output :
Value of x = 10
Value of y = 20
Value of x and y = 30

171 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 171 26-12-2022 16:45:44


In the above code, the name of the class is Sample. Inside the class, we have assigned
the variables x and y with initial value 10 and 20 respectively. These two variables are called as
class variables or member variables of the class. In class instantiation process, we have created
an object S to access the members of the class. The first two print statements simply print the
value of class variable x and y and the last print statement add the two values and print the
result.

10.5 Class Methods


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

Note
• The statements defined inside the class must be properly indented.
• Parameters are the variables in the function definition.
• Arguments are the values passed to the function definition.

Example: Program to find total and average marks using class

class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable

def process(self): #class method


sum = Student.mark1 + Student.mark2 + Student.mark3
avg = sum/3
print("Total Marks = ", sum)
print("Average Marks = ", avg)
return

S=Student()
[Link]()

In the above program, after defining the class, an object S is created. The statement
[Link]( ), calls the function to get the required output.
XII Std Computer Science 172

12th Computer Science_EM Chapter [Link] 172 26-12-2022 16:45:44


Note that, we have declared three variables mark1, mark2 and mark3 with the values
45, 91, 71 respectively. We have defined a method named process with self argument, which
means, we are not going to pass any value to that method. First, the process method adds the
values of the class variables, stores the result in the variable sum, finds the average and displays
the result.
Thus the above code will show the following output.
Output
Total Marks = 207
Average Marks = 69.0
Example : program to check and print if the given number is odd or
even using class
class Odd_Even:
def check(self, num):
if num%2==0:
print(num," is Even number")
else:
print(num," is Odd number")
n=Odd_Even()
x = int(input("Enter a value: "))
[Link](x)
When you execute this program, Python accepts the value entered by the user
and passes it to the method check through object.
Output 1
Enter a value: 4
4 is Even number
Output 2
Enter a value: 5
5 is Odd number

10.6 Constructor and Destructor in Python


Constructor is the special function that is automatically executed when an object of a
class is created. In Python, there is a special function called “init” which act as a Constructor.
It must begin and end with double underscore. This function will act as an ordinary function;
but only difference is, it is executed automatically when the object is created. This constructor
function can be defined with or without arguments. This method is used to initialize the class
variables.
General format of _ _init_ _ method (Constructor function)
def _ _init_ _(self, [args ……..]):
<statements>

173 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 173 26-12-2022 16:45:44


Example : Program to illustrate Constructor
class name
class Sample: Parameter
def __init__(self, num):
print("Constructor of class Sample...")
[Link]=num Instance variable
print("The value is :", num)
S=Sample(10)
The above class “Sample”, has only a constructor with one parameter named as num.
When the constructor gets executed, first the print statement, prints the “Constructor of
class Sample….”, then, the passing value to the constructor is assigned to instance variable
[Link] = num and finally it prints the value passed along with the given string.
The above constructor gets executed automatically, when an object S is created with
actual parameter 10. Thus, the Python display the following output.
Constructor of class Sample...
The value is : 10
Class variable defined within constructor keep count of number of objects created with
the class.

Note

Instance variables are the variables whose value varies from object to object.
For every object, a separate copy of the instance variable will be created.
Instance variables are declared inside a method using the self keyword. In
the above example, we use constructor to define instance variable.

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


of objects created.
class Sample:
num=0 class variable
def __init__(self, var):
[Link]+=1
[Link]=var instance variable
print("The object value is = ", [Link])
print("The count of object created = ", [Link])

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

XII Std Computer Science 174

12th Computer Science_EM Chapter [Link] 174 26-12-2022 16:45:44


In the above program, class variable num is shared by all three objects of the class
Sample. It is initialized to zero and each time an object is created, the num is incremented by
1. Since, the variable shared by all objects, change made to num by one object is reflected in
other objects as well. Thus the above program produces the output given below.

Output
The object value is = 15
The count of object created = 1
The object value is = 35
The count of object created = 2
The object value is = 45
The count of object created = 3
Destructor is also a special method to destroy the objects. In Python, _ _del_ _( )
method is used as destructor. It is just opposite to constructor.
Example : Program to illustrate about the __del__( ) method
class Sample:
num=0
def __init__(self, var):
[Link]+=1
[Link]=var
print("The object value is = ", [Link])
print("The value of class variable is= ", [Link])
def __del__(self):
[Link]-=1
print("Object with value %d is exit from the scope"%[Link])
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.

10.7 Public and Private Data Members

The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.

175 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 175 26-12-2022 16:45:44


Example : Program to illustrate private and public variables
class Sample:
n1 = 12
__n2 = 14
def display(self):
print("Class variable 1 = ", self.n1)
print("Class variable 2 = ", self.__n2)
S=Sample()
[Link]()
print("Value 1 = ", S.n1)
print("Value 2 = ", S.__n2)

In the above program, there are two class variables n1 and n2 are declared. The variable
n1 is a public variable and n2 is a private variable. The display( ) member method is defined to
show the values passed to these two variables.

The print statements defined within class will successfully display the values of n1 and
n2, even though the class variable n2 is private. Because, in this case, n2 is called by a method
defined inside the class. But, when we try to access the value of n2 from outside the class
Python throws an error. Because, private variable cannot be accessed from outside the class.

Output
Class variable 1 = 12
Class variable 2 = 14
Value 1 = 12

Traceback (most recent call last):


File "D:/Python/[Link]", line 12, in <module>
print("Value 2 = ", S.__n2)
AttributeError: 'Sample' object has no attribute '__n2'

XII Std Computer Science 176

12th Computer Science_EM Chapter [Link] 176 26-12-2022 16:45:45


10.8 Sample Programs to illustrate classes and objects

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


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

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

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


uppercase, lowercase, vowels, consonants and spaces in the given string
class String:
def __init__(self):
[Link]=0
[Link]=0
[Link]=0
[Link]=0
[Link]=0
[Link]=""
def getstr(self):
[Link]=str(input("Enter a String: "))
def count (self):
for ch in [Link]:
if ([Link]()):
[Link]+=1
if ([Link]()):
[Link]+=1
if (ch in ('AEIOUaeiou'):
[Link]+=1

177 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 177 26-12-2022 16:45:45


if ([Link]()):
[Link]+=1
[Link] = [Link]+[Link] - self.
vowel
def display(self):
print("The given string contains...")
print("%d Uppercase letters"%[Link])
print("%d Lowercase letters"%[Link])
print("%d Vowels"%[Link])
print("%d Consonants"%[Link])
print("%d Spaces"%[Link])
S = String()
[Link]()
[Link]()
[Link]()
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

• Python is an Object Oriented Programming language.


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

XII Std Computer Science 178

12th Computer Science_EM Chapter [Link] 178 26-12-2022 16:45:45


Hands on Experience

1. Write a program using class to store name and marks of students in list and print total
marks.

2. Write a program using class to accept three sides of a triangle and print its area.

3. Write a menu driven program to read, display, add and subtract two distances.

Evaluation

Part - I

Choose the best answer (1 Mark)


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

179 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 179 26-12-2022 16:45:45


7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<>
(c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
[Link]=name
print ([Link])
S=Student(“Tamil”)
(a) Error (b) Tamil
(c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num
(c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor
(c) Initialize (d) Instantiation

Part -II

Answer the following questions (2 Marks)

1. What is class?
2. What is instantiation?
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
[Link]()
print(S.__num)
4. How will you create constructor in Python?
5. What is the purpose of Destructor?

XII Std Computer Science 180

12th Computer Science_EM Chapter [Link] 180 26-12-2022 16:45:45


Part -III

Answer the following questions (3 Marks)


1. What are class members? How do you define it?
2. Write a class with two private class variables and print the sum using a method.
3. Find the error in the following program to get the given output?
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del [Link]
[Link]()
Output
Fruit 1 = Apple, Fruit 2 = Mango
4. What is the output of the following program?
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
[Link]()
5. How to define constructor and destructor in Python?
Part -IV

Answer the following questions (5 Marks)


1. Explain about constructor and destructor with suitable example.

References
1. [Link]
2. [Link]
3. Python programming using problem solving approach – Reema Thareja – Oxford University
press.
4. Python Crash Course – Eric Matthes – No starch press, San Francisco.

181 Python Classes and Objects

12th Computer Science_EM Chapter [Link] 181 26-12-2022 16:45:45


CHAPTER 13
Unit IV
PYTHON AND CSV FILES

Learning Objectives

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


• Understand what is CSV?
• Able to import CSV files in python programs
• Execute and debug python programs

13.1 Introduction

Python has a vast library of modules that are included with its distribution. One among
the module is the CSV module which gives the Python programmer the ability to parse CSV
(Comma Separated Values) files. A CSV file is a human readable text file where each line
has a number of fields, separated by commas or some other delimiter. You can assume each
line as a row and each field as a column. The CSV module will be able to read and write the vast
majority of CSV files.
13.2 Difference between CSV and XLS file formats

The difference between Comma-Separated Values (CSV) and eXceL Sheets(XLS) file
formats is
Excel CSV
Excel is a binary file that holds information CSV format is a plain text format with a
about all the worksheets in a file, including series of values separated by commas.
both content and formatting
XLS files can only be read by applications CSV can be opened with any text editor
that have been especially written to read their in Windows like notepad, MS Excel,
format, and can only be written in the same OpenOffice, etc.
way.
Excel is a spreadsheet that saves files into its CSV is a format for saving tabular
own proprietary format viz. xls or xlsx information into a delimited text file with
extension .csv
Excel consumes more memory while Importing CSV files can be much faster, and
importing data it also consumes less memory

XII Std Computer Science 224

12th Computer Science_EM Chapter [Link] 224 23-12-2022 15:39:36


Files saved in excel cannot be opened or edited by text editors.

13.3 Purpose Of CSV File

CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
Since they're plain text, they're easier to import into a spreadsheet or another storage database,
regardless of the specific software you're using.
You can open CSV files in a spreadsheet program like Microsoft Excel or in a text editor
or through a database which make them easier to read.

Note
CSV File cannot store charts or graphs. It stores data but does not contain
formatting, formulas, macros, etc.

A CSV file is also known as a Flat File. Files in the CSV format can be
imported to and exported from programs that store data in tables, such as Microsoft
Excel or OpenOfficeCalc

13.4 Creating a CSV file using Notepad (or any text editor)

A CSV file is a text file, so it can be created and edited using any text editor, But more
frequently a CSV file is created by exporting a spreadsheet or database in the program that
created it.

13.4.1 Creating CSV Normal File


To create a CSV file in Notepad, First open a new file using
File →New or ctrl +N.
Then enter the data you want the file to contain, separating each value with a comma
and each row with a new line.
For example consider the following details
Topic1,Topic2,Topic3
one,two,three
Example1,Example2,Example3

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:

225 Python and CSV Files

12th Computer Science_EM Chapter [Link] 225 23-12-2022 15:39:36


Topic1 Topic2 Topic3

one two three


Example1 Example2 Example3

Fig. 13.4.1 CSV file when opened in MS-Excel

In the above CSV file, you can observe the fields of data were separated by commas. But
what happens if the data itself contains commas in it?
If the fields of data in your CSV file contain commas, you can protect them by enclosing
those data fields in double-quotes (“). The commas that are part of your data will then be kept
separate from the commas which delimit the fields themselves.

13.4.2 Creating CSV File That contains Comma With Data


For example, let’s say that one of our fields contain commas in the description. If our
data looked like the below example:

RollNo Name Address


12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai
12103 Ram Gopalapuram, Chennai

To retain the commas in “Address” column, you can enclose the fields in quotation
marks. For example:
RollNo, Name, Address
12101, Nivetha, “Mylapore, Chennai”
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

XII Std Computer Science 226

12th Computer Science_EM Chapter [Link] 226 23-12-2022 15:39:36


Roll No Name Address
12101 Nivetha Mylapore, Chennai
12102 Lavanya Adyar, Chennai

12103 Ram Gopalapuram, Chennai

Fig 13.4.2 (a) CSV Field data with comma in Excel

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

It should be written in CSV file as

RollNo, Name, Address


12101, Nivetha, “Mylapore
Chennai”
12102, Lavanya, “Adyar
Chennai”
12103, Ram, “Gopalapuram
Chennai”

227 Python and CSV Files

12th Computer Science_EM Chapter [Link] 227 23-12-2022 15:39:37


The Result will look like this

Roll No Name Address


Mylapore,
12101 Nivetha Chennai
12102 Lavanya Adyar,
Chennai
12103 Ram Gopalapuram,
Chennai

Fig 13.4.2 (b) CSV Field Data with newline in Excel

13.4.3 Creating CSV File That contains Double Quotes With Data
If your fields contain double-quotes as part of their data, the internal quotation
marks need to be doubled so that they can be interpreted correctly. For Example, given the
following data:

Roll No Name Favorite Sports Address


12101 Nivetha “Cricket”, “Football” Mylapore Chennai
12102 Lavanya “Basketball”, “Cricket” Adyar Chennai
12103 Ram “Soccer”, “Hockey” Gopala puram Chennai

It should be written in csv file as

RollNo, Name, FavoriteSports, Address


12101, Nivetha,””” Cricket ””,”” Football ”””, Mylapore chennai
12102, Lavanya,””” Basketball ””,”” Cricket ”””, Adyar chennai
12103, Ram,””” Soccer””,”” Hockey”””, Gopalapuram chennai

The output will be

XII Std Computer Science 228

12th Computer Science_EM Chapter [Link] 228 23-12-2022 15:39:37


Roll No Name Favorite Sports Address
12101 Nivetha "Cricket", "Football" Mylapore, Chennai
12102 Lavanya "Basketball", "Cricket" Adyar, Chennai
12103 Ram "Soccer", "Hockey" Gopalapuram, Chennai

Fig 13.4.3 CSV Field Data with Double quotes in Excel


13.4.4 Rules to be followed to format data in a CSV file
1. Each record (row of data) is to be located on a separate line, delimited by a line break by
pressing enter key. For example:
xxx,yyy
denotes enter Key to be pressed

2. The last record in the file may or may not have an ending line break. For example:

ppp, qqq
yyy, xxx

3. There may be an optional header line appearing as the first line of the file with the same
format as normal record lines. The header will contain names corresponding to the fields
in the file and should contain the same number of fields as the records in the rest of the
file. For example:

field_name1,field_name2,field_name3
aaa,bbb,ccc
zzz,yyy,xxx CRLF( Carriage Return and Line Feed)

229 Python and CSV Files

12th Computer Science_EM Chapter [Link] 229 23-12-2022 15:39:37


4. Within the header and each record, there may be one or more fields, separated by commas.
Spaces are considered part of a field and should not be ignored. The last field in the record
must not be followed by a comma. For example: Red , Blue
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:

"Red","Blue","Green" #Field data with doule quotes


Black,White,Yellow #Field data without doule quotes

6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes. For example:

Red, “,”, Blue CRLF # comma itself is a field [Link] 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.

13.5 Create A CSV File Using Microsoft Excel

To create a CSV file using Microsoft Excel, launch Excel and then open the file you
want to save in CSV format. For example, below is the data contained in our sample Excel
worksheet:

XII Std Computer Science 230

12th Computer Science_EM Chapter [Link] 230 23-12-2022 15:39:37


Item Name Cost - Rs Quantity Profit
Keyboard 480 12 1152
Monitor 5200 10 10400
Mouse 200 50 2000
Total Profit 13552

Fig 13.5 Sample Worksheet Data


Once the data is entered in the worksheet, select File → Save As option, and for the
“Save as type option”, select CSV (Comma delimited) or type the file name along with extension
.csv.
Saving excel file as CSV

Fig 13.6 Save As dialog box


After you save the file, you are free to open it up in a text editor to view it or to edit it
manually. Its contents will resemble the following:

231 Python and CSV Files

12th Computer Science_EM Chapter [Link] 231 23-12-2022 15:39:37


Item Name, Cost-Rs, Quantity, Profit
Keyboard, 480, 12, 1152
Monitor, 5200, 10, 10400
Mouse, 200, 50, 2000
,,Total Profit =,13552

13.5.1 Microsoft Excel to open a CSV file


If Microsoft Excel has been installed on the computer, by default CSV files should
open automatically in Excel when the file is double-clicked. If you are getting an Open With
prompt when opening the CSV file, choose Microsoft Excel from the available programs to
open the file.
Alternatively, you can open Microsoft Excel and in the menu bar, select File → Open,
and select the CSV file. If the file is not listed, make sure to change the file type to be opened
to Text Files (*.prn, *.txt, *.csv).

If both MS Excel and Open Office calc is installed in the computer, by


default the CSV file will be opened in MS Excel.

13.6 Read and write a CSV file Using Python

Python provides a module named CSV, using this you can do several operations on the
CSV files. The CSV library contains objects and other code to read, write, and process data
from and to CSV files.

CSV files have been used extensively in e-commerce applications because


they are considered very easy to process.

13.6.1 Read a CSV File Using Python


There are two ways to read a CSV file.
1. Use the csv module’s reader function
2. Use the DictReader class.
Two ways of Reading CSV File

reader () function Dict Reader class

Fig 13.7 Ways to read CSV file

XII Std Computer Science 232

12th Computer Science_EM Chapter [Link] 232 23-12-2022 15:39:37


When you want to read from or write to a file ,you need to open it. Once the reading
is over it needs to be closed. So that, resources that are tied with the file are freed. Hence, in
Python, a file operation takes place in the following order

Step 1 Open a file

Step 2 Perform Read or write operation

Step 3 Close the file

Note
File name or the complete path name can be represented either with in “ “ or in ‘ ‘
in the open command.

Python has a built-in function open() to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.

For Example

>>> f = open("[Link]") # open file in current directory and f is file object


>>> f = open('c:\pyprg\[Link]') # specifying full path

You can specify the mode while opening a file. In mode, you can specify whether you
want to read 'r', write 'w' or append 'a' to the file. you can also specify “text or binary” in which
the file is to be opened.

The default is reading in text mode. In this mode, while reading from the file the data
would be in the format of strings.

On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.

Python File Modes


Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if
it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.

233 Python and CSV Files

12th Computer Science_EM Chapter [Link] 233 23-12-2022 15:39:37


'a' Open for appending at the end of the file without truncating it. Creates a new file
if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)

f=open("[Link]")
#equivalent to 'r' or 'rt'
f = open("[Link]",'w') # write in text mode
f = open("[Link]",'r+b') # read and write in binary mode
Python has a garbage collector to clean up unreferenced objects but, one must not
rely on it to close the file.

f = open("[Link]") # since no mode is specified the default mode rt is used


# perform file operations
[Link]()

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("[Link]",’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("[Link]")
# perform file operations
[Link]()

[Link] CSV Module’s Reader Function


You can read the contents of CSV file with the help of [Link]() function. The reader
function is designed to take each line of the file and make a list of all columns. Then, you
just choose the column you want the variable data for. Using this function one can read data
from csv files of different formats like quotes (" "), pipe (|) and comma (,).
The syntax for [Link]() is

XII Std Computer Science 234

12th Computer Science_EM Chapter [Link] 234 23-12-2022 15:39:37


[Link](fileobject,delimiter,fmtparams)
where
file object :- passes the path and the mode of the file
delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
fmtparams: optional parameter which help to override the default values of the dialects like
skipinitialspace,quoting etc. Can be omitted

CSV file - data with default delimiter comma (,)


1

CSV file - data with Space at the beginning


2

CSV file - data with quotes


3

CSV file - data with custom Delimiters


4

[Link].1 CSV file with default delimiter comma (,)


The following program read a file called “[Link]” with default delimiter comma (,)
and print row by row.
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open('c:\pyprg\[Link]', 'r', newline‘=’) as F:
#other way to open the file is f= ('c:\pyprg\[Link]', 'r')
reader = [Link](F)
# printing each line of the Data row by row
for row in reader:
print(row)
[Link]()
OUTPUT
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']

[Link].2. CSV files- data with Spaces at the beginning


Consider the following file “[Link]” containing the following data when opened
through notepad
Topic1, Topic2, Topic3,
one, two, three
Example1, Example2, Example3

235 Python and CSV Files

12th Computer Science_EM Chapter [Link] 235 23-12-2022 15:39:37


The following program read the file through Python using “[Link]()”.

import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\[Link]','r')
reader = [Link](F, dialect='myDialect')
for row in reader:
print(row)
[Link]()

OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']

As you can see in “[Link]” there are spaces after the delimiter due to which the
output is also displayed with spaces.

These whitespaces can be removed, by registering new dialects using csv.register_dialect()


class of csv module. A dialect describes the format of the csv file that is to be read. In dialects
the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.

Note
By default “skipinitialspace” has a value false

The following program reads “[Link]” file, which contains spaces after the delimiter.

import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\pyprg\[Link]','r')
reader = [Link](F, dialect='myDialect')
for row in reader:
print(row)
[Link]()
OUTPUT
['Topic1', 'Topic2', 'Topic3']
['one', 'two', 'three']
['Example1', 'Example2', 'Example3']

XII Std Computer Science 236

12th Computer Science_EM Chapter [Link] 236 23-12-2022 15:39:37


Note
A dialect is a class of csv module which helps to define parameters for
reading and writing CSV. It allows you to create, store, and re-use various formatting
parameters for your data.

[Link].3 CSV File-Data With Quotes


You can read the csv file with quotes, by registering new dialects using csv.register_dialect()
class of csv module.
Here, we have [Link] file with following data.

SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."
3, "Work hard dream big never give up and believe yourself."
4, "Failure is the opportunity to begin again more intelligently."
5, "The successful warrior is the average man, with laser-like focus."

The following Program read “[Link]” file, where delimiter is comma (,) but the
quotes are within quotes (“ “).
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
f=open('c:\pyprg\[Link]','r')
reader = [Link](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.

237 Python and CSV Files

12th Computer Science_EM Chapter [Link] 237 23-12-2022 15:39:37


[Link].4 CSV files with Custom Delimiters
You can read CSV file having custom delimiter by registering a new dialect with the
help of csv.register_dialect().
In the following file called “[Link]”,each column is separated with | (Pipe symbol)

Roll No | Name | City


12101 | Arun | Chennai
12102 | Meena | Kovai
12103 | Ram | Nellai

The following program read the file “[Link]” with user defined delimiter “|”

import csv
csv.register_dialect('myDialect', delimiter = '|') OUTPUT
with open('c:\pyprg\[Link]', 'r', newline‘=’) as f: ['RollNo', 'Name', 'City']
reader = [Link](f, dialect='myDialect') ['12101', 'Arun', 'Chennai']
for row in reader: ['12102', 'Meena', 'Kovai']
print(row) ['12103', 'Ram', 'Nellai']
[Link]()

In the above program, a new dialects called myDialect is registered. Use the delimiter=|
where a pipe (|) is considered as column separator.

13.6.2 Read a specific column In a File


To get the specific columns like only Item Name and profit for the “[Link]” file .
Then you have to do the following:

import csv
#opening the csv file which is in different location with read mode
f=open("c:\pyprg\[Link]",'r')
#reading the File with the help of [Link]()
readFile=[Link](f)
#printing the selected column
for col in readFile :
print (col[0],col[3])
[Link]()
[Link] File in Excel

XII Std Computer Science 238

12th Computer Science_EM Chapter [Link] 238 23-12-2022 15:39:37


A B C D

1 item Nam Cost-Rs Quantity Profit


2 Keyboard 480 12 1152
3 Monitor 5200 10 10400
4 Mouse 200 50 2000

[Link] File with selected col

OUTPUT
Item Name Profit
Keyboard 1152
Monitor 10400
Mouse 2000

13.6.3 Read A CSV File And Store It In A List


In this topic you are going to read a CSV file and the contents of the file will be stored
as a list. The syntax for storing in the List is

list = [] # Start as the empty list


[Link](element) # Use append() to add elements

For example all the row values of “[Link]” file is stored in a list using the following
program

import csv
# other way of declaring the filename
inFile= 'c:\pyprg\[Link]'
F=open(inFile,'r')
reader = [Link](F)
# declaring array
arrayValue = []
# displaying the content of the list
for row in reader:
[Link](row)
print(row)
[Link]()
[Link] opened in MS-Excel

239 Python and CSV Files

12th Computer Science_EM Chapter [Link] 239 23-12-2022 15:39:37


A1 fx Topic 1

>
A B C
1 Topic 1 Topic 2 Topic 3
2 One two three
3 Example 1 Example 2 Example 3
4
OUTPUT
['Topic1', 'Topic2', 'Topic3']
[' one', 'two', 'three']
['Example1', 'Example2', 'Example3']

Note
A list is a data structure in Python that is a mutable, or changeable,
ordered sequence of elements.

List literals are written within square brackets [ ]. Lists work similarly to strings

13.6.4 Read A CSV File And Store A Column Value In A List For Sorting

In this program you are going to read a selected column from the “[Link]” file by
getting from the user the column number and store the content in a list.

XII Std Computer Science 240

12th Computer Science_EM Chapter [Link] 240 23-12-2022 15:39:37


Item Name Cost - Rs Quantity Profit
Keyboard 480 12 1152
Monitor 5200 10 10400
Mouse 200 50 2000

Fig 13.6.4 CSV file Data for a selected column for sorting

Since the row heading is also get sorted, to avoid that the first row should be skipped.
This is can be done by using the command “next()”. The list is sorted and displayed.

# sort a selected column given by user leaving the header column in


# descending order of value
import csv
# other way of declaring the filename
inFile= ‘c:\pyprg\[Link]’
# opening the csv file which is in the same location of where the current #
python file

241 Python and CSV Files

12th Computer Science_EM Chapter [Link] 241 23-12-2022 15:39:37


F=open(inFile,’r’)
# reading the File with the help of [Link]()
reader = [Link](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:
[Link](row[a])
[Link](reverse=True)
for row in arrayValue:
print (row)
[Link]()

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

list_name.sort() command arranges a list value in ascending order. list_name.


sort(reverse=True) is used to arrange a list in descending order

13.6.5 Sorting A CSV File With A Specified Column


In this program you are going to see the “[Link]” file’s entire content is transferred
to a list. Then the list of rows is sorted and displayed in ascending order of quantity. To sort
by more than one column you can use itemgetter with multiple indices: operator .itemgetter
(1,2), The content of “[Link]” is

XII Std Computer Science 242

12th Computer Science_EM Chapter [Link] 242 23-12-2022 15:39:37


[Link] in Excel screen

Item Name Quantity


Keyboard 48
Monitor 52
Mouse 20

[Link] in Notepad
ItemName ,Quantity
Keyboard, 48
Monitor,52
Mouse ,20

Fig 13.6.5 CSV file Data into a list for sorting

The following program do the task mentioned above using [Link](col_no)


#Program to sort the entire row by using a specified column.
# declaring multiple header files
import csv ,operator
#One more way to read the file
data = [Link](open(‘c:\pyprg\[Link]’))
next(data) #(to omit the header)
#using operator module for sorting multiple columns
sortedlist = sorted (data, key=[Link](1)) # 1 specifies we want to sort
# according to second column
for row in sortedlist:
print(row)
OUTPUT
[‘Mouse ‘, ‘20’]
[‘Keyboard ‘, ‘48’]
[‘Monitor’, ‘52’]

243 Python and CSV Files

12th Computer Science_EM Chapter [Link] 243 23-12-2022 15:39:38


Note
The sorted() method sorts the elements of a given item in a specific order –
Ascending or Descending. Sort() method which performs the same way as sorted().
Only difference, sort() method doesn’t return any value and changes the original list
itself.

Add one more column “cost” in “[Link]” and sort it in descending order
of cost by using the syntax
sortedlist = sorted(data, key=[Link](Col_number),reverse=True)

13.6.6 Reading CSV File Into A Dictionary


To read a CSV file into a dictionary can be done by using DictReader method of csv
module which works similar to the reader() class but creates an object which maps data to a
dictionary. The keys are given by the fieldnames as parameter. DictReader works by reading
the first line of the CSV and using each comma separated value in this line as a dictionary key.
The columns in each subsequent row then behave like dictionary values and can be accessed
with the appropriate key (i.e. fieldname).
If the first row of your CSV does not contain your column names, you can pass a
fieldnames parameter into the DictReader’s constructor to assign the dictionary keys manually.
The main difference between the [Link]() and DictReader() is in simple terms csv.
reader and [Link] work with list/tuple, while [Link] and [Link] work with
dictionary. [Link] and [Link] take additional argument fieldnames that are
used as dictionary keys.
For Example Reading “[Link]” file into a dictionary
import csv
filename = ‘c:\pyprg\[Link]’
input_file =[Link](open(filename,’r’))
for row in input_file:
print(dict(row)) #dict() to print data

OUTPUT
{‘ItemName ‘: ‘Keyboard ‘, ‘Quantity’: ‘48’}
{‘ItemName ‘: ‘Monitor’, ‘Quantity’: ‘52’}
{‘ItemName ‘: ‘Mouse ‘, ‘Quantity’: ‘20’}

In the above program, DictReader() is used to read “[Link]” 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

12th Computer Science_EM Chapter [Link] 244 23-12-2022 15:39:38


Remove the dict() function from the above program and use print(row).Check
you are getting the following output
OrderedDict([(‘ItemName ‘, ‘Keyboard ‘), (‘Quantity’, ‘48’)])
OrderedDict([(‘ItemName ‘, ‘Monitor’), (‘Quantity’, ‘52’)])
OrderedDict([(‘ItemName ‘, ‘Mouse ‘), (‘Quantity’, ‘20’)])

13.6.7 Reading CSV File With User Defined Delimiter Into A Dictionary
You can also register new dialects and use it in the DictReader() methods. Suppose
“[Link]” is in the following format
ItemName|Quantity
Keyboard|48
Monitor|52
Mouse|20
Then “[Link]” can be read into a dictionary by registering a new dialect

import csv
csv.register_dialect(‘myDialect’,delimiter = ‘|’,skipinitialspace=True)
filename = ‘c:\pyprg\ch13\[Link]’
with open(filename, ‘r’, newline‘=’) as csvfile:
reader = [Link](csvfile, dialect=’myDialect’)
for row in reader:
print(dict(row))
[Link]()

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

13.7 Writing Data Into Different Types in Csv Files

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

12th Computer Science_EM Chapter [Link] 245 23-12-2022 15:39:38


Creating A New Normal CSV File
1

Modifying An Existing File


2

Writing On A CSV File with Quotes


3

Writing On A CSV File with Custom Delimiters


4

Writing On A CSV File with Lineterminator


5

Writing On A CSV File with Quotechars


6

Writing CSV File Into A Dictionary


7

Getting Data At Runtime And Writing In a File


8

13.7.1 Creating A New Normal CSV File


When you have a set of data that you would like to store inside a CSV file, it’s time to do
the opposite and use the writer function.

The [Link]() 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 [Link]() is

[Link](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 “[Link]”
that uses, (comma) as a value separator.

XII Std Computer Science 246

12th Computer Science_EM Chapter [Link] 246 23-12-2022 15:39:38


Import csv
csvData = [[‘Student’, ‘Age’], [‘Dhanush’, ‘17’], [‘Kalyani’, ‘18’], [‘Ram’, ‘15’]]
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as CF:
writer = [Link](CF) # CF is the file object
[Link](csvData) # csvData is the List name
[Link]()

When you open the “[Link]” file with a text editor, it will show the content as
follows.
Student, Age
Dhanush, 17
Kalyani, 18
Ram, 15

In the above program, [Link]() 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 “[Link]”.

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.

13.7.2 Modifying An Existing File


Making some changes in the data of the existing file or adding more data is called
modification .For example the “[Link]” file contains the following data.
Roll No, Name, City
1, Harshini, Chennai
2, Adhith, Mumbai
3, Dhuruv, Bangalore
4, Krishna, Tiruchy
5, Venkat, Madurai

The following program modify the “[Link]” file by modifying the value of an
existing row in [Link]

247 Python and CSV Files

12th Computer Science_EM Chapter [Link] 247 23-12-2022 15:39:38


import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘[Link]’, ‘r’, newline‘=’) as readFile:
reader = [Link](readFile)
lines = list(reader) # list()- to store each row of data as a list
lines[3] = row
with open(‘[Link]’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = [Link](writeFile)
#writerows()method writes multiple rows to a csv file
[Link](lines)
[Link]()
[Link]()

When we open the [Link] file with text editor, then it will show:

Roll No, Name, City

1, Harshini, Chennai

2, Adhith, Mumbai

3, Meena, Bangalore

4, Krishna, Tiruchy

5, Venkat, Madurai

In the above program,the third row of “[Link]” is modified and saved. First the
“[Link]” file is read by using [Link]() 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 “[Link]”
file.

[Link] ADDING NEW ROW


Sometimes, you may need to add new rows in the existing CSVfile. Adding a new row
at the end of the file is called appending a row.
The following program add a new row to the existing “[Link]” file.

XII Std Computer Science 248

12th Computer Science_EM Chapter [Link] 248 23-12-2022 15:39:38


import csv
row = [‘6’, ‘Sajini ‘, ‘Madurai’]
with open(‘[Link]’, ‘a’, newline‘=’) as CF: # append mode to add data at the end
writer = [Link](CF)
[Link](row) # writerow() method write a single row of data in file
[Link]()

When “[Link]” file is opened with a text editor, it displays as follows

Roll No, Name, City

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 “[Link]”. 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 “[Link] file.”

The ‘w’ write mode creates a new file. If the file is already existing ‘w’ mode
over writs it. Where as ‘a’ append mode add the data at the end of the file if the file
already exists otherwise creates a new one

Note
writerow() takes 1-dimensional data (one row), and writerows takes 2-dimensional
data (multiple rows) to write in a file.

13.7.3 CSV Files With Quotes


You can write the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module. The following program explains this.

249 Python and CSV Files

12th Computer Science_EM Chapter [Link] 249 23-12-2022 15:39:38


import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],
[‘1’, ‘Madhu’, ‘18/12/2001’],
[‘2’, ‘Sowmya’,’19/2/1998’],
[‘3’, ‘Sangeetha’,’20/3/1999’],
[‘4’, ‘Eshwar’, ‘21/4/2000’],
[‘5’, ‘Anand’, ‘22/5/2001’]]
csv.register_dialect(‘myDialect’,quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as f:
writer = [Link](f, dialect=’myDialect’)
for row in info:
[Link](row)
[Link]()
When you open “[Link]” 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\[Link]’, ‘w’, newline‘=’) as f:
writer = [Link](f, dialect=’myDialect’)
for row in info:
[Link](row)
[Link]()

XII Std Computer Science 250

12th Computer Science_EM Chapter [Link] 250 23-12-2022 15:39:38


When we open “[Link]” file, we get the following output:

SNO|Person|DOB
1|Madhu|18/12/2001
2|Sowmya|19/2/1998
3|Sangeetha|20/3/1999
4|Eshwar|21/4/2000
5|Anand|22/5/2001
In the above program, a dialect with delimiter as pipe(|)is registered. Then the list “info”
is written into the CSV file “[Link]”.

Note
The dialect parameter skipinitialspace when it is True, whitespace immediately following
the delimiter is ignored. The default is False.

13.7.5 CSV File With A Line Terminator


A Line Terminator is a string used to terminate lines produced by writer. The default
value is \r or \n. We can write csv file with a line terminator in Python by registering new
dialects using csv.register_dialect() class of csv module. For Example

import csv
Data = [[‘Fruit’, ‘Quantity’], [‘Apple’, ‘5’], [‘Banana’, ‘7’], [‘Mango’, ‘8’]]
csv.register_dialect(‘myDialect’, delimiter = ‘|’, lineterminator = ‘\n’)
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as f:
writer = [Link](f, dialect=’myDialect’)
[Link](Data)
[Link]()

When we open the [Link] 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.

251 Python and CSV Files

12th Computer Science_EM Chapter [Link] 251 23-12-2022 15:39:38


Note
Python’s CSV module only accepts \r\n, \n or \r as line terminator

13.7.6 CSV File with quote characters


You can write the CSV file with custom quote characters, by registering new dialects
using csv.register_dialect() class of csv module.

import csv
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], [‘3’,’Pencil’]]
csv.register_dialect(‘myDialect’,delimiter = ‘|’,quotechar = ‘”’,
quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as csvFile:
writer = [Link](csvFile, dialect=’myDialect’)
[Link](csvData)
print(“writing completed”)
[Link]()

When you open the “[Link]” 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\[Link]’, ‘w’, newline‘=’) as CF:
fields = [‘MOUNTAIN’, ‘HEIGHT’]
w = [Link](CF, fieldnames=fields)
[Link]()
[Link](data)
print(“writing completed”)
[Link]()

XII Std Computer Science 252

12th Computer Science_EM Chapter [Link] 252 23-12-2022 15:39:38


When you open the “[Link]” 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 “[Link]” file.
[Link] Writing Dictionary Into CSV File With Custom Dialects
import csv
csv.register_dialect(‘myDialect’, delimiter = ‘|’, quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as csvfile:
fieldnames = [‘Name’, ‘Grade’]
writer = [Link](csvfile, fieldnames=fieldnames, dialect=”myDialect”)
[Link]()
[Link]([{‘Grade’: ‘B’, ‘Name’: ‘Anu’},
{‘Grade’: ‘A’, ‘Name’: ‘Beena’},
{‘Grade’: ‘C’, ‘Name’: ‘Tarun’}])
print(“writing completed”)

When we open [Link] file, it will contain following output:

“Name”|”Grade”
”Anu”|”B”
”Beena”|”A”
“Tarun”|”C”

In the above program, a custom dialect called myDialect with pipe (|) as delimiter uses
the fieldnames as headings of each column to write in a csv file. Finally, we use a DictWriter()
to write dictionary data into “[Link]” file.

13.7.8 Getting Data At Runtime And Writing It In a CSV File


You can even accept the data through keyboard and write in to a CSV file. For example
the following program accept data from the user through key board and stores it in the file
called “[Link]”. It also displays the content of the file.

253 Python and CSV Files

12th Computer Science_EM Chapter [Link] 253 23-12-2022 15:39:38


import csv
with open(‘c:\pyprg\ch13\[Link]’, ‘w’, newline‘=’) as f:
w = [Link](f)
ans=’y’
while (ans==’y’):
name = input(“Name?: “)
date = input(“Date of birth: “)
place = input(“Place: “)
[Link]([name, date, place])
ans=input(“Do you want to enter more y/n?: “)
F=open(‘c:\pyprg\ch13\[Link]’,’r’)
reader = [Link](F)
for row in reader:
print(row)
[Link]()

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

XII Std Computer Science 254

12th Computer Science_EM Chapter [Link] 254 23-12-2022 15:39:38


Points to remember:
• A CSV file is a human readable text file where each line has a number of fields, separated
by commas or some other delimiter
• Excel is a binary file whereas CSV format is a plain text format
• The two ways to read a CSV file are using [Link]() 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 [Link]() 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.
• [Link] and [Link] work with list/tuple, while [Link] and [Link]
work with dictionary .
• [Link] and [Link] 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 [Link]() 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.

255 Python and CSV Files

12th Computer Science_EM Chapter [Link] 255 23-12-2022 15:39:38


Hands on Experience
1. Write a Python program to read the following [Link] file and sort the data in
alphabetically order of names in a list and display the output

A B C
1 SNO NAME OCCUPATION
2 1 NIVETHITHA ENGINEER
3 2 ADHITH DOCTOR
4 3 LAVANYA SINGER
5 4 VIDHYA TEACHER
6 5 BINDHU LECTURER

2. Write a Python program to accept the name and five subjects mark of 5 students .Find
the total and store all the details of the students in a CSV file

Evaluation

Part - I

Choose the best answer (1 Mark)


1. A CSV file is also known as a ….
(A) Flat File (B) 3D File
(C) String File (D) Random File
2. The expansion of CRLF is
(A) Control Return and Line Feed
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed
3. Which of the following module is provided by Python to do several operations on the
CSV files?
(A) py (B) xls (C) csv (D) os
4. Which of the following mode is used when dealing with non-text files like image or exe
files?
(A) Text mode (B) Binary mode (C) xls mode (D) csv mode
5. The command used to skip a row in a CSV file is
(A) next() (B) skip() (C) omit() (D) bounce()

XII Std Computer Science 256

12th Computer Science_EM Chapter [Link] 256 23-12-2022 15:39:38


6. Which of the following is a string used to terminate lines produced by writer()method of
csv module?
(A) Line Terminator (B) Enter key
(C) Form feed (D) Data Terminator
7. What is the output of the following program? import csv
d=[Link](open('c:\PYPRG\ch13\[Link]'))
next(d)
for row in d:
print(row)
if the file called “[Link]” contain the following details

chennai,mylapore

mumbai,andheri

A) chennai,mylapore (B) mumbai,andheri


(C) chennai (D) chennai,mylapore
mumba mumbai,andheri
8. Which of the following creates an object which maps data to a dictionary?
(A) listreader() (B) reader() (C) tuplereader() (D) DictReader ()
9. Making some changes in the data of the existing file or adding more data is called
(A)Editing (B) Appending
(C)Modification (D) Alteration
10. What will be written inside the file [Link] using the following program
import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\[Link]', 'w') as f:
wr = [Link](f,dialect='M')
[Link](D)
[Link]()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly

257 Python and CSV Files

12th Computer Science_EM Chapter [Link] 257 23-12-2022 15:39:38


Part - II

Answer the following questions (2 Marks)


1. What is CSV File?
2. Mention the two ways to read a CSV file using Python.
3. Mention the default modes of the File.
4. What is use of next() function?
5. How will you sort more than one column from a csv file?Give an example statement.

Part - III

Answer the following questions (3 Marks)


1. Write a note on open() function of python. What is the difference between the two
methods?
2. Write a Python program to modify an existing file.
3. Write a Python program to read a CSV file with default delimiter comma (,).
4. What is the difference between the write mode and append mode.
5. What is the difference between reader()method and DictReader() class?

Part - IV

Answer the following questions (5 Marks)


1. Differentiate Excel file and CSV file.
2. Tabulate the different mode with its meaning.
3. Write the different methods to read a File in Python.
4. Write a Python program to write a CSV File with custom quotes.
5. Write the rules to be followed to format the data in a CSV file.

REFERENCES
1. Python for Data Analysis, Data Wrangling with Pandas, NumPy, and IPython By
William McKinney
2. CSV File Reading and Writing - Python 3.7.0 documentation
3. [Link]

XII Std Computer Science 258

12th Computer Science_EM Chapter [Link] 258 23-12-2022 15:39:38


CHAPTER 14
Unit V
IMPORTING C++ PROGRAMS IN PYTHON

Learning Objectives

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


• Understand what is wrapping
• Able to import C++ functions and classes in to Python programs
• Create environment to work with both languages
• Execute and debug Python programs

14.1 Introduction
Python and C++ are general-purpose programming language. However, Python is
quite different from C++.

[Link] PYTHON C++

1 Python is typically an "interpreted" C++ is typically a "compiled"


language language

2 Python is a dynamic-typed C++ is compiled statically typed


language language

3 Data type is not required while Data type is required while


declaring variable declaring variable

4 It can act both as scripting and general It is a general purpose language


purpose language

Yet these two languages complement one another perfectly. Python is mostly used as a
scripting or "glue", language. That is, the top level program mostly calls routines written in C
or C++. This is useful when the logic can be written in terms of existing code (For example a
program written in C++) but can be called and manipulated through Python program.

259
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 259 23-12-2022 11:08:38


14.2 Scripting Language
A scripting language is a programming language designed for integrating and
communicating with other programming languages. Some of the most widely used scripting
languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl. Since a scripting
language is normally used in conjunction with another programming language, they are often
found alongside HTML, Java or C++.
14.2.1 Difference between Scripting and Programming Languages
Scripting Language and Programming Language looks like the following picture.

9
6

Basically, all scripting languages are programming languages. The theoretical difference
between the two is that scripting languages do not require the compilation step and are rather
interpreted. For example, normally, a C++ program needs to be compiled before running
whereas, a scripting language like JavaScript or Python need not be compiled. A scripting
language requires an interpreter while a programming language requires a compiler. A given
language can be called as a scripting or programming language depending on the environment
they are put to use.

14.3 Applications of Scripting Languages

1. To automate certain tasks in a program


2. Extracting information from a data set
3. Less code intensive as compared to traditional programming language
4. can bring new functions to applications and glue complex systems together
Python is actually an interpreted, high-level, general-purpose programming language
that can be used on any modern computer operating system. It can be used for processing text,
numbers, images, scientific data and just about anything else you might save on a computer.
Now a days, large applications are written almost exclusively in Python.

XII Std Computer Science 260

12th Computer Science_EM Chapter [Link] 260 23-12-2022 11:08:38


14.4 Features of Python over C++

• Python uses Automatic Garbage Collection whereas C++ does not.


• C++ is a statically typed language, while Python is a dynamically typed language.
• Python runs through an interpreter, while C++ is pre-compiled.
• Python code tends to be 5 to 10 times shorter than that written in C++.
• In Python, there is no need to declare types explicitly where as it should be done in C++
• In Python, a function may accept an argument of any type, and return multiple values
without any kind of declaration beforehand. Whereas in C++ return statement can return
only one value.

Note
Python deletes unwanted objects (built-in types or class instances) automatically
to free the memory space. The process by which Python periodically frees and reclaims
blocks of memory that no longer are in use is called Garbage Collection.

14.5 Importing C++ Files in Python

Importing C++ program in a Python program is called wrapping up of C++ in Python.


Wrapping or creating Python interfaces for C++ programs are done in many ways. The
commonly used interfaces are
• Python-C-API (API-Application Programming Interface for interfacing with C
programs)
• Ctypes (for interfacing with c programs)
• SWIG (Simplified Wrapper Interface Generator- Both C and C++)
• Cython (Cython is both a Python-like language for writing
C-extensions)
• Boost. Python (a framework for interfacing Python and C++)
• MinGW (Minimalist GNU for Windows)

14.5.1 MinGW Interface


MinGW refers to a set of runtime header files, used in compiling and linking the code
of C, C++ and FORTRAN to be run on Windows Operating System.
MinGw-W64 (version of MinGW) is the best compiler for C++ on Windows. To compile
and execute the C++ program, you need ‘g++’ for Windows. MinGW allows to compile and
execute C++ program dynamically through Python program using g++.

261
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 261 23-12-2022 11:08:38


Python program that contains the C++ coding can be executed through either by using
command prompt or by using run terminal.

g++ is a program that calls GCC (GNU C Compiler) and automatically links the
required C++ library files to the object code.

Refer installation of MinGW in Annexure -2

14.5.2 Executing C++ Program through Python


1. Double click on the command prompt or the run terminal.

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 [Link] is a Python program which will read the C++program
[Link]. The “[Link]” 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 [Link]. Same way the Python
program [Link] code is also typed in notepad and saved as [Link].

3. To execute our program double click the run terminal change the path to the Python
folder location. The syntax to execute the Python program is

Python <[Link]> -i <C++ filename without cpp extension>

XII Std Computer Science 262

12th Computer Science_EM Chapter [Link] 262 23-12-2022 11:08:38


Where,

Python keyword to execute the Python program from command-


line

[Link] Name of the Python program to executed

-i input mode

C++ filename without name of C++ file to be compiled and executed


cpp extension

For example type Python [Link] –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 “[Link]”.

Now let us will see the execution through our example [Link] and [Link]. 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:\Program Files\migw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0>echo off


Microsoft windows [Version 6.1.7601]
copy right <c> 2009 Microsoft Corporation. All rights reserved.

C:\>cd Pyprg

C:\Pyprg> Python c:\pyprg\[Link]-i c:\pyprg\pali


Enter apositive number:232
The reverse of the number is:232
The number is a palindrome

C:\Pyprg> Python c:\pyprg\[Link] -i c:\pyprg\pali


Enter a positive number:234
The reverse of the number is:432
The number is not a palindrome

C:\Pyprg>

Fig 14.2

263
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 263 23-12-2022 11:08:38


Note
To clear the screen in command window use cls command

Now let us will see how to write the Python program for compiling C++ code.
14.6 Python Program to import C++

Python contains many modules. For a problem Python allow programmers to have the
flexibility in using different module as per their convenience. The Python program what we
have written contains a few new commands which we have not come across in basic Python
program. Since our program is an integration of two different languages, we have to import the
modules like os, sys and getopt.
14.6.1 MODULE
Modular programming is a software design technique to split your code into separate
parts. These parts are called modules. The focus for this separation should have modules with no
or just few dependencies upon other modules. In other words: Minimization of dependencies
is the goal.
But how do we create modules in Python? Modules refer to a file containing Python
statements and definitions. A file containing Python code, for e.g. [Link], 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

The above example is named as [Link]

XII Std Computer Science 264

12th Computer Science_EM Chapter [Link] 264 23-12-2022 11:08:38


14.6.2 How to import modules in Python?
We can import the definitions inside a module to another module. We use the import
keyword to do this. To import our previously defined module factorial we type the following
in the Python prompt.
>>> import factorial
Using the module name we can access the functions defined inside the module. The
dot (.) operator is used to access the functions. The syntax for accessing the functions from
the module is
<module name> . <function name>

For example:
>>> [Link](5)
120

factorial . fact (5)

Function call

Dot operator
Module name
Python has number of standard (built in) modules. Standard modules can be imported
the same way as we import our user-defined modules. We are now going to see the Standard
modules which are required for our program to run C++ code.
[Link] Python’s sys module
This module provides access to builtin variables used by the interpreter. One among the
variable in sys module is argv
[Link]
[Link] 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 [Link], import sys should be used. The first argument, [Link][0] contains the
name of the python program (example [Link]) and [Link] [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

12th Computer Science_EM Chapter [Link] 265 23-12-2022 11:08:38


main([Link][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.

[Link] Python's OS Module


The OS module in Python provides a way of using operating system dependent
functionality.
The functions that the OS module allows you to interface with the Windows operating
system where Python is running on.
[Link](): Execute the C++ compiling command (a string contains Unix, C command
which also supports C++ command) in the shell (Here it is Command Window). For Example
to compile C++ program g++ compiler should be invoked. To do so the following command
is used.

[Link] (‘g++ ’ + <variable_name1> +‘ -<mode> ’ + <variable_name2>)

where each argument contains

function system() defined in os module to interact with the


[Link] :-
operating system

General compiler to compile C++ program under Windows


g++ :-
Operating system.

Name of the C++ file along with its path and without extension
variable_name1:-
in string format

To specify input or output mode. Here it is o prefixed with


mode :-
hyphen.

variable_name2 :- Name of the executable file without extension in string format

For example the command to compile and execute C++ program is given below

g++ compiler compiles the file cpp_file and –o


[Link]('g++ ' + cpp_file + ' -o ' + exe_file)
(output) send to exe_file

Note
‘+’ in [Link]() 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

XII Std Computer Science 266

12th Computer Science_EM Chapter [Link] 266 23-12-2022 11:08:38


[Link].3 Python getopt module
The getopt module of Python helps you to parse (split) command-line options and
arguments. This module provides getopt() method to enable command-line argument parsing.
[Link] function
This function parses command-line options and parameter list. Following is the syntax
for this method −
<opts>,<args>=[Link](argv, options, [long_options])

Here is the detail of the parameters −


argv − This is the argument list of values to be parsed (splited). In our
program the complete command will be passed as a list. For example
c:\pyprg\[Link] -i c:\pyprg\pali_cpp
options − This is string of option letters that the Python program recognize as, for input or for
output, with options (like ‘i’ or ‘o’) that followed by a colon (:). Here colon is used
to denote the mode.
long_options −This contains a list of strings. Argument of Long options should be followed
by an equal sign '='. In our program the C++ file name along with its path
will be passed as string and ‘i’ i will be also passed to indicate it as the input
file.
getopt() method returns value consisting of two elements. Each of these values are
stored separately in two different list (arrays) opts and args .Opts contains list of splitted strings
like mode and path. args contains error string, if at all the comment is given with wrong path
or mode. args will be an empty list if there is no error.
For example The Python code which is going to execute the C++ file p4 in command
line will have the getopt() method like the following one.
opts, args = [Link] (argv, "i:",['ifile='])

where opts contains [('-i', 'c:\\pyprg\\p4')]

-i :- option - mode should be followed by : (colon)

'c:\\pyprg\\p4' value - absolute path of C++ file.

In our examples since the entire command line commands are parsed and no leftover
argument, the second argument args will be empty []. If args is displayed using print()
command it displays the output as [].

>>>print(args)
[]

267
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 267 23-12-2022 11:08:38


Note
You can check out the full list of Python standard modules and what they are
for. These files are in the Lib directory inside the location where Python is installed.

Some more command for wrapping C++ code

if __name__=='__main__':
main([Link][1:])

__name__ (A Special variable) in Python


Since there is no main() function in Python, when the command to run a Python
program is given to the interpreter, the code that is at level 0 indentation (top must line of
the program) is to be executed. However, before doing that, interpreter will define a few
special variables. __name__ is one such special variable which by default stores the name
of the Python file. If the source file is executed as the main program, the interpreter sets the
__name__ variable to have a value “__main__”.
__name__ is a built-in variable which evaluates to the name of the current module.
Thus it can be used to check whether the current script is being run on its own.
For example consider the following

if __name__ == '__main__':
main ([Link][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
[Link][1:] - get everything after the script name(file name).
[Link][0] is the script name (python program)
Remember “string slicing” you have studied in chapter 8.

14.7 Python program Executing C++ Program using control statement

Now let us write a Python program to read a C++ coding and execute its result. The steps
for executing the C++ program to check a given number is palindrome or not is given below

XII Std Computer Science 268

12th Computer Science_EM Chapter [Link] 268 23-12-2022 11:08:38


Type the C++ program to check whether the input number is
Step 1 palindrome or not in notepad and save it as “pali_cpp.cpp”.

Type the Python program and save it as [Link]


Step 2

Click the Run Terminal and open the command window


Step 3

Type the command Python [Link] -i pali_cpp


Step 4

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

12th Computer Science_EM Chapter [Link] 269 23-12-2022 11:08:38


#Now select File→New in Notepad and type the Python program
# Save the File as [Link] . Program that compiles and executes a .cpp file
# Python c:\pyprg\[Link] -i c:\pyprg\pali_cpp
import sys, os, getopt
def main(argv):
opts, args = [Link](argv, "i:")
for o, a in opts:
if o in "-i":
run(a)

def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
[Link]('g++ ' + inp_file + ' -o ' + exe_file)
[Link](exe_file)
if __name__=='__main__':
main([Link][1:])

Output of the above program


Output 1
C:\Users\Dell>python c:\pyprg\[Link] -i c:\pyprg\pali_cpp
Enter a positive number: 56765
The reverse of the number is: 56765
The number is a palindrome

Output 2
C:\Users\Dell>python c:\pyprg\[Link] -i c:\pyprg\pali_cpp
Enter a positive number: 56756
The reverse of the number is: 65765
The number is not a palindrome

XII Std Computer Science 270

12th Computer Science_EM Chapter [Link] 270 23-12-2022 11:08:38


Python code How does it works
import sys, os, getopt include sys , os and getopt modules to
use the required function
def main(argv): Function main() is defined and 'argv'
contains the 'input mode and the c++
program file' in the form of list i.e ['-i',
'c:\ pyprg \pali_cpp']
opts, args = [Link](argv, "i:") getopt() splits the command as option
and argument. ‘opts’ contains
[('-i', 'c:\pyprg\pali_cpp')]. Since no error
‘args’ shows []
for o, a in opts: ‘o’ contains the mode and ‘a’ contains the
path of c++ program i.e
print("o = ",o) shows o = -i
print("a = ",a) shows a = c:\pyprg\pali_cpp
if o in ("-i"): Checks o == ‘i’ if true
run(a) Calls the function run() passed along
with the c++ program
def run(a): Definition of run() function begins here
inp_file=a+'.cpp' Variable ‘inp_file’ contains the joined c++
program name and .cpp
print( inp_file) shows c:\pyprg\pali_cpp.cpp
exe_file=a+'.exe' Variable ’exe_file’ contains the joined c++
program name and .exe
print( exe_file) shows c:\pyprg\pali_cpp.exe
[Link]('g++ ' + inp_file + ' -o ' + exe_file) g++ compiler compiles the c++ program
in inp_file and store the executable file in
exe_file
[Link](exe_file) Executes the exe file
if __name__=='__main__': __name__ stores name of the python
program
__ main__ also stores the name of the
python program.
main([Link][1:]) If 'name' and 'main' are equal then main()
is called and passed with the command line
argument omitting the python program name
argv[1:] contains –i c:\pyprg\pali_cpp

271
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 271 23-12-2022 11:08:38


The Python script(program) is mainly used to read the C++ file along with the type
of mode like ‘i’/’o’. ‘getopt()’ Parses(splits) each value of the command line and passes the
options(values) as list to ‘opt’ and since no error ‘args’ generates empty list[]. Using ‘for loop’
the tuple in the list is unpacked - ‘o’ stores the mode and ‘a’ stores the name along with the path
of the c++ file.
The variable ‘inp_file’ store the c++ file along with its extension and ‘exe_file’ stores the
executable file with .exe extension. ‘+’ usd in this program helps to concatenate the file name
with the extensions. ‘[Link]()’ 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.

14.8 How Python is handling the errors in C++

Python not only execute the successful C++ program, it also helps to display even errors
if any in C++ statement during compilation. For example in the following C++ program an
error is there. Let us see what happens when you compile through Python.
Example 14.8.1
// C++ program to print the message Hello
//Now select File→New in Notepad and type the C++ program
#include<iostream>
using namespace std;
int main()
{
std::cout<<"hello"
return 0;
}
// Save this file as [Link]
# Now select File→New in Notepad and type the Python program as [Link]
# Program that compiles and executes a .cpp file
# Python [Link] -i hello
import sys, os, getopt
def main(argv):
opts, args = [Link](argv, "i:")
for o, a in opts:
if o in "-i":
run(a)

XII Std Computer Science 272

12th Computer Science_EM Chapter [Link] 272 23-12-2022 11:08:39


def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
[Link]('g++ ' + inp_file + ' -o ' + exe_file)
[Link](exe_file)
if __name__=='__main__':
main([Link][1:])

Output of the above program


C:\Users\Dell>python c:\pyprg\[Link] -i c:\pyprg\hello
c:\pyprg\[Link]: In function 'int main()':
c:\pyprg\[Link]:19: error: expected ';' before 'return'
std::cout<<"hello"
^
;
return 0;
~~~~~~
'c:\pyprg\[Link]' is not recognized as an internal or external command,
operable program or batch file.

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

12th Computer Science_EM Chapter [Link] 273 23-12-2022 11:08:39


Points to remember:
• The dot (.) operator is used to access the functions of a imported module
• sys module provides access to some variables used by the interpreter and to functions
that interact with the interpreter
• OS module in Python provides a way of using operating system dependent functionality
• The getopt module of Python helps you to parse (split) command-line options and
arguments

Hands on Experience

1. Write a C++ program to create a class called Student with the following details
Protected member
Rno integer
Public members
void Readno(int); to accept roll number and assign to Rno
void Writeno(); To display Rno.
The class Test is derived Publically from the Student class contains the following details
Protected member
Mark1 float
Mark2 float
Public members
void Readmark(float, float); To accept mark1 and mark2
void Writemark(); To display the marks
Create a class called Sports with the following detail
Protected members
score integer
Public members
void Readscore(int); To accept the score
void Writescore(); To display the score
The class Result is derived Publically from Test and Sports class contains the following
details
Private member
Total float

XII Std Computer Science 274

12th Computer Science_EM Chapter [Link] 274 23-12-2022 11:08:39


Public member
void display() assign the sum of mark1, mark2, score in total.
invokeWriteno(), Writemark() and Writescore(). Display the total also.
Save the C++ program in a file called hybrid. Write a python program to execute the
[Link]
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 [Link]

Evaluation

Part - I

Choose the best answer (1 Mark)


1. Which of the following is not a scripting language?
(A) JavaScript (B) PHP
(C) Perl (D) HTML
2. Importing C++ program in a Python program is called
(A) wrapping (B) Downloading
(C) Interconnecting (D) Parsing

3. The expansion of API is


(A) Application Programming Interpreter
(B) Application Programming Interface
(C) Application Performing Interface
(D) Application Programming Interlink

4. A framework for interfacing Python and C++ is


(A) Ctypes (B) SWIG
(C) Cython (D) Boost

5. Which of the following is a software design technique to split your code into separate
parts?
(A) Object oriented Programming
(B) Modular programming
(C) Low Level Programming
(D) Procedure oriented Programming
275
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 275 23-12-2022 11:08:39


6. The module which allows you to interface with the Windows operating system is
(A) OS module      (B) sys module
(c) csv module      (d) getopt module
7. getopt() will return an empty array if there is no error in splitting strings to
(A) argv variable      (B) opt variable
(c)args variable     (d) ifile variable
8. Identify the function call statement in the following snippet.
if __name__ =='__main__':
main([Link][1:])
(A) main([Link][1:]) (B) __name__
(C) __main__ (D) argv
9. Which of the following can be used for processing text, numbers, images, and scientific
data?
(A) HTML (B) C
(C) C++ (D) PYTHON
10. What does __name__ contains ?
(A) c++ filename (B) main() name
(C) python filename (D) os module name

Part - II

Answer the following questions (2 Marks)


1. What is the theoretical difference between Scripting language and other programming
language?
2. Differentiate compiler and interpreter.
3. Write the expansion of (i) SWIG (ii) MinGW
4. What is the use of modules?
5. What is the use of cd command. Give an example.

Part - III

Answer the following questions (3 Marks)


1. Differentiate PYTHON and C++
2. What are the applications of scripting language?

XII Std Computer Science 276

12th Computer Science_EM Chapter [Link] 276 23-12-2022 11:08:39


3. What is MinGW? What is its use?
4. Identify the module ,operator, definition name for the following
[Link]()
5. What is [Link]? What does it contain?

Part - IV

Answer the following questions (5 Marks)


1 Write any 5 features of Python.
2. Explain each word of the following command.
Python <[Link]> -<i> <C++ filename without cpp extension>
3. What is the purpose of sys,os,getopt module in [Link]
4. Write the syntax for getopt() and explain its arguments and return values
5. Write a Python program to execute the following c++ coding
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file [Link]

REFERENCES
1. Learn Python The Hard Way by Zed Shaw
2. Python Programming Advanced by Adam Stuart or Powerful Python by Aaron Maxwell
3. [Link]

277
Importing C++ Programs in Python

12th Computer Science_EM Chapter [Link] 277 23-12-2022 11:08:39


CHAPTER 15
Unit V
DATA MANIPULATION THROUGH SQL

Learning Objectives

After the completion of this chapter, the student will be able to write Python script to
• Create a table and to add new rows in the database.
• Update and Delete record in a table
• Query the table
• Write the Query in a CSV file

15.1 Introduction
A database is an organized collection of data. The term "database" can both refer to the
data themselves or to the database management system. The Database management system is
a application software for the interaction between users and the databases. Users don't have
to be human users. They can be other programs and applications as well. We will learn how
Python program can interact as a user of an SQL database.

15.2 SQLite
SQLite is a simple relational database system, which saves its data in regular data
files within internal memory of the computer. It is designed to be embedded in applications,
instead of using a separate database server program such as MySQLor Oracle. SQLite is fast,
rigorously tested, and flexible, making it easier to work. Python has a native library for SQLite.
To use SQLite,

import sqlite3
Step 1

Step 2 create a connection using connect () method and pass the name of the database File

Step 3
Set the cursor object cursor = connection. cursor ()

• Connecting to a database in step2 means passing the name of the database to be accessed.
If the database already exists the connection will open the same. Otherwise, Python will
open a new database file with the specified name.

XII Std Computer Science 278

12th Computer Science_EM Chapter [Link] 278 23-12-2022 15:33:41


• Cursor in step 3: is a control structure used to traverse and fetch the records of the
database.
• Cursor has a major role in working with Python. All the commands will be executed
using cursor object only.
To create a table in the database, create an object and write the SQL command in it.
Example:- sql_comm = "SQL statement"

For executing the command use the cursor method and pass the required sql command
as a parameter. Many number of commands can be stored in the sql_comm and can be executed
one after other. Any changes made in the values of the record should be saved by the commend
"Commit" before closing the "Table connection".
15.3 Creating a Database using SQLite

The following example explains how a connection to be made to a database through


Python sqlite3
# Python code to demonstrate table creation and insertions with SQL
# importing module
import sqlite3
# connecting to the database
connection = [Link] ("[Link]")
# cursor
cursor = [Link]()

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."[Link]
('[Link]')" is again used in some program, "connect" command just opens the already
created database.

15.3.1 Creating a Table


After having created an empty database, you will most probably add one or more tables
to this database. The SQL syntax for creating a table "Student" in the database "Academy" looks
like as follows :

CREATE TABLE Student (

Rollno INTEGER, Sname VARCHAR(20), Grade CHAR(1), gender CHAR(1),

Average float(5, 2), birth_date DATE, PRIMARY KEY (Rollno) );


This is the way, somebody might do it on a SQL command shell. Of course, we want to
do this directly from Python. To be capable to send a command to "SQL", or SQLite, we need a

279
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 279 23-12-2022 15:33:41


cursor object. Usually, a cursor in SQL and databases is a control structure to traverse over
the records in a database. So it's used for the fetching of the results.

Note
Cursor is used for performing all SQL commands.

The cursor object is created by calling the cursor() method of connection. The cursor is
used to traverse the records from the result set. You can define a SQL command with a triple
quoted string in Python. The reason behind the triple quotes is sometime the values in the
table might contain single or double quotes.

Example 15.3.1

sql_command = """
CREATE TABLE Student (
Rollno INTEGER PRIMARY KEY ,
Sname VARCHAR(20),
Grade CHAR(1),
gender CHAR(1),
Average DECIMAL(5,2),
birth_date DATE);"""

In the above example the Rollno field as "INTEGER PRIMARY KEY" A column which
is labeled like this will be automatically auto-incremented in SQLite3. To put it in other words:
If a column of a table is declared to be an INTEGER PRIMARY KEY, then whenever a
NULL will be used as an input for this column, the NULL will be automatically converted
into an integer which will one larger than the highest value so far used in that column. If
the table is empty, the value 1 will be used.

15.3.2 Adding Records


To populate (add record) the table "INSERT" command is passed to SQLite. “execute”
method executes the SQL command to perform some action. The following example 15.3.2 is
a complete working example. To run the program you should uncomment the "DROP TABLE"
line in the SQL command, if the program has been executed already.

XII Std Computer Science 280

12th Computer Science_EM Chapter [Link] 280 23-12-2022 15:33:41


Example 15.3.2 -1

import sqlite3

connection = [Link] ("[Link]")

cursor = [Link]()

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

[Link](sql_command)

sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average,


birth_date) VALUES (NULL, "Akshay", "B", "M","87.8", "2001-12-12");"""

[Link](sql_command)

sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average,


birth_date) VALUES (NULL, "Aravind", "A", "M","92.50","2000-08-17");"""

[Link](sql_command)

# never forget this, if you want the changes to be saved:

[Link]()

[Link]()

print("STUDENT TABLE CREATED")

OUTPUT

STUDENT TABLE CREATED

Of course, in most cases, you will not literally insert data into a SQL table. You will
rather have a lot of data inside of some Python data type e.g. a dictionary or a list, which has
to be used as the input of the insert statement.

The following working example, assumes that you have an already existing database
[Link] 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

12th Computer Science_EM Chapter [Link] 281 23-12-2022 15:33:41


Example 15.3.2-2

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
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])
[Link](sql_command)
[Link]()
[Link]()
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.

15.4 SQL Query Using Python

The time has come now to finally query our “Student” table. Fetching the data from
record is as simple as inserting them. The execute method uses the SQL command to get all
the data from the table.
15.4.1 SELECT Query
“Select” is the most commonly used statement in SQL. The SELECT Statement in SQL
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

12th Computer Science_EM Chapter [Link] 282 23-12-2022 15:33:41


If you run the program 15.4.1-1, you would get the following result, depending on the
actual data:
It should be noted that the database file that will be created will be in the same folder as
that of the python file. If we wish to change the path of the file, change the path while opening
the file.
Example 15.4.1-1
#save the file as “sql_Academy_query.py”
import sqlite3
connection = [Link]("[Link]")
crsr = [Link]()
# execute the command to fetch all the data from the table Student
[Link]("SELECT * FROM Student")
# store all the fetched data in the ans variable
ans= [Link]()
# loop to print all the data
for i in ans:
print(i)

[Link] Displaying all records using fetchall()


The fetchall() method is used to fetch all rows from the database table

Example [Link]-2

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM student")
print("fetchall:")
result = [Link]()
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

12th Computer Science_EM Chapter [Link] 283 23-12-2022 15:33:41


Note
[Link]() -fetchall () method is to fetch all rows from the database table
[Link]() - The fetchone () method returns the next row of a query result set or
None in case there is no row left.
[Link]() method that returns the next number of rows (n) of the result set

[Link] Displaying A record using fetchone()


The fetchone() method returns the next row of a query result set or None in case there
is no row left.

Example [Link]-1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM student")
print("\nfetch one:")
res = [Link]()
print(res)
OUTPUT
fetch one:
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')

[Link] Displaying all records using fetchone()


Using while loop and fetchone() method we can display all the records from a table.

Example [Link] -1
import sqlite3 OUTPUT
connection = [Link]("[Link]") fetching all records one by one:
cursor = [Link]() (1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
[Link]("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 = [Link]() (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 = [Link]() (7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')

XII Std Computer Science 284

12th Computer Science_EM Chapter [Link] 284 23-12-2022 15:33:41


[Link] Displaying Specified number of records using fetchmany(n)
Displaying specified number of records is done by using fetchmany(n). This method
returns the number of rows of the result set.

Example [Link]-1: Program to display the content of tuples using fetchmany()

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM student")
print("fetching first 3 records:")
result = [Link](3)
print(result)
OUTPUT
fetching first 3 records:
[(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12'), (2, 'Aravind', 'A', 'M', 92.5, '2000-08-17'), (3,
'BASKAR', 'C', 'M', 75.2, '1998-05-17')]

Example [Link]-2: Program to display the content of tuples in newline without


using loops

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM student")
print("fetching first 3 records:")
result = [Link](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

12th Computer Science_EM Chapter [Link] 285 23-12-2022 15:33:41


15.4.2 CLAUSES IN SQL
SQL provides various clauses that can be used in the SELECT statements. This clauses
can be called through python script. Almost all clauses will work with SQLite. The following
frequently used clauses are discussed here
• DISTINCT
• WHERE
• GROUP BY
• ORDER BY.
• HAVING

[Link] SQL DISTINCT Keyword


The distinct keyword is helpful when there is need of avoiding the duplicate values
present in any specific columns/table. When we use distinct keyword only the unique values
are fetched. In this example we are going to display the different grades scored by students
from “student table”.

Example [Link]-1

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT DISTINCT (Grade) FROM student")
result = [Link]()
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.

[Link] SQL WHERE CLAUSE


The WHERE clause is used to extract only those records that fulfill a specified condition.
In this example we are going to display the different grades scored by male students from
“student table”

XII Std Computer Science 286

12th Computer Science_EM Chapter [Link] 286 23-12-2022 15:33:41


import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = [Link]()
print(*result,sep="\n")

OUTPUT
('B',)
('A',)
('C',)
('D',)

[Link] SQL Group By Clause


The SELECT statement can be used along with GROUP BY clause. The GROUP BY
clause groups records into summary rows. It returns one records for each group. It is often
used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by
one or more columns. The following example count the number of male and female from the
student table and display the result.

Example [Link] -1

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT gender,count(gender) FROM student Group BY gender")
result = [Link]()
print(*result,sep="\n")

OUTPUT
('F', 2)
('M', 5)

[Link] SQL ORDER BY Clause


The ORDER BY Clause can be used along with the SELECT statement to sort the data
of specific fields in an ordered way. It is used to sort the result-set in ascending or descending
order. In this example name and Rollno of the students are displayed in alphabetical order of
names

287
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 287 23-12-2022 15:33:41


Example [Link] -1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT Rollno,sname FROM student Order BY sname")
result = [Link]()
print(*result,sep="\n")

OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(6, 'PRIYA')
(4, 'SAJINI')
(7, 'TARUN')
(5, 'VARUN')

[Link] SQL HAVING Clause


Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but can be used only with group functions. Group functions cannot be
used in WHERE Clause but can be used in HAVING clause.
Example [Link] -1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY
GENDER HAVING COUNT(GENDER)>3")
result = [Link]()
co = [i[0] for i in [Link]]
print(co)
print(result)
OUTPUT
['gender', 'COUNT(GENDER)']
[('M', 5)]

15.5 The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators. The AND
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”

XII Std Computer Science 288

12th Computer Science_EM Chapter [Link] 288 23-12-2022 15:33:41


Example for WHERE WITH NOT Operator
Example 15.5 -1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT * FROM student where NOT Grade='A' and NOT
Grade='B'")
result = [Link]()
print(*result,sep="\n")

OUTPUT
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')

Example for WHERE WITH AND Operator


In this example we are going to display the name, Rollno and Average of students who
have scored an average between 80 to 90% (both limits are inclusive)
Example 15.5 -2

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT Rollno, Sname, Average FROM student WHERE
(Average>=80 AND Average<=90)")
result = [Link]()
print(*result,sep="\n")

OUTPUT
(1, 'Akshay', 87.8)
(5, 'VARUN', 80.6)

Example for WHERE WITH OR Operator


In this example we are going to display the Rollno and name of students who have not
scored an average between 60 to 70%

289
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 289 23-12-2022 15:33:41


Example 15.5 -3

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT Rollno, Sname FROM student WHERE (Average<60
OR Average>70)")
result = [Link]()
print(*result,sep="\n")

OUTPUT
(1, 'Akshay')
(2, 'Aravind')
(3, 'BASKAR')
(4, 'SAJINI')
(5, 'VARUN')
(6, 'PRIYA')

15.6 Querying A Date Column

In this example we are going to display the rollno, name and grade of students who have
born in the year 2001
Example 15.6 -1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT Rollno, Sname, grade FROM student
WHERE(Birth_date>='2001-01-01' AND Birth_date<='2001-12-31')")
result = [Link]()
print(*result,sep="\n")
OUTPUT
(1, 'Akshay', 'B')
(5, 'VARUN', 'B')

15.7 Aggregate Functions

These functions are used to do operations from the values of the column and a single
value is returned.

XII Std Computer Science 290

12th Computer Science_EM Chapter [Link] 290 23-12-2022 15:33:41


• COUNT() • AVG()
• SUM() • MAX()
• MIN()
15.7.1 COUNT() function
The SQL COUNT() function returns the number of rows in a table satisfying the criteria
specified in the WHERE clause. COUNT() returns 0 if there were no matching rows.

Example 15.7.1-1

Example 1 : In this example we are going to count the number of records(rows)


import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT COUNT(*) FROM student ")
result = [Link]()
print(result)
Output:
[(7,)]

EXAMPLE 15.7.1-2

Example 2 : In this example we are going to count the number of records by


specifying a column
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT COUNT(AVERAGE) FROM student ")
result = [Link]()
print(result

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

12th Computer Science_EM Chapter [Link] 291 23-12-2022 15:33:41


15.7.2AVG():
The following SQL statement in the python program finds the average mark of all
students.

Example 15.7.2-1

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT AVG(AVERAGE) FROM student ")
result = [Link]()
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 = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT SUM(AVERAGE) FROM student ")
result = [Link]()
print(result)

OUTPUT
[(592.6,)]

Note
NULL values are ignored.

XII Std Computer Science 292

12th Computer Science_EM Chapter [Link] 292 23-12-2022 15:33:41


15.7.4 MAX() AND MIN() FUNCTIONS
The MAX() function returns the largest value of the selected column.
The MIN() function returns the smallest value of the selected column.
The following example show the highest and least average student’s name.

Example 15.7.4-1

import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
print("Displaying the name of the Highest Average")
[Link]("SELECT sname,max(AVERAGE) FROM student ")
result = [Link]()
print(result)
print("Displaying the name of the Least Average")
[Link]("SELECT sname,min(AVERAGE) FROM student ")
result = [Link]()
print(result)

OUTPUT
Displaying the name of the Highest Average
[('PRIYA', 98.6)]
Displaying the name of the Least Average
[('TARUN', 62.3)]

15.8 Updating A Record


You can even update a record (tuple) in a table through python script. The following
example change the name “Priya” to “Priyanka” in a record in “student table”

293
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 293 23-12-2022 15:33:41


Example 15.8 -1

# code for update operation


import sqlite3
# database name to be passed as parameter
conn = [Link]("[Link]")
# update the student record
[Link]("UPDATE Student SET sname ='Priyanka' where Rollno='6'")
[Link]()
print ("Total number of rows updated :", conn.total_changes)
cursor = [Link]("SELECT * FROM Student")
for row in cursor:
print (row)
[Link]()
OUTPUT
Total number of rows updated : 1
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
(6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')

Note
Remember throughout this chapter student table what we have created is taken as example
to explain the SQL queries .Example 15.3.2 -2 contain the student table with records

XII Std Computer Science 294

12th Computer Science_EM Chapter [Link] 294 23-12-2022 15:33:41


15.9 Deletion Operation
Similar to Sql command to delete a record, Python also allows to delete a record. The
following example delete the content of Rollno 2 from "student table"

Example 15.9-1

# code for delete operation


import sqlite3
# database name to be passed as parameter
conn = [Link]("[Link]")
# delete student record from database
[Link]("DELETE from Student where Rollno='2'")
[Link]()
print("Total number of rows deleted :", conn.total_changes)
cursor =[Link]("SELECT * FROM Student")
for row in cursor:
print(row)
[Link]()

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

12th Computer Science_EM Chapter [Link] 295 23-12-2022 15:33:41


15.10 Data input by User

In this example we are going to accept data using Python input() command during
runtime and then going to write in the Table called "Person"

Example 15.10 -1

# code for executing query using input data


import sqlite3
# creates a database in RAM
con =[Link]("[Link]")
cur =[Link]()
[Link]("DROP Table person")
[Link]("create table person (name, age, id)")
print("Enter 5 students names:")
who =[input() for i in range(5)]
print("Enter their ages respectively:")
age =[int(input()) for i in range(5)]
print("Enter their ids respectively:")
p_id =[int(input())for i in range(5)]
n =len(who)
for i in range(n):
# This is the q-mark style:
[Link]("insert into person values (?, ?, ?)", (who[i], age[i], p_id[i]))
[Link]("select * from person")
# Fetches all entries from table
print("Displaying All the Records From Person Table")
print (*[Link](), sep='\n' )

XII Std Computer Science 296

12th Computer Science_EM Chapter [Link] 296 23-12-2022 15:33:41


OUTPUT
Enter 5 students names:
RAM
KEERTHANA
KRISHNA
HARISH
GIRISH
Enter their ages respectively:
28
12
21
18
16
Enter their ids respectively:
1
2
3
4
5
Displaying All the Records From Person Table
('RAM', 28, 1)
('KEERTHANA', 12, 2)
('KRISHNA', 21, 3)
('HARISH', 18, 4)
('GIRISH', 16, 5)

You can even add records to the already existing table like “Student” Using the above
coding with appropriate modification in the Field Name. To do so you should comment the
create table statement

Note
Execute (sql[, parameters]) :- Executes a single SQL statement. The SQL statement
may be parametrized (i. e. Use placeholders instead of SQL literals). The sqlite3 module
supports two kinds of placeholders: question marks? (“qmark style”) and named
placeholders :name (“named style”).

297
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 297 23-12-2022 15:33:41


15.11 Using Multiple Table for Querying

Python allows to query more than one table by joining them. In the following example
a new table called “Appointment” which contain the details of students Rollno, Duty, Age is
created. The tables “student” and “Appointment” are joined and displayed the result with the
column headings.
Example 15.11-1
import sqlite3
connection = [Link]("[Link]")
cursor = [Link]()
[Link]("""DROP TABLE Appointment;""")
sql_command = """
CREATE TABLE Appointment(rollnointprimarkey,Dutyvarchar(10),age int)"""
[Link](sql_command)
sql_command = """INSERT INTO Appointment (Rollno,Duty ,age )
VALUES ("1", "Prefect", "17");"""
[Link](sql_command)
sql_command = """INSERT INTO Appointment (Rollno, Duty, age)
VALUES ("2", "Secretary", "16");"""
[Link](sql_command)
# never forget this, if you want the changes to be saved:
[Link]()
[Link] ("SELECT [Link],[Link],
[Link], [Link] FROM student,Appointment
where [Link]=[Link]")
#print ([Link]) to display the field names of the table
co = [i[0] for i in [Link]]
print(co)
# Field informations can be read from [Link].
result = [Link]()
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.

XII Std Computer Science 298

12th Computer Science_EM Chapter [Link] 298 23-12-2022 15:33:41


15.12 Integrating Query With Csv File

You can even store the query result in a CSV file. This will be useful to display the query
output in a tabular format. In the following example (EXAMPLE 15.12 -1) Using Python
script the student table is sorted “gender” wise in descending order and then arranged the
records alphabetically. The output of this Query will be written in a CSV file called “[Link]”,
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/[Link]','w, newline= ' ')
c=[Link](d)
connection = [Link]("[Link]")
cursor = [Link]()

[Link]("SELECT * FROM student ORDER BY GENDER DESC,SNAME")


# WRITING THE COLUMN HEADING
co = [i[0] for i in [Link]]
[Link](co)
data=[Link]()
for item in data:
[Link](item)
[Link]()
# Reading the CSV File
with open('c:/pyprg/[Link]', "r") as fd:
for line in fd:
line = [Link]("\n", "")
print(line)
[Link]()
[Link]()
OUTPUT
Rollno,Sname,Grade,gender,Average,birth_date
1, Akshay, B, M, 87.8, 2001-12-12
2, Aravind, A, M, 92.5, 2000-08-17
3, BASKAR, C, M, 75.2, 1998-05-17
7, TARUN, D, M, 62.3, 1999-02-01
5, VARUN, B, M, 80.6, 2001-03-14
6, PRIYA, A, F, 98.6, 2002-01-01
4, SAJINI, A, F, 95.6, 2002-11-01

299
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 299 23-12-2022 15:33:41


Example 15.12 -2 Opening the file (“[Link]”) 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 = [Link]("[Link]")
print(“Content of the table before sorting and writing in CSV file”)
cursor = [Link]("SELECT * FROM Student")
for row in cursor:
print (row)
# CREATING CSV FILE
d=open('c:\pyprg\[Link]','w', newline= ' ')
c=[Link](d)
cursor = [Link]()
[Link]("SELECT * FROM student ORDER BY GENDER DESC,SNAME")
#WRITING THE COLUMN HEADING
co = [i[0] for i in [Link]]
[Link](co)
data=[Link]()
for item in data:
[Link](item)
[Link]()
print(”[Link] File is created open by visiting c:\pyprg\[Link]”)
[Link]()

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.

XII Std Computer Science 300

12th Computer Science_EM Chapter [Link] 300 23-12-2022 15:33:41


OUTPUT
Content of the table before sorting and writing in CSV file
(1, 'Akshay', 'B', 'M', 87.8, '2001-12-12')
(2, 'Aravind', 'A', 'M', 92.5, '2000-08-17')
(3, 'BASKAR', 'C', 'M', 75.2, '1998-05-17')
(4, 'SAJINI', 'A', 'F', 95.6, '2002-11-01')
(5, 'VARUN', 'B', 'M', 80.6, '2001-03-14')
(6, 'Priyanka', 'A', 'F', 98.6, '2002-01-01')
(7, 'TARUN', 'D', 'M', 62.3, '1999-02-01')
[Link] File is created open by visiting c:\pyprg\[Link]
OUTPUT THROUGH EXCEL
A B C D E F

1 Rollno Sname Grade gender Average birth_date

2 1 Akshay B M 87.8 12-12-2001

3 2 Aravind A M 92.5 17-08-2000

4 3 BASKAR C M 75.2 17-05-1998

5 7 TARUN D M 62.3 01-02-1999

6 5 VARUN B M 80.6 14-03-2001

7 6 PRIYA A F 98.6 01-01-2002

8 4 SAJINI A F 95.6 01-11-2002

15.3 Table List

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 = [Link]('[Link]')
cursor = [Link]()
[Link]("SELECT name FROM sqlite_master WHERE type='table';")
print([Link]())

OUTPUT
[('Student',), ('Appointment',), ('Person',)]

301
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 301 23-12-2022 15:33:42


The above program (Example 15.3-1) display the names of all tables created in ‘Academy.
db’ database. The master table holds the key information about your database tables and it
is called sqlite_master
So far, you have been using the Structured Query Language in Python scripts. This
chapter has covered many of the basic SQL commands. Almost all sql commands can be
executed by Python SQLite module. You can even try the other commands discussed in the
SQL chapter.

Points to remember:
• A database is an organized collection of data.
• Users of database can be human users, other programs or applications
• SQLite is a simple relational database system, which saves its data in regular data files.
• Cursor is a control structure used to traverse and fetch the records of the database. All
the SQL commands will be executed using cursor object only.
• As data in a table might contain single or double quotes, SQL commands in Python
are denoted as triple quoted string.
• “Select” is the most commonly used statement in SQL
• The SELECT Statement in SQL is used to retrieve or fetch data from a table in a database
• The GROUP BY clause groups records into summary rows
• The ORDER BY Clause can be used along with the SELECT statement to sort the data
of specific fields in an ordered way
• Having clause is used to filter data based on the group functions.
• Where clause cannot be used along with ‘Group by’
• The WHERE clause can be combined with AND, OR, and NOT operators
• The ‘AND’ and ‘OR’ operators are used to filter records based on more than one
condition
• Aggregate functions are used to do operations from the values of the column and a
single value is returned.
• COUNT() function returns the number of rows in a table.
• AVG() function retrieves the average of a selected column of rows in a table.
• SUM() function retrieves the sum of a selected column of rows in a table.
• MAX() function returns the largest value of the selected column.
• MIN() function returns the smallest value of the selected column
• sqlite_master is the master table which holds the key information about your database
tables.
• The path of a file can be either represented as ‘/’ or using ‘\’ in Python. For example the
path can be specified either as 'c:/pyprg/[Link]', or c:\pyprg\[Link]’.

XII Std Computer Science 302

12th Computer Science_EM Chapter [Link] 302 23-12-2022 15:33:42


Hands on Experience
1. Create an interactive program to accept the details from user and store it in a csv file using
Python for the following table.
Database name;- DB1
Table name : Customer

Cust_Id Cust_Name Address Phone_no City

C008 Sandeep 14/1 Pritam Pura 41206819 Delhi

C010 Anurag Basu 15A, Park Road 61281921 Kolkata

C012 Hrithik 7/2 Vasant Nagar 26121949 Delhi

2. Consider the following table GAMES. Write a python program to display the records for
question (i) to (v)
Table: GAMES

Gcode Name GameName Number PrizeMoney ScheduleDate

101 Padmaja Carom Board 2 5000 01-23-2014

102 Vidhya Badminton 2 12000 12-12-2013

103 Guru Table Tennis 4 8000 02-14-2014

105 Keerthana Carom Board 2 9000 01-01-2014

108 Krishna Table Tennis 4 25000 03-19-2014

(i) To display the name of all Games with their Gcodes in descending order of their schedule
date.
(ii) To display details of those games which are having Prize Money more than 7000.
(iii) To display the name and gamename of the Players in the ascending order of Gamename.
(iv) To display sum of PrizeMoney for each of the Numberof participation groupings (as
shown in column Number 4)
(v) Display all the records based on GameName

303
Data Manipulation Through SQL

12th Computer Science_EM Chapter [Link] 303 23-12-2022 15:33:42


Evaluation

Part - I

Choose the best answer (1 Mark)


1. Which of the following is an organized collection of data?
(A) Database (B) DBMS (C) Information (D) Records
2. SQLite falls under which database system?
(A) Flat file database system (B) Relational Database system
(C) Hierarchical database system (D) Object oriented Database system
3. Which of the following is a control structure used to traverse and fetch the records of the
database?
(A) Pointer (B) Key
(C) Cursor (D) Insertion point
4. Any changes made in the values of the record should be saved by the command
(A) Save (B) Save As (C) Commit (D) Oblige
5. Which of the following executes the SQL command to perform some action?
(A) execute() (B) key() (C) cursor() (D) run()
6. Which of the following function retrieves the average of a selected column of rows in a
table?
(A) Add() (B) SUM() (C) AVG() (D) AVERAGE()
7. The function that returns the largest value of the selected column is
(A) MAX() (B) LARGE()
(C) HIGH() (D) MAXIMUM()
8. Which of the following is called the master table?
(A) sqlite_master (B) sql_master
(C) main_master (D) master_main
9. The most commonly used statement in SQL is
(A) cursor (B) select (C) execute (D) commit
10. Which of the following keyword avoid the duplicate?
(A) Distinct (B) Remove (C) Where (D) GroupBy

XII Std Computer Science 304

12th Computer Science_EM Chapter [Link] 304 23-12-2022 15:33:42


Part - II
Answer the following questions (2 Marks)
1. Mention the users who uses the Database.
2. Which method is used to connect a database? Give an example.
3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”
4. Write the command to populate record in a table. Give an example.
5. Which method is used to fetch all rows from the database table?

Part - III
Answer the following questions (3 Marks)
1. What is SQLite?What is it advantage?
2. Mention the difference between fetchone() and fetchmany()
3. What is the use of Where [Link] a python statement Using the where clause.
4. Read the following [Link] on that write a python script to display department wise
records
database name :- [Link]
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
5. Read the following [Link] on that write a python script to display records in
desending order of
Eno
database name :- [Link]
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

12th Computer Science_EM Chapter [Link] 305 23-12-2022 15:33:42


3. hat is the use of HAVING clause. Give an example python script
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-

Icode :- integer and act as primary key

Item Name :- Character with length 25

Rate :- Integer

Record to be added :- 1008, Monitor,15000

5. Consider the following table Supplier and item .Write a python script for (i) to (ii)

SUPPLIER

Suppno Name City Icode SuppQty

S001 Prasad Delhi 1008 100

S002 Anu Bangalore 1010 200

S003 Shahid Bangalore 1008 175

S004 Akila Hydrabad 1005 195

S005 Girish Hydrabad 1003 25

S006 Shylaja Chennai 1008 180

S007 Lavanya Mumbai 1005 325

i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40

References
1. The Definitive Guide to SQLite by Michael Owens
2. Programming for Beginners: 2 Manuscripts: SQL & Python by Byron Francis
3. [Link]

XII Std Computer Science 306

12th Computer Science_EM Chapter [Link] 306 23-12-2022 15:33:42


CHAPTER 16
Unit V DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART

Learning Objectives

After learning this chapter, the learners will be able to


• Define the term Data Visualization.
• List the types of Data Visualization.
• List the uses of Data Visualization.
• List the types of Visualizations in Matplotlib.
• Explore importing Matplotlib.
• Classify the types of Data Visualization plots.
• Practice creating various types of plots using Matplotlib.

16.1 Data Visualization Definition

Data Visualization is the graphical representation of information and data. The


objective of Data Visualization is to communicate information visually to users. For this, data
visualization uses statistical graphics. Numerical data may be encoded using dots, lines, or
bars, to visually communicate a quantitative message.
General types of Data Visualization
• Charts
• Tables
• Graphs
• Maps
• Infographics
• Dashboards
Data visualization - Uses
• Data Visualization help users to analyze and interpret the data easily.

307
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 307 23-12-2022 11:35:36


• It makes complex data understandable and usable.
• Various Charts in Data Visualization helps to show relationship in the data for one or more
variables.

Infographics → An infographic (information graphic) is the representation of


information in a graphic format.
Dashboard → A dashboard is a collection of resources assembled to create a single unified
visual display. Data visualizations and dashboards translate complex ideas and concepts
into a simple visual format. Patterns and relationships that are undetectable in text are
detectable at a glance using dashboard.

Introduction to Matplotlib — Data Visualization in Python


Matplotlib is the most popular data visualization library in Python. It allows you to
create two dimension (2D) charts in few lines of code.
Types of Visualizations in Matplotlib
There are many types of Visualizations under Matplotlib. Some of them are:
• Line plot
• Scatter plot
• Histogram
• Box plot
• Bar chart and
• Pie chart

Scatter plot: A scatter plot is a type of plot that shows the data as a collection of
points. The position of a point depends on its two-dimensional value, where each
value is a position on either the horizontal or vertical dimension.
Box plot: The box plot is a standardized way of displaying the distribution of data based
on the five number summary: minimum, first quartile, median, third quartile, and
maximum.

Installing Matplotlib
You can install matplotlib using pip. Pip is a Package manager software for installing
python packages.

308
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 308 23-12-2022 11:35:36


Note
Detailed installation procedures given in Annexure - II

16.2 Getting Started

After installing Matplotlib, we will begin coding by importing Matplotlib using the
command:
import [Link] 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 [Link]() function inside the
file to display your plot.
Example
import [Link] as plt
[Link]([1,2,3,4])
[Link]()
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

12th Computer Science_EM Chapter [Link] 309 23-12-2022 11:35:36


You may be wondering why the x-axis ranges from 0-3 and the y-axis from 1-4. If you
provide a single list or array to the plot () command, matplotlib assumes it is a sequence of y
values, and automatically generates the x values for you. Since python ranges start with 0, the
default x vector has the same length as y but starts with 0. Hence the x data are [0, 1, 2, 3].
plot() is a versatile command, and will take an arbitrary number of arguments.
Program

For example, to plot x and y, you can issue the command:


import [Link] as plt
[Link]([1,2,3,4], [1,4,9,16])
[Link]()

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

1.0 1.5 2.0 2.5 3.0 3.5 4.0

Figure 16.2

310
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 310 23-12-2022 11:35:36


Plotting Two Lines
To plot two lines, use the following code:
import [Link] as plt
x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
[Link](x, y, label='Line 1')
[Link](x2, y2, label='Line 2')
[Link]('X-Axis')
[Link]('Y-Axis')
[Link]('LINE GRAPH')
[Link]()
[Link]()
Output
With [Link] and [Link], you can assign labels to those respective axis. Next, you
can assign the plot's title with [Link], and then you can invoke the default legend with plt.
legend().

LINE GRAPH
14 Line1
Line2

12

10
Y - Axis

4
1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00
X - Axis

Figure 16.3
311
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 311 23-12-2022 11:35:36


Buttons in the output
In the output figure, you can see few buttons at the bottom left corner. Let us see the use
of these buttons.

Configure
Subplots
Home Button Pan Axis Button Button

Forward / Back Buttons Zoom Save the


Button Figure Button

Figure 16.4
Home Button → The Home Button will help once you have begun navigating your chart. If
you ever want to return back to the original view, you can click on this.

Forward/Back buttons → These buttons can be used like the Forward and Back buttons in
your browser. You can click these to move back to the previous point you were at, or forward
again.
Pan Axis → This cross-looking button allows you to click it, and then click and drag your
graph around.
Zoom → The Zoom button lets you click on it, then click and drag a square that you would like
to zoom into specifically. Zooming in will require a left click and drag. You can alternatively
zoom out with a right click and drag.
Configure Subplots → This button allows you to configure various spacing options with your
figure and plot.
Save Figure → This button will allow you to save your figure in various forms.

16.3 Special Plot Types

Matplotlib allows you to create different kinds of plots ranging from histograms and
scatter plots to bar graphs and bar charts.
Line Chart
A Line Chart or Line Graph is a type of chart which displays information as a series of
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

12th Computer Science_EM Chapter [Link] 312 23-12-2022 11:35:37


Example: Line plot
import [Link] as plt
years = [2014, 2015, 2016, 2017, 2018]
total_populations = [8939007, 8954518, 8960387, 8956741, 8943721]
[Link] (years, total_populations)
[Link] ("Year vs Population in India")
[Link] ("Year")
[Link] ("Total Population")
[Link]()
In this program,
[Link]() → specifies title to the graph
[Link]() → specifies label for X-axis
[Link]() → specifies label for Y-axis
Output

Year vs Population in India


8960000

8955000
Total Population

8950000

8945000

8940000

2014.4 2014.5 2015.0 2015.5 2016.0 2016.6 2017.0 2017.7 2018.0


Year

Figure 16.5
Bar Chart
A BarPlot (or BarChart) is one of the most common type of plot. It shows the
relationship between a numerical 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 [Link]() function.
313
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 313 23-12-2022 11:35:37


Example
import [Link] 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
[Link] (y_positions, usage)
[Link] (y_positions, labels)
[Link] ("RANGE")
[Link] ("MARKS")
[Link]()
Output

MARKS

80

60
RANGE

40

20

0
TAMIL ENGLISH MATHS PHYSICS CHEMISTRY CS

Figure 16.6

The above code represents the following:


Labels → Specifies labels for the bars.
Usgae → Assign values to the labels specified.
Xticks → Display the tick marks along the x-axis at the values represented. Then specify
the label for each tick mark.
Range → Create sequence of numbers.
314
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 314 23-12-2022 11:35:37


Bar Graph and Histogram are the two ways to display data in the form of a diagram.

Key Differences Between Histogram and Bar Graph


The differences between Histogram and bar graph are as follows
1. Histogram refers to a graphical representation; that displays data by way of bars to
show the frequency of numerical data. A bar graph is a pictorial representation of data
that uses bars to compare different categories of data.
2. A histogram represents the frequency distribution of continuous variables. Conversely,
a bar graph is a diagrammatic comparison of discrete variables.
3. Histogram presents numerical data whereas bar graph shows categorical data.
4. The histogram is drawn in such a way that there is no gap between the bars. On the ot her
hand, there is proper spacing between bars in a bar graph that indicates discontinuity.
5. Items of the histogram are numbers, which are categorised together, to represent ranges
of data. As opposed to the bar graph, items are considered as individual entities.
6. In the case of a bar graph, it is quite common to rearrange the blocks, from highest to
lowest. But with histogram, this cannot be done, as they are shown in the sequence of
classes.
7. The width of rectangular blocks in a histogram may or may not be same while the
width of the bars in a bar graph is always same.
Pie Chart
Pie Chart is probably one of the most common type of chart. It is a circular graphic
which is divided into slices to illustrate numerical proportion. The point of a pie chart is
to show the relationship of parts out of a whole.
To make a Pie Chart with Matplotlib, we can use the [Link]() function. The autopct
parameter allows us to display the percentage value using the Python string formatting.

Example
import [Link] as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
[Link] (sizes, labels = labels, autopct = "%.2f ")
[Link]()

315
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 315 23-12-2022 11:35:37


Output

English

Tamil
18.43
20.51

Maths 20.74

17.28

23.04 Social

Science

Figure 16.7

Hands on Practice

1. Plot a line chart for the given data and set the title for x and y axis.
Average Pulse: 80, 85, 90, 95, 100
Calorie Burnage: 240, 250, 260, 270, 280

2. Plot a pie chart for your marks in the recent examination.

3. Plot a line chart on the academic performance of Class 12 students in Computer


Science for the past 10 years.

4. Plot a bar chart for the number of computer science periods in a week.

316
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 316 23-12-2022 11:35:37


Evaluation

Part - I

Choose the best answer (1 Mark)


1. Which is a python package used for 2D charts?
a. [Link] b. [Link]
c. [Link] d. [Link]
2. Identify the package manager for installing Python packages, or modules.
a. Matplotlib b. PIP
c. [Link]() d. python package
3. Which of the following feature is used to represent data and information graphically?
a. Data List b. Data Tuple
c. Classes and Objects d. Data Visualization
4. .......... is a collection of resources assembled to create a single unified visual display.
a. Interface b. Dashboard
c. Objects d. Graphics
5. Which of the following module should be imported to visualize data and information
in Python?
a. csv b. getopt
c. mysql d. matplotlib
6. ............ is a type of chart which displays information as a series of data points connected
by straight line segments.
a. csv b. Pie chart
c. Bar chart d. All the above
7. Read the code:
import [Link] as plt
[Link](3,2)
[Link]()
Identify the output for the above coding.

317
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 317 23-12-2022 11:35:37


a. Epic Info b.
16 1 info
16
14 14
12
12
Y axis

y axis
10
8
10
2 6
4
8
2
2 3 4 5 6 7
6
8 11
3 x axis
5 6 7 9 10
X axis

c.
d.
2.100
4.0
2.075
3.5
2.050

some numbers
2.025 3.0

2.000 2.5

1.975 2.0
1.950
1.5
1.925
1.0
1.900
0.0 0.0 0.5 1.5 2.0 2.5 3.0
2.85 2.90 2.95 3.00 3.05 3.10 3.15

8. Identify the right type of chart using the following hints.


Hint 1: This chart is often used to visualize a trend in data over intervals of time.
Hint 2: The line in this type of chart is often drawn chronologically.
a. Line chart b. Bar chart
c. Pie chart d. Scatter plot
9. Read the statements given below. Identify the right option from the following for pie
chart.
Statement A: To make a pie chart with Matplotlib, we can use the [Link]() function.
Statement B: The autopct parameter allows us to display the percentage value using
the Python string formatting.
a. Statement A is correct b. Statement B is correct
c. Both the statements are correct d. Both the statements are wrong

318
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 318 23-12-2022 11:35:37


Part - II

Answer the following questions (2 Marks)


1. What is Data Visualization?
2. List the general types of data visualization.
3. List the types of Visualizations in Matplotlib.
4. How will you install Matplotlib?
5. Write the difference between the following functions: [Link]([1,2,3,4]), plt.
plot([1,2,3,4], [1,4,9,16]).

Part - III

Answer the following questions (3 Marks)


1. Draw the output for the following data visualization plot.
import [Link] as plt
[Link]([1,3,5,7,9],[5,2,7,8,2], label="Example one")
[Link]([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
[Link]()
[Link]('bar number')
[Link]('bar height')
[Link]('Epic Graph\nAnother Line! Whoa')
[Link]()
2. Write any three uses of data visualization.
3. Write the plot for the following pie chart output.

319
Data Visualization using Pyplot

12th Computer Science_EM Chapter [Link] 319 23-12-2022 11:35:37


Part - IV

Answer the following questions (5 Marks)


1. Explain in detail the types of pyplots using Matplotlib.
2. Explain the various buttons in a matplotlib window.
3. Explain the purpose of the following functions:
a. [Link]
b. [Link]
c. [Link]
d. [Link]()
e. [Link]()

Reference
1. [Link] [Link] / data - science - with - python - intro -to- data
-visualization-and-matplotlib-5f799b7c6d82.
2. [Link]
d9143287ae39.
3. [Link] [Link] / legends - titles - labels - matplotlib - tutorial/?
completed=/matplotlib-intro-tutorial/.
4. [Link]

320
XII Std Computer Science

12th Computer Science_EM Chapter [Link] 320 23-12-2022 11:35:37

You might also like