Introduction To Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Introduction to Python Programming

Lecture Notes

Mithun A. V.
Contents

I Python Basics

1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.1 Introduction 9
1.2 Features of Python 9
1.3 Installing Python 10
1.4 Different Methods to Run Python Programs 10
1.5 Objects and Numerical Types 11
1.6 Variables 11
1.7 Comments in Python 11
1.8 Strings 12
1.8.1 Accessing Characters Inside a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.2 Built-in String Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.8.3 String Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.8.4 Formatted Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.9 Operators in Python 13
1.9.1 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.9.2 Relational or Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.9.3 Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.9.4 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.9.5 Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.9.6 Membership Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9.7 Identity Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10 Input and Output in Python 16
1.10.1 Getting Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.10.2 Output using print() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.11 Indentation In Python 17

2 Control Statements and Python Data Structures . . . . . . . . . . . . . . . . . 19


2.1 Conditional (Branching) Statements 19
2.1.1 if ... else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1.2 Nested if...else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.1.3 elif Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2 Iteration (Looping) Statements 21
2.2.1 while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2.2 for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.2.3 range() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.3 Lists 22
2.3.1 List Functions and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.4 Tuples 26
2.4.1 Functions that can be applied to tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.5 Sets 27
2.5.1 Methods of Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.5.2 Functions that can be applied to sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.6 Dictionaries 29
2.6.1 Functions that can be applied to dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.6.2 Methods of Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.6.3 Iterating over dictionary items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.7 The enumerate() Function 31
2.8 Mutable and Immutable Objects 31

3 Functions, Modules, Files, Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 33


3.1 Functions 33
3.1.1 Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.1.2 Function Calling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.1.3 Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.1.4 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2 Modules 36
3.2.1 Importing Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.2.2 The math Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.2.3 The statistics Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.2.4 Creating Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3 Files 38
3.3.1 Opening a file using open() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.3.2 Closing a file using close() method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.3.3 Writing to a file using the write() method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.3.4 Reading a file using read() method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.4 Exceptions 41
3.4.1 Built-in Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.4.2 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

4 Numpy Arrays and Data Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . 45


4.1 Introduction 45
4.2 array Class 45
4.2.1 Accessing elements of an array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
4.2.2 Adding elements to an array using insert() and append() methods . . . . . . . . . 46
4.3 NumPy Module 47
4.3.1 Creating Arrays using NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.3.2 zeros(), ones() and empty() Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.3.3 arange() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.3.4 linspace() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3.5 random() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.3.6 Indexing, Slicing and Iterating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.3.7 Copying Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.3.8 Splitting Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.3.9 Shape Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.3.10 Transposing an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.3.11 Resizing an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.3.12 Arithmetic Operations on Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.4 Matplotlib 56
4.5 Pyplot 56
4.5.1 plot() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.5.2 Formatting Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
4.5.3 Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.5.4 Histograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.5.5 Scatter Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.5.6 Figure and Subplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
4.5.7 Plotting sinx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.5.8 Plotting x2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
URLs 67
Books 67
I
Python Basics

1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . 9
1.1 Introduction
1.2 Features of Python
1.3 Installing Python
1.4 Different Methods to Run Python Programs
1.5 Objects and Numerical Types
1.6 Variables
1.7 Comments in Python
1.8 Strings
1.9 Operators in Python
1.10 Input and Output in Python
1.11 Indentation In Python

2 Control Statements and Python Data Struc-


tures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.1 Conditional (Branching) Statements
2.2 Iteration (Looping) Statements
2.3 Lists
2.4 Tuples
2.5 Sets
2.6 Dictionaries
2.7 The enumerate() Function
2.8 Mutable and Immutable Objects

3 Functions, Modules, Files, Exceptions . 33


3.1 Functions
3.2 Modules
3.3 Files
3.4 Exceptions

4 Numpy Arrays and Data Visualization . 45


4.1 Introduction
4.2 array Class
4.3 NumPy Module
4.4 Matplotlib
4.5 Pyplot

Bibliography . . . . . . . . . . . . . . . . . . . . . . . . 67
URLs
Books
1. Getting Started

1.1 Introduction

Many tasks that we do in computers can be automated by writing some programs. For individuals
from disciplines other than computer science, learning a programming language like C is not so
easy. Python is a language that is relatively simple and easy to learn. Python was developed by
the Dutch programmer Guido van Rossum in 1991. Python was named after a British TV Comedy
Show “Monty Python’s Flying Circus”. Sample programs in python contains references to this
show.

1.2 Features of Python


• High-level programming language.
• General purpose programming Language which can be used for developing any kind of
applications.
• A language that is relatively simple and easy to learn. Programs written in python are shorter
than the same programs written in other languages like C, Java.
• Python is an interpreted programming language. Unlike C, which is a compiled language,
python statements are executed directly without being first converted to an object code. This
speeds up development since no compilation and linking is required.
• Python is an Object Oriented Programming Language.
• Python has support for GUI Programming.
• Python has a large standard library with lots of functions and modules.
• Python is a dynamically typed language. Hence data types of the variables need not be
specified explicitly. Type of variables will be automatically assigned depending on the value
contained in the variable.
• Programs written in python are portable.
• Python is free to download and use.
10 Chapter 1. Getting Started

1.3 Installing Python


• Comes pre-installed in Ubuntu.
• For information about how to install in python in other operating systems see the video
https://www.youtube.com/watch?v=YYXdXT2l-Gg.

Versions of Python
There are 2 series of python versions available now. Python 2 series and Python 3 series.

Figure 1.1: Versions of Python (as on Feb 2021)

1.4 Different Methods to Run Python Programs


Using Interactive Interpreter
• Easiest way to get started with python programming.
• Interactive interpreter can be invoked by running the command python3 from the shell.
• It will first display the version information of python.
• Primary prompt is >>> where the python statements can be typed in.
• A secondary prompt of three dots (...) will be displayed for continuation of commands in
multiple lines.
1 >>> print ( " Hello World " )
2 Hello World
3 >>>
Listing 1.1: Running python in interactive interpreter

Using Scripts
• Python code (script) can be written using a text editor and saved as a file with extension .py.
• Script can be executed at shell by invoking the interpreter.
1 $ python3 hello . py
2 Hello World
Listing 1.2: Running python script

Using an IDE
• IDE stands for Integrated Development Environment.
• It is an editor with GUI (Graphical User Interface) for writing, executing and debugging the
code and many other features that facilitates programming.
• Some examples for python IDE are IDLE, Atom, Sublime etc..
1.5 Objects and Numerical Types 11

Using Jupyter Notebook


Jupyter notebook is free web based application that can be used to create and share live codes along
with its documentation.

Figure 1.2: Using Jupyter Notebook

1.5 Objects and Numerical Types


Python programs operates on different kinds of objects. Each object has a type, which specifies the
operations that can be performed on that object. Types can be scalar or non-scalar.
• Scalar:
Scalar types are indivisible. Python has four scalar types.
1. int: Used to specify integers. e.g. -25, 35.
2. float: Used to specify real numbers. They have a decimal point. e.g. 3.14, 5.78.
3. bool: used to represent boolean values True and False.
4. None: Specifies null or no value.
• Non-Scalar:
Types which can be divided. e.g. strings.

1.6 Variables
• Variables are names given for memory locations, where python objects are stored.
• Rules for variable naming in python are
– Variable names cane contain letters(uppercase or lowercase), digits and underscore(_).
– Variable name cannot begin with a digit
– Variables names are case sensitive
– Reserved words in python cannot be used as variable names.
1 a = 10
2 b = 3.50
Listing 1.3: Assigning values to variables

Objects and operators can be combined to form expressions. For example, a+b is an expression.

1.7 Comments in Python


Comments are used for documenting the code. It helps programmers to better understand the code.
In python, single line comments can be written by writing the commment after the # symbol.
12 Chapter 1. Getting Started

1 r = 10
2 # Find the area of the circle with radius r
3 a = 3.14* r * r
Listing 1.4: Example for single line comment

Multiline comments can be written by writing the comment between a pair of three double/single
quotes
1 r = 10
2 """ Find the area of the circle with radius r
3 where 3.14 is the value for pi """
4 a = 3.14* r * r
5 ''' Find the perimeter of the circle with radius r
6 where 3.14 is the value for pi '''
7 p = 2*3.14* r
Listing 1.5: Example for multine line comment

1.8 Strings
Textual data is called a string. String is a sequence of characters. In python, a string is placed
between a pair of single or double quotes. If the string contains a single quote, then the string
can be put inside a pair of double quotes and vice versa. Each character in a string has an index
associated with it. The index of the first character in a string is 0.

1.8.1 Accessing Characters Inside a String


• Individual characters of a string can be accessed by specifying the index within a square
bracket. If the index specified does not exist, then an index error will occur.
1 t = " Have a nice day "
2 print ( t [1]) # Prints a
3 print ( t [10]) # Prints e
4 print ( t [30]) # Index error
Listing 1.6: Accessing individual characters in a string

• A range of characters can be accessed using : operator. For example a:b will return characters
from index a to index b-1. If no index is specified before :, then it will be assumed as 0,
meaning from the beginning. Similarly, if no index is specified after :, then it will be assumed
as the last index of the string, meaning till the end. This is called slicing of strings.
1 t = " Have a nice day "
2 print ( t [0:4]) # Prints Have
3 print ( t [:4]) # Prints Have
4 print ( t [5:]) # Prints a nice day
Listing 1.7: Accessing a range of characters in a string

1.8.2 Built-in String Functions and Methods


Functions and methods can be considered as same things, except that methods are applied on
objects of a type using a dot operator. Some of the string functions and methods that can be applied
to a string s are given below.
• len(s): This function returns the length of a string, which means the number of characters in
the string.
• s.lower(): This method returns another string t, which is a copy of s but with all the letters
converted to lower case.
1.9 Operators in Python 13

• s.upper(): This method returns another string t, which is a copy of s but with all the letters
converted to upper case.
• s.count(t,beg,end): This method counts the number of occurrences of a string t within the
string s in the index range beg and end. Arguments beg and end are optional, and they are 0
and length of the string by default.
• s.find(t,beg,end): This method returns the index of a string t within a string s in the index
range beg and end. Arguments beg and end are optional, and they are 0 and length of the string
by default. If the argument string does not exist in s, then it will return -1.
• s.replace(t,u): This method returns a string in which all the occurrences of string t in s are
replaced with the string u.
1 s = " Have a nice day "
2 print ( len ( s ) ) # Prints 16
3 print ( s . lower () ) # Prints have a nice day
4 print ( s . upper () ) # Prints HAVE A NICE DAY
5 print ( s . count ( 'a ') ) # Prints 3
6 print ( s . count ( 'a ' ,0 ,6) ) # Prints 2
7 print ( s . find ( 'a ') ) # Prints 1
8 print ( s . find ( 'a ' ,4 ,6) ) # Prints 5
9 print ( s . replace ( ' nice ' , ' good ') ) # Prints Have a good day
Listing 1.8: String Functions and Methods

1.8.3 String Operators


• + operator can be used to concatenate two strings.
• * operator can be used to concatenate a string to itself a required number of times.
1 a = " Have a "
2 b = " nice day "
3 print ( a + " " + b ) # Prints Have a nice day
4 print ( b *2) # Prints nice daynice day
Listing 1.9: String Operators

1.8.4 Formatted Strings


{} can be used as place holders for variables while printing a string.
1 a = " Sun "
2 b = " rise "
3 n = " east "
4 print ( ' {} {} in the {} '. format (a ,b , n ) ) # Prints Sun rise in the east
Listing 1.10: Formatted String

1.9 Operators in Python


1.9.1 Arithmetic Operators
Operator Meaning Description
+ Addition Values on both the sides of the operator are added
- Subtraction Value on the RHS is subtracted from the value on the LHS
* Multiplication Values on both the sides of the operator are multiplied
/ Division Values on the LHS is divided by the value on the RHS
// Floor Division Finds the quotient when LHS is divided by RHS
% Modulus Finds the remainder when LHS is divided by RHS
** Exponentiation Finds LHS raised to the power RHS
14 Chapter 1. Getting Started

1 a = 5
2 c = 2
3
4 print ( a + c) # Prints 7
5 print ( a - c) # Prints 3
6 print ( a * c) # Prints 10
7 print ( a / c) # Prints 2.5
8 print ( a % c) # Prints 1
9 print ( a ** c ) # Prints 25
10 print ( a // c ) # Prints 2
Listing 1.11: Arithmetic Operators

1.9.2 Relational or Comparison Operators


Relational operators compare the values of the operands and returns a boolean value (TRUE or FALSE).
Operator Meaning Description
Returns TRUE, if values on both sides of the operator are
== Equal
equal. Otherwise returns FALSE.
Returns TRUE, if values on both sides of the operator are
!= Not Equal
not equal. Otherwise returns FALSE.
Returns TRUE, if values on LHS is less than the value on
< Less than
the RHS. Otherwise returns FALSE.
Returns TRUE, if values on LHS is less than or equal to the
<= Less than or equal
value on the RHS. Otherwise returns FALSE.
Returns TRUE, if values on LHS is greater than the value on
> Greater than
the RHS. Otherwise returns FALSE.
Returns TRUE, if values on LHS is greater than or equal to
>= Greater than or equal
the value on the RHS. Otherwise returns FALSE.

1 a = 5
2 c = 2
3
4 print ( a == c ) # Prints False
5 print ( a != c ) # Prints True
6 print ( a < c) # Prints False
7 print ( a <= c ) # Prints False
8 print ( a > c) # Prints True
9 print ( a >= c ) # Prints True
Listing 1.12: Relational Operators

1.9.3 Assignment Operators


Assignment operators assigns value of the expression on the RHS to the variable on the LHS.
Operator Example Description
= a=b+10 Assign the value of b+10 to a.
+= a+=10 a = a + 10
-= a-=10 a = a - 10
*= a*=10 a = a * 10
/= a/=10 a = a / 10
%= a%=10 a = a % 10
//= a//=10 a = a // 10
**= a**=2 a = a ** 2
1.9 Operators in Python 15

1 a =5
2 a += 5
3 print ( a ) # Prints 10
4 a *= 2
5 print ( a ) # Prints 20
6 a **= 2
7 print ( a ) # Prints 400
Listing 1.13: Assignment Operators

1.9.4 Logical Operators


Logical operators are used to combine two or more relational operations. A logical operation will
always return a boolean value TRUE or FALSE.
Operator Description
Returns TRUE if the relational operations on both sides of
and
and are TRUE. Otherwise returns FALSE.
Returns TRUE if one of the relational operations on both
or
sides of or is TRUE. Otherwise returns FALSE.
not is a unary operator. Returns TRUE if the relational
not
operation after not is FALSE. Otherwise returns FALSE.

1 a = 5
2 b = 5.89
3 c = 2
4 print (a > b and a > c ) # Prints False
5 print (a > b or a > c ) # Prints True
6 print ( not (a > b ) ) # Prints True
Listing 1.14: Logical Operators

1.9.5 Bitwise Operators


Bitwise operators operate on the binary representations of the operands. Binary 1 is treates as TRUE
and binary 0 is treated as FALSE.
Operator Meaning Description
AND operation is performed on corresponding bit posi-
& Bitwise AND
tions in both operands.
OR operation is performed on corresponding bit positions
| Bitwise OR
in both operands.
XOR operation is performed on corresponding bit posi-
^ Bitwise XOR
tions in both operands.
~ One’s Complement Returns operand with all the bits inverted.
Shifts the bits in the operand to left by the specified num-
<< Left Shift
ber.
Shifts the bits in the operand to right by the specified
>> Right Shift
number.

1 a =15 # 00001111
2 b =2 # 00000010
3
4 print ( a & b ) # 00000010. Prints 2
5 print ( a | b ) # 00001111. Prints 15
16 Chapter 1. Getting Started

6 print ( a ^ b ) # 00001101. Prints 13


7 print (~ a ) # 11110000. Prints -16
8 print (a > > b ) # 00000011. Prints 3
9 print (a < < b ) # 00111100. Prints 60
Listing 1.15: Bitwise Operators

1.9.6 Membership Operators


Membership operators check whether a value exists in a sequence (string, list, tuples etc.) or not.
Operator Description
in Returns TRUE if a value exists in a sequence. Otherwise returns FALSE.
not in Returns TRUE if a value does not exist in a sequence. Otherwise returns FALSE.

1 a = " hello world "


2 print ( 'a ' in a ) # Prints False
3 print ( 'l ' in a ) # Prints True
Listing 1.16: Membership Operators

1.9.7 Identity Operators


Identity operators are used to check whether a value is a particular data type.
Operator Description
is Returns TRUE if type of the value on the LHS is the type specified on the RHS.
is not Returns TRUE if type of the value on the LHS is not the type specified on the RHS.

1 a = ' Hello world '


2 print ( type ( a ) is str ) # Prints True
3 print ( type ( a ) is int ) # Prints False
Listing 1.17: Identity Operators

1.10 Input and Output in Python


1.10.1 Getting Input
Input from user can be accepted using 2 functions.
input() Function
input() function is used to get input from the user. It takes an optional prompt message as argument.
The program execution will be suspended until the user enters an input value. The value entered by
the user will be treated as string. Hence, it needs to be converted to required type before performing
operations on it.
1 a = int ( input ( " Enter a number : " ) ) # e . g . 10
2 b = int ( input ( " Enter another number : " ) ) # e . g . 20
3 s = a + b
4 print ( ' Sum of {} and {} is {} '. format (a ,b , s ) )
5 # Prints Sum of 10 and 20 is 30
Listing 1.18: Identity Operators

raw_input() Function
raw_input() is same as input() function. It is used in Python 2.x versions. It is renamed as input()
in Python 3.x.
1.11 Indentation In Python 17

1.10.2 Output using print() Function


print function is used to display output on the screen or on a file. The syntax is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
• objects can be comma separated list of any objects which will be converted to string before
printing.
• sep is an optional argument. It specifies the string used to separate the objects. By default, it
is space.
• end is an optional argument. It specifies what to print at the end. By default, it is new line
(\n).
• file is an optional argument. It must be an object with a write(string) method; if it is not
present or None, sys.stdout will be used.
• flush is an optional argument. It is used to specify whether the stream is to be flushed or not.
1 print ( " hi " ," hello " )
2 # Prints hi hello
3 print ( " kerala " ," karnataka " , " tamilnadu " , sep = ' , ')
4 # Prints kerala , karnataka , tamilnadu
Listing 1.19: print() function

1.11 Indentation In Python


While writing programs it may be necessary to group two or more statements. For example, when
using branching statements like if, a particular block of statements are to be executed when the
condition is TRUE and another block of statements if the condition is FALSE. Languages like C uses
curly brackets for grouping statements. In python, a block or group of statements is created by
writing the statements with same indentation. A block ends when a line with different indentation
comes.
1 a = int ( input ( " Enter a number " ) )
2 if a % 2 == 0:
3 print ( " The number is even " )
4 print ( a *2)
5 else :
6 print ( " The number is odd " )
7 print ( a *3)
Listing 1.20: Indentation in Python

In this example, line numbers 3 and 4 are having same indentation. Hence they form a group of
statements which are executed when the condition in line number 2 is TRUE. Similarly line numbers
6 and 7 are having same indentation. Hence they form a group of statements which are executed
when the condition in line number 2 is FALSE.
2. Control Statements and Python Data Structures

2.1 Conditional (Branching) Statements


Conditional statements are used to control the flow of statements in a program. A conditional
statement has 3 parts.
1. A condition, which is a relational expression that evaluates to TRUE or FALSE.
2. A block of statements that has to be executed if the condition evaluates to TRUE.
3. An optional block of statements that has to be executed if the condition evaluates to FALSE.
Figure 2.1 shows the flowchart for a conditional statement.

Code

True Block Condition False Block

Code

Figure 2.1: Flowchart for Conditional Statement

2.1.1 if ... else Statement


Conditional statements in python are written using if and else statements.
1 statement x
2 if condition :
3 true block statements
4 else :
5 false block statements
20 Chapter 2. Control Statements and Python Data Structures

6 statement y
Listing 2.1: Syntax for if...else
If the condition evaluates to TRUE, then the true block statements are executed followed by
statement y. If the condition evaluates to FALSE, false block statements are executed followed by
statement y. All the statements in the true block or false block should have the same indentation.
1 a = int ( input ( " Enter a number " ) )
2 if a % 2 == 0:
3 print ( " The number is even " )
4 print ( a *2)
5 else :
6 print ( " The number is odd " )
7 print ( a *3)
8 # The following line will be printed in both cases
9 print ( " Thank you for using the program " )
Listing 2.2: Example for if...else

2.1.2 Nested if...else Statement


An if ... else statement can be placed inside another if ... else statement. This is called nested
if ... else.
1 n = int ( input ( " Enter a number : " ) )
2 if ( n %2 == 0) :
3 if ( n %3 == 0) :
4 print ( " {} is divisble by 2 and 3 " . format ( n ) )
5 else :
6 print ( " {} is divisble by 2 " . format ( n ) )
7 else :
8 if ( n %3 == 0) :
9 print ( " {} is divisble by 3 " . format ( n ) )
10 else :
11 print ( " {} is neither divisble by 2 nor by 3 " . format ( n ) )
Listing 2.3: Example for nested if...else

2.1.3 elif Statement


elif statement can be used to check more than one condition and thereby creating more than two
branches.
1 statement x
2 if condition 1:
3 statement block 1
4 elif condition 2
5 statement block 2
6 elif condition 3
7 statement block 2
8 .
9 .
10 .
11 else :
12 statement block n
13 statement y
Listing 2.4: Syntax for if...elif..else
condition 1 will be evaluated first. If it is TRUE then statement block 1 will be executed. If it is
FALSE, condition 2 will be evaluated. If it is TRUE, statement block 2 will executed. This process
will go on. If none of the conditions are evaluated to TRUE, then statement block n will be executed.
2.2 Iteration (Looping) Statements 21

1 marks = int ( input ( " Enter your marks in 100: " ) )


2
3 if marks >= 80 and marks <= 100:
4 print ( " Distinction " )
5 elif marks >= 60 and marks < 80:
6 print ( " First Class " )
7 elif marks >= 50 and marks < 60:
8 print ( " Second Class " )
9 elif marks >= 40 and marks < 50:
10 print ( " Third Class " )
11 elif marks >=0 and marks < 40:
12 print ( " Failed " )
13 else :
14 print ( " Invalid Marks " )
Listing 2.5: Example for if...elif...else

2.2 Iteration (Looping) Statements


Looping statements are used to execute a block of statements repeatedly. Flowchart for looping
statement is given in Figure 2.2.

Code

False
Condition

True
Loop Body Code

Figure 2.2: Flowchart for Looping Statement

2.2.1 while Loop


while loop is used to execute a block of statements repeatedly until the specified condition becomes
FALSE.
1 statement x
2 while condition :
3 loop body
4 statement y
Listing 2.6: Syntax for while
The condition is evaluated first. If it is TRUE, statements in the loop body are executed. Then the
condition is evaluated again. This process will continue until the condition becomes FALSE.
1 n = int ( input ( " Enter a number : " ) )
2 print ( " The multiplication table for " , n )
3 i = 1
4 while i <= 10:
5 print ( ' {} x {} = {} '. format (i ,n , i * n ) )
6 i = i + 1
Listing 2.7: Example for while
22 Chapter 2. Control Statements and Python Data Structures

This example prints the multiplication table for a number from 1 to 10.

2.2.2 for Loop


for loop is used to repeat a block of statements by iterating over a sequence such as string, list,
tuple etc.
1 statement x
2 for variable in sequence :
3 loop body
4 statement y
Listing 2.8: Syntax for for

variable is first bound to the first item in the sequence and the loop body is executed. The variable
is then assigned the second value in the sequence and the loop body is executed again. This process
continues until the sequence is exhausted or a break statement is encountered within the loop body.
1 name = input ( " Enter your name : " )
2 print ( " The letters in your name are " )
3 for l in name :
4 print ( l )
Listing 2.9: Example for for

This example iterates over the input string and display each letter in the string in each iteration.

2.2.3 range() Function


range() function is normally used with for loop for generating a sequence of numbers. range()
function takes 3 arguments: start, stop and step.
• start specifies the starting integer in the sequence. This argument is optional. By default it
is 0.
• stop specifies the integer where the range should stop (not included).
• step specifies the increment for sequence. step can be positive or negative. This is an optional
argument. By default, it is 1.
1 # Prints numbers from 0 to 9
2 for i in range (10) :
3 print ( i )
4
5 # Prints numbers from 10 to 19
6 for i in range (10 ,20) :
7 print ( i )
8
9 # Prints numbers 10 ,12 ,14 ,16 ,18
10 for i in range (10 ,20 ,2) :
11 print ( i )
12
13 # Prints numbers from 20 to 11
14 for i in range (20 ,10 , -1) :
15 print ( i )
Listing 2.10: Example for range() function

2.3 Lists
List is an ordered sequence of values. Each value in the list is associated with an index which starts
at 0. Values inside a list need not be of the same type. List is created by writing the values separated
by comma inside a pair of square brackets. An empty list can be written as []. Individual elements
2.3 Lists 23

inside a list can be accessed by writing the index of the element within square brackets. A negative
indexing, starting from -1 for the last element of a list can also be used. Slicing operator (:) can
be used to retrieve a range of values from a list. + operator can be used to concatenate two lists. *
operator can be used to repeat a list.
1 lst1 = [ " hello " , " world " , 5 , 2.35]
2 lst2 = [10 ,11]
3
4 print ( lst1 ) # Prints [ ' hello ', ' world ', 5 , 2.35]
5 print ( lst1 [2]) # Prints 5
6 print ( lst1 [ -1]) # Prints 2.35
7 print ( lst1 [ -2]) # Prints 5
8 print ( lst1 [1:3]) # Prints [ ' world ', 5]
9 print ( lst1 [1:]) # Prints [ ' world ', 5 , 2.35]
10 print ( lst1 [:2]) # Prints [ ' hello ',' world ', 5]
11
12 lst3 = lst1 + lst2 # Concatenates lst1 and lst2
13 print ( lst3 ) # Prints [ ' hello ', ' world ', 5 , 2.35 , 10 , 11]
14
15 lst4 = lst2 *2
16 print ( lst4 ) # Prints [10 , 11 , 10 , 11]
17
18 lst2 [1]=15 # Changes the value at index 1
19 print ( lst2 ) # Prints [10] ,15]
Listing 2.11: Example for list

2.3.1 List Functions and Methods


Many built in functions and methods are available in python that helps to work with lists.

Adding items to list using append, insert and extend methods


• append(object) method can be used to append an object to the end of a list.
• insert(index, object) method can be used to insert an object to a list at the specified index.
• extend(sequence) method can be used to add the elements of the sequence object at the end
of the list.
1 countries1 = [ " India " , " Maldives " , " Switzerland " ]
2 countries2 = [ " UAE " , " Netherlands " , " USA " ]
3
4 # Appending " Candada " to the end of the list countries1
5 countries1 . append ( " Canada " )
6 # Prints [ ' India ', ' Maldives ', ' Switzerland ', ' Canada ']
7 print ( countries1 )
8
9 # Inserting " New Zealand " at index 2 of the lsit countries1
10 countries1 . insert (2 , " New Zealand " )
11 # Prints [ ' India ', ' Maldives ', ' New Zealand ', ' Switzerland ', ' Canada ']
12 print ( countries1 )
13
14 # Appending list countries2 to countries1
15 countries1 . append ( countries2 )
16 # Prints [ ' India ', ' Maldives ', ' New Zealand ', ' Switzerland ', ' Canada ',
[ ' UAE ', ' Netherlands ', ' USA ']]
17 print ( countries1 )
18
19 # Resetting Lists
20 countries1 = [ " India " , " Maldives " ]
21 countries2 = [ " UAE " , " Netherlands " , " USA " ]
22
24 Chapter 2. Control Statements and Python Data Structures

23 # Extending the list countries1 with items of the list countries1


24 countries1 . extend ( countries2 )
25 # Prints [ ' India ', ' Maldives ', ' UAE ', ' Netherlands ', ' USA ']
26 print ( countries1 )
Listing 2.12: Adding items to a list

Removing items in a list using remove() and pop() methods


• remove(object) method can be used to remove the specified object from a list.
• pop(index) removes the item from the specified index and returns it. The argument index is
optional. If not specified, the last item in the list will be popped out.
1 a = [13 ,10 ,45 ,56 ,25]
2 print ( a ) # Prints the list
3
4 a . remove (45) # Remove item 45 from the list
5 print ( a ) # Prints [13 , 10 , 56 , 25]
6
7 a . pop (2) # Pop the item at index 2
8 print ( a ) # Prints [13 , 10 , 25]
9
10 a . pop () # Pop the last item
11 print ( a ) # Prints [13 , 10]
Listing 2.13: Removing items in a list

count() Method
count(object) method returns how many times the object appears in the list.
1 a = [13 ,10 ,45 ,10 ,25]
2 print ( a . count (10) ) # Prints 2
3 print ( a . count (25) ) # Prints 1
4 print ( a . count (99) ) # Prints 0
Listing 2.14: Example for count() method

reverse() Method
reverse() method reverses the objects of a list.
1 a = [13 ,10 ,45 ,10 ,25]
2 print ( a ) # Prints [13 , 10 , 45 , 10 , 25]
3 a . reverse ()
4 print ( a ) # Prints [25 , 10 , 45 , 10 , 13]
Listing 2.15: Example for reverse() method

clear() Method
clear() method removes all the objects from a list.
1 a = [13 ,10 ,45 ,10 ,25]
2 print ( a ) # Prints [13 , 10 , 45 , 10 , 25]
3 a . clear ()
4 print ( a ) # Prints []
Listing 2.16: Example for clear() method
2.3 Lists 25

index() Method
index(object) method returns the index of the specified object. If the specified object does not exist
in the list, it raises an error.
1 a = [13 ,10 ,45 ,10 ,25]
2 print ( a . index (45) ) # Prints 2
3 print ( a . index (99) ) # Raises an error
Listing 2.17: Example for index() method

sort() Method
sort() method sorts the items on the list in ascending order. sort(reverse=True) can be used to sort
the list in descending order.
1 a = [13 ,10 ,45 ,10 ,25]
2 w = [ " kerala " , " karanataka " , " tamilnadu " ]
3 print ( a ) # Prints [13 , 10 , 45 , 10 , 25]
4 a . sort ()
5 print ( a ) # Prints [10 , 10 , 13 , 25 , 45]
6 w . sort ()
7 print ( w ) # Prints [ ' karanataka ', ' kerala ', ' tamilnadu ']
8 a . sort ( reverse = True )
9 print ( a ) # Prints [45 , 25 , 13 , 10 , 10]
Listing 2.18: Example for sort() method

Functions that can be applied to lists


• len(list):
Returns the number of items in the list.
• max(list):
Returns the maximum value in the list.
• min(list): Returns the minimum value in the list.
• map(function, list): Returns a list containing items which are obtained by applying the
function to each item in the list.
• sum(list): Returns the sum of the elements in the list.
• sorted(list): Returns a list with all the items of the list specified as sorted. Unlike the
sort() method, the original list will remain as it is.

1 a = [13 ,10 ,45 ,10 ,25]


2 print ( min ( a ) ) # Prints 10
3 print ( max ( a ) ) # Prints 45
4 print ( sum ( a ) ) # Prints 103
5 print ( len ( a ) ) # Prints 5
6 a2 = sorted ( a ) # Returns a new list with items in list a sorted
7 print ( a ) # Prints [13 , 10 , 45 , 10 , 25]
8 print ( a2 ) # Prints [10 , 10 , 13 , 25 , 45]
9
10 w = [ " kerala " , " karanataka " , " tamilnadu " ]
11 print ( min ( w ) ) # Prints karnataka
12 print ( max ( w ) ) # Prints tamilnadu
13 print ( len ( w ) ) # Prints 3
14
15 # Returns list with len function applied to all the items in w
16 w2 = list ( map ( len , w ) )
17 print ( w2 ) # Prints [6 , 10 , 9]
Listing 2.19: Examples for list functions
26 Chapter 2. Control Statements and Python Data Structures

Other useful functions


• split(separator,maxpsplits): This method can be used with string to obtain a list from a
given string. The string will be split based on a separating character given as argument
(separator). If no separating character is given, then space will be taken as the separating
character. maxpsplits specifies the maximum number of splits to be created.
1 states = " kerala , karnataka , tamilnadu , assam "
2 # Split the string using , as separating character
3 slist = states . split ( " ," )
4 # Prints [ ' kerala ', ' karnataka ', ' tamilnadu ', ' assam ']
5 print ( slist )
6
7 # Split the string using , as separating character
8 # and maximum splits as 2
9 slist = states . split ( " ," ,2)
10 # Prints [ ' kerala ', ' karnataka ', ' tamilnadu , assam ']
11 print ( slist )
Listing 2.20: Examples for split() functions

1 # Enter marks . e . g . 10 20 30
2 marks = input ( " Enter marks in 3 subjects spearted by space : " )
3 # split () splits the marks after each space and returns a list
4 # map () function converts each item in the list to integer
5 marklist = list ( map ( int , marks . split () ) )
6 # Prints [10 , 20 , 30]
7 print ( marklist )
Listing 2.21: Using split() and map()

2.4 Tuples
Like list, a tuples is an ordered sequence of values. Each value in the tuple is associated with an
index which starts at 0. Values inside a tuple need not be of the same type. Unlike list, a tuple is
created by writing the values separated by comma inside a pair of parentheses. The main difference
between a tuple and a list is that, lists are mutable (can be modified), whereas tuples are immutable
(Once created, cannot be modified). An empty tuple can be written as (). Individual elements inside
a tuple can be accessed by writing the index of the element within square brackets. A negative
indexing, starting from -1 for the last element of a tuple can also be used. Slicing operator ( : ) can
be used to retrieve a range of values from a tuple. + operator can be used to concatenate two tuples.
* operator can be used to repeat a tuple.
1 tup1 = ( " hello " , " world " , 5 , 2.35)
2 tup2 = (10 ,11)
3
4 print ( tup1 ) # Prints ( ' hello ', ' world ', 5 , 2.35)
5 print ( tup1 [2]) # Prints 5
6 print ( tup1 [ -1]) # Prints 2.35
7 print ( tup1 [ -2]) # Prints 5
8 print ( tup1 [1:3]) # Prints ( ' world ', 5)
9 print ( tup1 [1:]) # Prints ( ' world ', 5 , 2.35)
10 print ( tup1 [:2]) # Prints ( ' hello ',' world ', 5)
11
12 tup3 = tup1 + tup2 # Concatenates lst1 and lst2
13 print ( tup3 ) # Prints ( ' hello ', ' world ', 5 , 2.35 , 10 , 11)
14
15 tup4 = tup2 *2
16 print ( tup4 ) # Prints (10 , 11 , 10 , 11)
2.5 Sets 27

17
18 tup2 [1]=15 # Results in an error since tuple is immutable
Listing 2.22: Example for tuple

2.4.1 Functions that can be applied to tuples


The functions max, min, sum, len and sorted, which can be applied to lists, can also be applied to
tuples in the same manner. Refer section 2.3.1.

2.5 Sets
Set is an unordered collection of objects. Values inside a set need not be of the same type. A set is
created by writing the values separated by comma inside a pair of curly brackets. Since objects in
a set are unordered, they cannot be accessed using indexing. A set contains only unique values. If
a value is entered multiples times while creating a set, duplicates will be removed. An empty set
can be created using the set function.
1 s1 = {1 , 2 , 3 , " hello " , 3}
2 s2 = set () # Creates an empty set
3 s3 = set ([2 ,3 ,5 ,7]) # Creates a set from a list
4
5 print ( s1 )
6 # Prints {1 , 2 , 3 , ' hello '}. Duplicate 3 is removed .
7 # The order of items may get changed during each execution .
8 print ( s3 )
9 # Prints {2 , 3 , 5 , 7}
10 # The order of items may get changed during each execution .
Listing 2.23: Example for tuple

2.5.1 Methods of Sets


Adding items to a set using add() method
• add(object) method can be used to add the specified object to a set.
1 s1 = {11 ,22 ,33}
2 print ( s1 ) # Prints {33 , 11 , 22}
3 s1 . add (44)
4 print ( s1 ) # Prints {33 , 11 , 44 , 22}
5 s1 . add (33) # No effect since 33 is already in the list
6 print ( s1 ) # Prints {33 , 11 , 44 , 22}
Listing 2.24: Example for add method for set

Removing items from a set using remove(), discard() and pop() methods
• remove(object) method can be used to remove the specified object from a set. A key error
will be raised if object to be deleted is not in the set or the set is empty.
1 s1 = {11 ,22}
2 print ( s1 ) # Prints {11 , 22}
3 s1 . remove (22)
4 print ( s1 ) # Prints {11}
5 s1 . remove (11)
6 print ( s1 ) # Prints set () ( i . e . empty set )
7 s1 . remove (33) # Raises a key error since 33 is not in the set
Listing 2.25: Example for remove method for set
28 Chapter 2. Control Statements and Python Data Structures

• discard(object) method can be used to remove the specified object from a set. No error will
be raised if the item to be discarded is not in the set.
1 s1 = {11 ,22}
2 print ( s1 ) # Prints {11 , 22}
3 s1 . discard (22)
4 print ( s1 ) # Prints {11}
5 s1 . discard (33)
6 print ( s1 ) # Prints {11}
Listing 2.26: Example for discard method for set

• pop() method can be used to remove an arbitrary item from a set. This method returns the
item removed from the set. Key error will be raised if the set is empty.
1 s1 = {11 ,22 ,33}
2 print ( s1 ) # Prints {33 , 11 , 22}
3 i = s1 . pop () # Remvoes a random item , say 33
4 print ( i ) # Prints 33
5 print ( s1 ) # Prints {11 , 22}
Listing 2.27: Example for pop method for set

Set operations using union(), intersection() and difference() methods


• s1.union(s2) method will find the union of sets s1 and s2.
• s1.intersection(s2) method will find the intersection of sets s1 and s2.
• s1.difference(s2) method will find the intersection of sets s1 and s2 (s1- s2).
1 odd_numbers = {1 ,3 ,5 ,7 ,9}
2 even_numbers = {2 ,4 ,6 ,8 ,10}
3 prime_numbers = {2 ,3 ,5 ,7}
4 print ( odd_numbers . union ( prime_numbers ) )
5 # Prints {1 , 2 , 3 , 5 , 7 , 9}
6 print ( even_numbers . intersection ( prime_numbers ) )
7 # Prints {2}
8 print ( odd_numbers . difference ( prime_numbers ) )
9 # Prints {1 ,9}
Listing 2.28: Example for set operations

isdisjoint(), issubset() and issuperset() methods


• s1.isdisjoint(s2) method is used to check whether sets s1 and s2 are disjoint. It returns
TRUE, if they are disjoint and FALSE otherwise.
• s1.issubset(s2) method is used to check whether s1 is a subset of s2. If yes, it returns TRUE,
and FALSE otherwise.
• s1.issuperset(s2) method is used to check whether s1 is a superset of s2. If yes, it returns
TRUE, and FALSE otherwise.

1 odd_numbers = {1 ,3 ,5 ,7 ,9}
2 even_numbers = {2 ,4 ,6 ,8 ,10}
3 prime_numbers = {2 ,3 ,5 ,7}
4 numbers = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10}
5 print ( odd_numbers . isdisjoint ( even_numbers ) ) # Prints True
6 print ( odd_numbers . isdisjoint ( prime_numbers ) ) # Prints False
7 print ( odd_numbers . issubset ( numbers ) ) # Prints True
8 print ( numbers . issuperset ( even_numbers ) ) # Prints True
Listing 2.29: Example for isdisjoint(), issubset() and issuperset()
2.6 Dictionaries 29

2.5.2 Functions that can be applied to sets


The functions max, min, sum, len and sorted, which can be applied to lists and tuples, can also be
applied to sets in the same manner. Refer section 2.3.1.

2.6 Dictionaries
A dictionary is a collection of key:value pairs. In other words, each value in a dictionary is
associated with a key. The key:value pairs are enclosed in a pair of curly brackets and are separated
by commas. Values in a dictionary can be any object and may not be unique. But keys in a
dictionary should be immutable (numbers, string or tuples) and unique. An empty dictionary is
created using {}. Values in a dictionary can be accessed by putting the key inside square brackets.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( marks ) # Prints { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
3
4 print ( marks [ ' Mat ' ]) # Prints 48
5
6 marks [ ' Bio '] = 47 # Adds a new key value pair to the dictionary
7 print ( marks ) # Prints { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48 , ' Bio ': 47}
Listing 2.30: Example for dictionary

2.6.1 Functions that can be applied to dictionary


len() function
• len() function can be used to find the number of items (key:value pairs) in a dictionary.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( len ( marks ) ) # Prints 3
Listing 2.31: Example for len() function

str() function
• str() function can be used to get a string representation of a dictionary.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( str ( marks ) ) # Prints { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
Listing 2.32: Example for str() function

2.6.2 Methods of Dictionaries


keys() Method
• keys() method returns a view object which contains a list of all the keys in the dictionary.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( marks . keys () ) # Prints dict_keys ([ ' Phy ', ' Chem ', ' Mat '])
Listing 2.33: Example for keys() method

values() Method
• values() method returns a view object which contains a list of all the values in the dictionary.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( marks . values () ) # Prints dict_values ([45 , 40 , 48])
Listing 2.34: Example for values() method
30 Chapter 2. Control Statements and Python Data Structures

items() Method
• items() method returns a view object which contains a list of all the key value pairs as a
tuple.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( marks . items () )
3 # Prints dict_items ([( ' Phy ', 45) , ( ' Chem ', 40) , ( ' Mat ', 48) ])
Listing 2.35: Example for items() method

get() Method
• get(key,default) method returns the value for the specified key. default argument is optional.
If the key does not exist, then it returns the default value. If default argument is not given
and the specified key does not exist, then it returns None.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 print ( marks . get ( ' Phy ') ) # Prints 45
3 print ( marks . get ( ' Bio ') ) # Prints None
4 print ( marks . get ( ' Bio ' ," Does not exist " ) ) # Prints Does not exist
Listing 2.36: Example for get() method

clear() Method
• clear() method clears all the items from the dictionary.
1 marks = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 marks . clear ()
3 print ( marks ) # Prints {}
Listing 2.37: Example for clear() method

update() Method
• d1.update(d2) method can be used to add/update multiple key:value pairs with a single
statement. key:value pairs from the disctionary d2 will be added/updated to the dictionary d1.
1 m1 = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 m2 = { ' Mat ' :50 , ' Bio ' :42}
3 m1 . update ( m2 )
4 print ( m1 ) # Prints { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 50 , ' Bio ': 42}
Listing 2.38: Example for update() method

2.6.3 Iterating over dictionary items


in operator along with the items() method of the dictionary can be used to iterate over items in a
dictionary.
1 m1 = { ' Phy ': 45 , ' Chem ': 40 , ' Mat ': 48}
2 for k , v in m1 . items () :
3 print ( ' Marks in {} is {} '. format (k , v ) )
4 # Prints
5 # Marks in Phy is 45
6 # Marks in Chem is 40
7 # Marks in Mat is 48
Listing 2.39: Iterating over dictionary items
2.7 The enumerate() Function 31

2.7 The enumerate() Function


enumerate() function returns an enumerate object, taking a collection of items as input. It adds a
counter as the key of the enumerate object.
1 states = ( ' kerala ' , ' karnataka ' , ' tamilnadu ')
2
3 for i , value in enumerate ( states ) :
4 print (i , " : " , value )
5
6 # Prints the folowing
7 # 0 : kerala
8 # 1 : karnataka
9 # 2 : tamilnadu
Listing 2.40: Using enumerate() to iterate over a tuple

2.8 Mutable and Immutable Objects


In python, any object whose value can be modified after its creation is called a mutable object
and any object whose value cannot be modifed after creation is called an immutable object. Every
object in python has an associated id which represents its memory location.
1 marks = [11 ,22 ,33]
2 print ( id ( marks ) ) # Prints the id , say 139684592739392
3 marks [1] = 44
4 print ( id ( marks ) ) # Prints the same id 139684592739392
Listing 2.41: list is mutable

In this example, changing the value inside a list does not change the id of the list because list is a
mutable object in python.
1 marks = (11 ,22 ,33)
2 print ( id ( marks ) ) # Prints the id , say 139684592739392
3 marks [1] = 44 # Raises an error since tuple is mutable
4 marks = (44 ,55)
5 print ( id ( marks ) # Prints a different id , say 139684601537600
Listing 2.42: tuple is immutable

In this example, changing the value inside a tuple raises an error, because tuple is an immutable
object in python. Giving a new values to the same variable (Line no. 4) will create different object
with different id.
• Lists, dictionaries and sets are mutable objects in python.
• int, float, string, tuple etc. are immutable objects in python.
3. Functions, Modules, Files, Exceptions

3.1 Functions
A function is a group of related statements that does a particular task. The task may be something
that is repeatedly used in a program. Once a function is defined, it can be called any number of
times to perform the designated task. This helps to reuse the code once written. Functions also
helps to divide the program to smaller units thereby making it simple to understand. One way to
categorize function is
1. User-defined functions created by the programmer.
2. Built-in functions which are already defined in the language. (e.g. sorted, min, sum, input,
print).

3.1.1 Function Definition


Syntax for defining a function in python is given below.
1 def function_name ( f ormal_ param eter_l ist ) :
2 docstring
3 function_statements
Listing 3.1: Syntax for Function Definition

• All statements inside a function should be intended


• formal_parameter_list is a comma separated list of variables that accepts the values passed
to the function when it is being called.
• docstring is optional. A Docstring is a string that appears as the first statement inside a
function, module or class. It is used to document what the function does.
• function_statements (function body) can be any valid python statement.
• Function body is executed until either of the following occurs
– A return statement is encountered. In this case, the value of the expression following
the return statement becomes the value of the function and it is passed back to the
statement which called the function.
– There are no statements to execute. In this case, the function returns None.
34 Chapter 3. Functions, Modules, Files, Exceptions

A function which returns the larger of two numbers passed to it is given below.
1 def findLarger ( fno , sno ) :
2 " Finds the larger among two numbers " # Docstring
3 if fno > sno :
4 return fno
5 else :
6 return sno
Listing 3.2: Example for Function Definition

3.1.2 Function Calling


Statements inside a function will not be executed until it is being called. A function can be called
by writing the name of the function followed by the actual parameters (also known as arguments)
within parentheses, in the same order as the matching formal arguments in the function definition.
1 def findLarger ( fno , sno ) :
2 " Finds the larger among two numbers "
3 if fno > sno :
4 return fno
5 else :
6 return sno
7
8 large = findLarger (10 ,20) # Function Call
9 print ( large ) # Prints 20
Listing 3.3: Example for Function Call
In this example, the function findLarger is being called by passing two arguments 10 and 20 (Line
No. 8). These values are bound to the formal parameters fno and sno respectively. The function
finds the larger of two values and returns it. This value gets stored in the variable large.

3.1.3 Function Arguments


Required Arguments
These are the arguments passed to the function in the same order as the formal parameters. If the
number of arguments passed (actual parameters) does not match the number of formal parameters,
then an error is raised. Refer the previous example in which the function findLarger is called using
required arguments.
Keyword Arguments
Keyword arguments allows to pass arguments using parameter name. Hence the order of actual
parameters need not be the same as the order of the actual parameters.
1 def checkPass ( name , marks ) :
2 " Displays whether a student has passed or not "
3 if marks >= 40:
4 print ( name , " has passed " )
5 else :
6 print ( name , " has failed " )
7
8 checkPass ( marks = 45 , name = ' Abcd ') # Prints Abcd has passed .
Listing 3.4: Keyword Arguments

Default Arguments
Keyword arguments are normally used along with default arguments. While defining a function, a
default value for an argument can be given. In such a case, if no object is passed for a parameter, it
will assume the default value.
3.1 Functions 35

1 def checkPass ( name , marks =30) :


2 " Displays whether a student has passed or not "
3 if marks >= 40:
4 print ( name , " has passed " )
5 else :
6 print ( name , " has failed " )
7
8 checkPass ( name = ' Abcd ') # Prints Abcd has failed .
9 checkPass ( marks =50 , name = ' Abcd ') # Prints Abcd has passed .
Listing 3.5: Keyword and Default Arguments

In this example, the first call to checkPass does not pass any value for the marks argument.
Hence it will be assigned a value 30 by default.

3.1.4 Recursion
Recursion is a process by which a function calls itself repeatedly until some specified condition has
been satisfied. This process is used for repetitive computations in which each action is stated in
terms of a previous result. In order to solve a problem recursively, two conditions must be satisfied.
1. The problem must be written in recursive form
2. The problem statement must include a stopping condition
For example, to find the factorial of a number, we can write the problem as

n! = n ∗ (n − 1)!

Also we know that

1! = 1 (Base case)

Therefore

n! = n ∗ (n − 1)!
(n − 1)! = (n − 1) ∗ (n − 2)!
(n − 2)! = (n − 2) ∗ (n − 3)!
..
2! = 2 ∗ 1!

Example 3.1. Write a recursive function to find the factorial of a number.

1 def factorial ( n ) :
2 " n should be an integer greater than 1 "
3 if n ==1: # Terminating condition
4 return 1
5 else :
6 return n * factorial (n -1) # Recursive Call
7
8 print ( factorial (7) ) # Prints 5040
Listing 3.6: Factorial using recursion

Example 3.2. Write a recursive function to generate fibonacci sequence.


36 Chapter 3. Functions, Modules, Files, Exceptions

1 def fib ( n ) :
2 " n should be an integer greater than or equal to 0 "
3 if n ==0 or n ==1:
4 return 1
5 else :
6 return fib (n -1) + fib (n -2)
7
8 def generateFib ( n ) :
9 for i in range ( n ) :
10 print ( fib ( i ) )
11
12 generateFib (10)
13 # Generates first 10 numbers in the fibonacci sequence
14 generateFib (12)
15 # Generates first 12 numbers in the fibonacci sequence
Listing 3.7: Fibonacci using recursion

3.2 Modules
A module is a file with extension .py which contains python statements and definitions. Modules
are used to divide large programs to into smaller units. Once created, a module can be imported to
another python script, thereby providing reusability. Python has lots of standard (built-in) modules.

3.2.1 Importing Modules


A module can be imported to another python file using the import statement. All the definitions
inside that module can be used in the file where the module has been imported, using the dot
operator.
1 import module_name
Listing 3.8: Syntax for import

1 import math # Import the built - in math module


2 print ( math . sqrt (81) ) # Prints 9.0
Listing 3.9: Example for import

In this example, the sqrt() function defined inside the built-in module math is accessed by writing
the name of the module (math) followed by the dot operator and the function.
Importing modules by renaming
While importing, an alias name can be given to the module which can be used thereafter in the
program instead of the original name.
1 import math as mat # Import the built - in math module with alias mat
2 print ( mat . sqrt (81) ) # Prints 9.0
Listing 3.10: Example for import by renaming

Importing only specific functions from a module


Rather than importing the entire module, required functions can be imported. In this case, the
functions can be written directly without using the name of the module and the dot operator. This is
done with following syntax.
1 from module_name import def1 , def2 ,...
Listing 3.11: Syntax for importing specific functions from a module
3.2 Modules 37

1 from math import sqrt , factorial # Import sqrt and factorial from math
2 print ( sqrt (81) ) # Prints 9.0
3 print ( factorial (5) ) # Prints 120
Listing 3.12: Example for importing specific functions from a module

3.2.2 The math Module


math module provides access to the mathematical functions defined by the C standard. Some
examples for functions and constants defined in the math module are given in Table 3.1 and Table
3.2 respectively.

Function Description
Returns the ceiling of the number n (Smallest integer greater than or
math.ceil(n)
equal to n).
math.floor(n) Returns the floor of the number n (Largest integer less than or equal to n).
n!
math.comb(n,r) Returns k!(n−k)! , the number of ways to select r items from n items.
n!
Returns n−k)! , the number of ways to arrange r items selected from n
math.perm(n,r)
items.
math.factorial(n) Returns the factorial of n, n!.
math.gcd(n1,n2) Returns the GCD of the numbers n1 and n2
Returns the logarithm of n to the base. base is optional, which is e (natural
math.log(n,base)
logarithm) by default.
math.pow(n,p) Returns n p .

math.sqrt(n) Returns n.
math.sin(n) Returns sin(n) where n is in radians.
math.cos(n) Returns cos(n) where n is in radians.
math.tan(n) Returns tan(n) where n is in radians.

Table 3.1: Functions in math module

Constant Description
math.pi Value of π = 3.141592...
math.e Value of e = 2.718281...

Table 3.2: Constants in math module

1 import math
2
3 print ( math . ceil (5.015) ) # Prints 6
4 print ( math . floor (5.015) ) # Prints 5
5 print ( math . log (100 ,10) ) # Prints 2
6 print ( math . comb (5 ,3) ) # Prints 10
7 print ( math . perm (5 ,3) ) # Prints 60
8 print ( math . gcd (8 ,12) ) # Prints 4
9 print ( math . sin ( math . pi /2) ) # Prints 1.0
Listing 3.13: Examples for functions in math module
38 Chapter 3. Functions, Modules, Files, Exceptions

3.2.3 The statistics Module


statistics This module provides functions for calculating mathematical statistics of numeric (Real-
valued) data. Some examples for functions defined in the statistics module are given in Table 3.3.
The functions take a dataset as input which can be any sequence such as lists.

Function Description
statistics.mean() Returns the arithmetic mean of the given data.
statistics.median() Returns the median of the given data.
statistics.mode() Returns the mode of the given data.
statistics.pstdev() Returns the standard deviation from an entire population.
statistics.stdev() Returns the standard deviation from a sample data.
statistics.pvariance() Returns the variance from an entire population.
statistics.variance() Returns the standard variance from a sample data.

Table 3.3: Functions in math module

1 import statistics
2
3 data = [10 ,20 ,25 ,15 ,10]
4
5 print ( statistics . mean ( data ) ) # Prints 16
6 print ( statistics . median ( data ) ) # Prints 15
7 print ( statistics . stdev ( data ) ) # Prints 6.519202405202649
8 print ( statistics . variance ( data ) ) # Prints 42.5
Listing 3.14: Examples for functions in statistics module

3.2.4 Creating Modules


A programmer can create a module by defining functions and saving the file as a .py file. The
module can be then used in another script by importing it. An example is given below.
1 def getfib ( n ) :
2 " n should be an integer greater than or equal to 0 "
3 if n ==0 or n ==1:
4 return 1
5 else :
6 return getfib (n -1) + getfib (n -2)
Listing 3.15: fib.py

1 import fib # Importing the module fib


2
3 for i in range (10) :
4 print ( fib . getfib ( i ) ) # Accesing the getfib () defined in fib module
Listing 3.16: generatefib.py

3.3 Files
A file inside a computer’s memory stores some data. A file is identified by a file name. Each
operating system has its own file system. Python provides file accessing capability irrespective of
the operating system, through file handles. For example,
1 fh = open ( ' marks . txt ' , 'w ')
3.3 Files 39

creates a file named "marks.txt" and returns a file handle (fh) with which the file can be accessed.
File operations in python can be done in 3 steps.
1. Opening the file
2. Reading/Writing the file
3. Closing file

3.3.1 Opening a file using open() function


A file needs to be opened before it is read or written. open() function is used to open a file. open()
function returns a file handle, which can be used to read contents in a file or write contents to a file.
Most commonly open function takes 2 arguments as shown in the syntax below.
1 filehandle = open ( filename , mode )
Listing 3.17: Syntax for opening a file

• filename is the name of the file.


• mode is written as a string which specifies the way in which the file will be accessed. mode
can be "r", "w", "a" or "x". By default the files are opened in text mode ("t"). This can
be changed to binary mode ("b") when opening files such as images where data will be in
binary format. mode can be any of the following.

Mode Description
This mode specifies read mode. It is the default value. This mode opens a file for
"r"
reading its contents. An error will be raised if the file does not exist.
This mode specifies write mode. This mode opens a file for writing. A new file
"w"
will be created if the file does not exist, otherwise it will overwrite the existing file.
This mode specifies append mode. This mode opens a file for appending to an
"a"
existing file. A new file will be created if the file does not exist.
This mode specifies exclusive creation mode. This mode creates the specified
"x" file and raises an error if the file already exists. This helps to prevent accidental
overwriting of a file.
"r+" This mode opens a file for reading and writing.
This mode opens a file for writing and reading. A new file will be created if the
"w+"
file does not exist, otherwise it will overwrite the existing file.
"a+" This mode opens a file for appending and reading.
"rb" This mode opens a file for reading in binary mode.
"wb" This mode opens a file for writing in binary mode.
"ab" This mode opens a file for appending in binary mode.
"rb+" This mode opens a file for reading and writing in binary mode.
"wb+" This mode opens a file for writing and reading in binary mode.
"ab+" This mode opens a file for appending and reading in binary mode.

• filehandle is a file object returned by the open() function. Some of the properties of the file
object are,
– closed: Returns True if the file is closed, False otherwise.
– name: Returns the name of the opened file.
– mode: Retuens the mode in which the file is opened.
1 myfile = open ( " sample . txt " ," w " )
2
3 print ( myfile . closed ) # Prints False
4 print ( myfile . mode ) # Prints w
40 Chapter 3. Functions, Modules, Files, Exceptions

5 print ( myfile . name ) # Prints sample . txt


6
7 myfile . close () # Closing the file
8 print ( myfile . closed ) # Pritns True
Listing 3.18: Example for File Properties

3.3.2 Closing a file using close() method


Once the file operations are completed, the opened file must be closed. This will free up the
resources held up by the file. An opened file can be closed using the close() method of the file
object.
1 myfile = open ( " sample . txt " ," w " )
2 print ( myfile . name ) # Prints sample . txt
3
4 myfile . close () # Closing the file
5 print ( myfile . closed ) # Pritns True
Listing 3.19: Example for closing a file

3.3.3 Writing to a file using the write() method


A file can be written using the following steps.
1. Open the file in any of the following mode (either text or binary)
• "w": Creates a new file if it does not exist. Overwrites the file if it already exists.
• "a": Creates a new file if it does not exist. Appends to the end of the file if it already
exists.
• "x": Creates a new file if it does not exist. Raises an error if it already exists.
2. Write to the file using the write() method of the file object.
1 filehandle . write ( string )

• filehandle is the file object returned by the open() function.


• string is the content to be written in to the file.
• write() method does not add a new line at the end of the string.
1 studfile = open ( " students . txt " ," a " ) # Open the file in append mode
2
3 more = 'y ' # Used to repeat user input
4 while more == 'y ':
5 line = input ( " Enter the student details : " )
6 studfile . write ( line ) # Write the student details to the file
7 studfile . write ( " \ n " ) # Writes a new line
8 more = input ( " Do you want to conitnue ( y / n ) : " )
9
10 studfile . close () # Closing the file
Listing 3.20: Example for writing to a file

This example will get the student details from the user and add that to file "student.txt".
Using with statement
with statement in python can be used along with open() and write() method. This will close the
file automatically after the nested block of code inside the with statement is over or an exception is
occurred inside the block or a return statement is executed.
1
2 with open ( " students . txt " ," a " ) as studfile :
3 more = 'y ' # Used to repeat user input
3.4 Exceptions 41

4 while more == 'y ':


5 line = input ( " Enter the student details : " )
6 studfile . write ( line ) # Write the student details to the file
7 studfile . write ( " \ n " ) # Writes a new line
8 more = input ( " Do you want to conitnue ( y / n ) : " )
Listing 3.21: Example for writing to a file

3.3.4 Reading a file using read() method


A file can be read by opening the file in read mode. Syntax is
1 filehandle . read ( size )

• filehandle is the file object returned by the open() function.


• size is an optional argument used to specify the number of bytes to be read. If not specified,
it will read the entire file.
1 studfile = open ( " students . txt " ," r " )
2 contents = studfile . read (6) # Reads only the first 6 bytes
3 print ( contents )
4 studfile . close ()
5
6 studfile = open ( " students . txt " ," r " )
7 contents = studfile . read () # Reads the entire file
8 print ( contents )
9 studfile . close ()
Listing 3.22: Example for reading a file

3.4 Exceptions
Exceptions are errors that occur during execution of a program. These errors does not occur
always. It may be due to some invalid input. An example is division by 0 exception. Python
provides mechanisms to handle exceptions, so that the program execution will continue rather than
terminating.

3.4.1 Built-in Exceptions


Python has a collection of built-in exception classes. If any of these exception occurs during the
execution of the program, they can be handled gracefully.

IndexError
An IndexError is raised when an attempt is made to access an index from a sequence (such as list,
tuple) that is out of the range.

OverflowError
An OverflowError exception is raised when the result of an arithmetic operation is too large to be
represented.

ZeroDivisionError
An ZeroDivisionError is raised when the divisor argument of a division or modulo operation is
zero.

RuntimeError
An RuntimeError is raised when an error occurs that does not belong to any other classes of
exception.
42 Chapter 3. Functions, Modules, Files, Exceptions

3.4.2 Exception Handling


Exceptions can be handled by putting the statements that may cause runtime errors inside a try
block. An except block should be created to handle each exception. If any error occurs inside the
try block, control will be transferred to the except block. A try block should be followed by at
least one except block.
1 try :
2 Statements that may cause exception
3 except Exception1 :
4 Statements to handle Exception1
5 except Exception2 :
6 Statements to handle Exception2
7 .
8 .
9 else :
10 Statements executed when there are no errors
11 finally :
12 Statements executed always
Listing 3.23: Syntax for Excpetion Handling

• If any error occurs inside the try block, the control will be transferred to the except block for
the corresponding exception.
• The optional else block can contain statements that need to be executed if no errors were
raised.
• The optional finally block can contain statements that need to be executed regardless of
whether an error occurred or not.
• An except block for the base class Exception may be written to handle exceptions that do not
belong to any of the exceptions mentioned in the except blocks.
• If an exception occurs in the try block, the statements inside the first matching except block
will be executed and all other except blocks will be skipped. Hence except block for each
exception should be written in the order of priority. If there is an except block written for the
base class Exception to handle all unhandled exceptions, it is recommended to write it as the
last except block.
1 try :
2 divisors = [0 ,2 ,5]
3 n = int ( input ( " Enter a number : " ) ) # Say 10
4 q = n / divisors [0] # Raises an exception
5 print ( q )
6 filename = input ( " Enter the file name : " )
7 f = open ( filename , " r " )
8 f . read ()
9 f . close ()
10 except ZeroDivisionError :
11 print ( " Divide by Zero Error " ) # Prints Divide by Zero Error
12 except IndexError :
13 print ( " Index out of range " )
14 except Exception :
15 print ( " Something went wrong " )
16 else :
17 print ( " Divided Successfully . " )
18 finally :
19 print ( " Thank you !!! " ) # Prints Thank You !!!
Listing 3.24: Handling ZeroDivisionError

In this example, an exception is raised in line no. 4 since the divisor is 0. This exception will be
caught by the except block for ZeroDivisionError (Line No. 10). After that, statements inside the
3.4 Exceptions 43

finally block will be executed.


1 try :
2 divisors = [0 ,2 ,5]
3 n = int ( input ( " Enter a number : " ) ) # Say 10
4 q = n / divisors [4] # Raises an exception
5 print ( q )
6 filename = input ( " Enter the file name : " )
7 f = open ( filename , " r " )
8 f . read ()
9 f . close ()
10 except ZeroDivisionError :
11 print ( " Divide by Zero Error " )
12 except IndexError :
13 print ( " Index out of range " ) # Prints Index out of range
14 except Exception :
15 print ( " Something went wrong " )
16 else :
17 print ( " Divided Successfully . " )
18 finally :
19 print ( " Thank you !!! " ) # Prints Thank You !!!
Listing 3.25: Handling IndexError

In this example, an exception is raised in line no. 4 since the index 4 of the list divisors is out of
range. This exception will be caught by the except block for IndexError (Line No. 12). After that,
statements inside the finally block will be executed.
1 try :
2 divisors = [0 ,2 ,5]
3 n = int ( input ( " Enter a number : " ) ) # Say 10
4 q = n / divisors [2]
5 print ( q ) # Prints 2.0
6 filename = input ( " Enter the file name : " ) # An invalid file name
7 f = open ( filename , " r " )
8 f . read ()
9 f . close ()
10 except ZeroDivisionError :
11 print ( " Divide by Zero Error " )
12 except IndexError :
13 print ( " Index out of range " )
14 except Exception :
15 print ( " Something went wrong " ) # Prints Something went wrong
16 else :
17 print ( " Divided Successfully . " )
18 finally :
19 print ( " Thank you !!! " ) # Prints Thank You !!!
Listing 3.26: Handling general Exception

In this example, an exception is raised in line no. 6 if an invalid file name is given. Since this
exception is not caught by the ZeroDivisionError and IndexError, this exception will be caught by
the except block for Exception (Line No. 14)1 . After that, statements inside the finally block will
be executed.
1 try :
2 divisors = [0 ,2 ,5]
3 n = int ( input ( " Enter a number : " ) ) # Say 10
4 q = n / divisors [2]
5 print ( q ) # Prints 2.0

1 There is a built-in exception class (FileNotFoundError) to handle invalid file names which is not discussed here.
44 Chapter 3. Functions, Modules, Files, Exceptions

6 filename = input ( " Enter the file name : " ) # A valid file name
7 f = open ( filename , " r " )
8 f . read ()
9 f . close ()
10 except ZeroDivisionError :
11 print ( " Divide by Zero Error " )
12 except IndexError :
13 print ( " Index out of range " )
14 except Exception :
15 print ( " Something went wrong " )
16 else :
17 print ( " Divided Successfully . " ) # Prints Divided Successfully .
18 finally :
19 print ( " Thank you !!! " ) # Prints Thank You !!!
Listing 3.27: When no exceptions are raised

If no exceptions are raised, then the statements inside the else block will also get executed.
4. Numpy Arrays and Data Visualization

4.1 Introduction
Array is a collection of items of same type. Each item in the list is associated with an index. Python
doest not have a built-in support for arrays. The features of arrays can be achieved using lists in
python.
In python, arrays can be created using
• array class in the standard python library.
• NumPy package which is one of the fundamental scientific packages in python.

4.2 array Class


One dimensional arrays can be created using the array class. This can be done by importing the
array module.
1 array ( datatype , valuelist )
Listing 4.1: Syntax for creating an array

Here, datatype specifies the type of values in the array. It can be any data type such as integer, float,
double etc. It is represented using a type code. Some of the type codes are listed below.
• i for signed integer
• l for signed long
• f for float
• d for double
1 import array as arr
2 # Creating an integer array
3 a = arr . array ( 'i ' , [11 , 22 , 34])
4
5 # Creating a float array
6 b = arr . array ( 'f ' , [2.5 , 3.2 , 3.3])
Listing 4.2: Example for array
46 Chapter 4. Numpy Arrays and Data Visualization

4.2.1 Accessing elements of an array


Individual elements inside an array can be accessed by writing the index of the element within
square brackets. A negative indexing, starting from -1 for the last element of an array can also be
used. Slicing operator (:) can be used to retrieve a range of values from an array.
1 import array as arr
2 # Creating an integer array
3 a = arr . array ( 'i ' , [11 , 22 , 34 , 45])
4
5 # Accessing the element at index 2 and prints 34
6 print ( a [2])
7
8 # Accessing the element at last index and prints 45
9 print ( a [ -1])
10
11 # Accessing the elements starting from index 1 to index 2
12 # Prints array ( ' i ', [22 , 34])
13 print ( a [1:3])
Listing 4.3: Accessing array elements

4.2.2 Adding elements to an array using insert() and append() methods


Elements can be added to an array at specified index using the insert() method. append() method
is used to add an element at the end of an array.
1 insert ( index , element )
2 append ( element )
Listing 4.4: Syntax for insert() and append

1 import array as arr


2 # Creating an integer array
3 a = arr . array ( 'i ' , [11 , 22 , 34 , 45])
4
5 # Adds an element at index 2
6 a . insert (2 , 99)
7 # Prints array ( ' i ', [11 , 22 , 99 , 34 , 45])
8 print ( a )
9
10 # Adds an element at the end
11 a . append (88)
12 # Prints array ( ' i ', [11 , 22 , 99 , 34 , 45 , 88])
13 print ( a )
Listing 4.5: Adding elements to an array

Removing elements in an array using remove() and pop() methods


• remove(element) method can be used to remove the specified element from a list.
• pop(index) removes the item from the specified index and returns it. The argument index is
optional. If not specified, the last item in the array will be popped out.
1 import array as arr
2 # Creating an integer array
3 a = arr . array ( 'i ' , [11 , 22 , 34 , 45])
4
5 # Adds an element at index 2
6 a . remove (34)
7 # Prints array ( ' i ', [11 , 22 , 45])
8 print ( a )
4.3 NumPy Module 47

9
10 # Pops the last element 45
11 element = a . pop ()
12 # Prints 45
13 print ( element )
Listing 4.6: Removing items in an array

4.3 NumPy Module


It is a python library which provides a multidimensional array object and a set of operations for these
arrays. These operations include mathematical, logical, shape manipulation, basic linear algebra,
basic statistical operations etc. Numpy includes an ndarray object which encapsulates n-dimensional
arrays of elements of same type and operations on them. Some of the differences between an
ndarray and normal python list are
• Size of an ndarray is fixed at the time of creation. Python lists can grow dynamically.
• All elements of an ndarray are of the same data type, whereas lists can have elements of
different types.
• Numpy arrays have many mathematical and statical operations that can be executed on large
amount of data more efficiently.
Using NumPy, an array is created using the class ndarray. The array class in python’s standard
library can create only one dimensional arrays whereas ndarray can be used to create multi dimen-
sional arrays and it has more functionalities. Each dimension of an ndarray is called an axis. Some
of the attributes of an ndarray object are:
• ndarray.ndim
Returns the number of axes (dimensions) of the array.
• ndarray.shape
Returns the dimension of the array as a tuple, containing integers indicating the size of the
array in each dimension.
• ndarray.size
Returns the total number elements in the array.
• ndarray.dtype
Returns an object representing the type of elements in the array.

4.3.1 Creating Arrays using NumPy


There are different ways to create arrays using NumPy module.

array() Function
The array() function can be used to create arrays from regular python lists or tuples. Type of the
resulting array will be determined based on the type of elements in the sequence. A sequence of
sequence is transformed into a two dimensional array. A sequence of sequence of sequence is
transformed into a three dimensional array and so on.
1 import numpy as np
2 # Creates an ndarray from the list [22 ,33 ,45]
3 a = np . array ([22 , 35 , 45])
4 # Prints [22 35 45]
5 print ( a )
6 # Prints int64
7 print ( a . dtype )
8 # Creates a 2 D array with dimension 2 x 2
9 a = np . array ([[1 ,2] , [3 ,4]])
48 Chapter 4. Numpy Arrays and Data Visualization

10 print ( a ) # Prints [[1 2] [3 4]]


Listing 4.7: Creating an ndarray

4.3.2 zeros(), ones() and empty() Functions


• zeros() function creates an array full of zeros.
• ones() function creates an array full of ones.
• empty() function creates an array whose initial content is random and depends on the state of
the memory.
1 numpy . zeros ( shape , dtype , order )
2 numpy . ones ( shape , dtype = float , order = 'C ')
3 numpy . empty ( shape , dtype = float , order = 'C ')
Listing 4.8: zeros(), ones() and empty() Syntaxes

• shape is an integer or tuple which specifies the number of elements in each dimension.
• dtype is an optional argument which specifies the data type of elements. By default, the dtype
of the created arrays will be float64.
• order is an optional argument which can take up value either 'C' (row-major) or 'F' (column-
major). It specifies how to store the values (row major or column major). By default, the
value will be 'C'.
1 import numpy as np
2
3 print ( " Zeros " )
4 a = np . zeros (5)
5 print ( a ) # Prints [0. 0. 0. 0. 0.]
6 a = np . zeros ((2 ,3) )
7 print ( a )
8 ''' Prints [[0. 0. 0.]
9 [0. 0. 0.]] '''
10
11 print ( " Ones " )
12 a = np . ones (5)
13 print ( a ) # Prints [1. 1. 1. 1. 1.]
14 a = np . ones ((2 ,3) )
15 print ( a )
16 ''' Prints [[1. 1. 1.]
17 [1. 1. 1.]] '''
18
19 print ( " Empty " )
20 a = np . empty (5)
21 print ( a ) # Prints [1. 1. 1. 1. 1.]
22 a = np . empty ((2 ,3) )
23 print ( a )
24 ''' Prints [[1. 1. 1.]
25 [1. 1. 1.]] '''
Listing 4.9: zeros(), ones() and empty() Functions

4.3.3 arange() Function


arange() function returns an array containing evenly spaced values within an interval.
1 numpy . arange ( start , stop , step , dtype )
Listing 4.10: Syntax for arange() Function
4.3 NumPy Module 49

• start is an integer or real number. It is an optional argument. It specifies the start of interval.
The interval includes this value. The default start value is 0.
• stop is an integer or real number. It specifies the end of interval. The interval does not include
this value.
• step is an integer or real number. It is an optional argument. It specifies spacing between
values. The default start value is 1.
• dtype specifies the type of the output array. If dtype is not given, it will infer the data type
from the other input arguments.
1 import numpy as np
2
3 ''' Creates array containing elements within interval 0 ( default )
4 and 5 ( does not include ) . Step is 1 ( default ) '''
5 a = np . arange (5)
6 print ( a ) # Returns [0 1 2 3 4]
7
8
9 ''' Creates array containing elements within interval 4 ( includes )
10 and 10 ( does not include ) . Step is 1 ( default ) '''
11 a = np . arange (4 ,10)
12 print ( a ) # Returns [4 5 6 7 8 9]
13
14 ''' Creates array containing elements within interval 4 ( includes )
15 and 7 ( does not include ) . Step is 0.5 '''
16 a = np . arange (4 ,7 ,0.5)
17 print ( a ) # Returns [4. 4.5 5. 5.5 6. 6.5]
Listing 4.11: Example for arange() Function

4.3.4 linspace() Function


linspace() function returns an array containing a specified number of samples, evenly spaced
within an interval.
1 numpy . linspace ( start , stop , num , endpoint , rettype , dtype )
Listing 4.12: Syntax for linspace() Function

• start is an integer or real number. It specifies the start of interval.


• stop is an integer or real number. It specifies the end of interval unless endpoint is set to
False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples,
so that stop is excluded.
• num is an integer. It is an optional argument. It specifies the number of samples to be generated.
Default value is 50.
• endpoint is an optional boolean value. If True, stop is the last sample. Otherwise, it is not
included. Default is True.
• rettype is an optional boolean value. If True, returns (samples, step), where step is the
spacing between samples.
• dtype is an optional argument which specifies the type of the output array. If dtype is not
given, the data type is inferred from start and stop.
1 a = np . linspace (2 ,6 ,6)
2 print ( a ) # Prints [2. 2.8 3.6 4.4 5.2 6. ]
3
4 a = np . linspace (2 ,6 ,6 , endpoint = False )
5 print ( a ) # Prints [2. 2.66666667 3.33333333 4. 4.66666667 5.33333333]
6
7 (a , step ) = np . linspace (2 ,6 ,6 , retstep = True )
50 Chapter 4. Numpy Arrays and Data Visualization

8 print ( a ) # Prints [2. 2.8 3.6 4.4 5.2 6. ]


9 print ( step ) # Prints 0.8
Listing 4.13: Example for linspace() Function
• Line No. 1: Creates an array containing 6 evenly spaced elements within interval 2 and 6
• Line No. 4: Creates an array containing 6 evenly spaced elements within interval 2 and 6.
Since endpoint is set to False, first it creates 7 evenly spaced elements within interval 2 and
6 and then excludes the last one (6).
• Line No. 7: Creates an array containing 6 evenly spaced elements within interval 2 and 6.
Also returns the value for step.

4.3.5 random() Function


random() function generates random samples within the half-open interval [0.0, 1.0). It returns an
array of specified shape and fills it with random floats.
1 numpy . random . random ( size )
Listing 4.14: Syntax for random() Function
where size is an integer or tuple of integers which specifies the number of elements in each
dimension of the array.
1 import numpy as np
2
3 a = np . random . random (5)
4 print ( a )
5
6 a = np . random . random ((2 ,3) )
7 print ( a )
Listing 4.15: Example for random() Function
• Line No. 3: Creates an array containing 5 random number in the half open interval [0.0,1.0).
• Line No. 6: Creates an array containing 6 random number in the half open interval [0.0,1.0)
and arranges them as a 2 dimensional array (2 × 3).

4.3.6 Indexing, Slicing and Iterating


Indexing
• Indexing a NumPy array means accessing the elements inside the array. Array elements can be
accessed using the [] operator. Index starts at 0.
• Multi dimensional array elements can be accessed using comma separated indices (one for
each dimension) inside [].
• A negative indexing, starting from -1 for the last element of an array can also be used.
1 import numpy as np
2 a = np . array ((11 ,22 ,33 ,44 ,55) )
3 print ( a [1]) # Prints 22
4 a = np . array ((11 ,22 ,33 ,44 ,55) )
5 print ( a [ -1]) # Prints 55
6 a = np . array ((11 ,22 ,33 ,44 ,55) )
7 print ( a [ -2]) # Prints 44
8 # 2 D Array
9 b = np . array (((1 ,2 ,3) ,(4 ,5 ,6) ) )
10 print ( b [1 ,1]) # Prints 5
11 b = np . array (((1 ,2 ,3) ,(4 ,5 ,6) ) )
12 print ( b [1 , -1]) # Prints 6
Listing 4.16: Indexing Example
4.3 NumPy Module 51

Slicing
• Part of an array can be retrieved using a slice instead of index inside [].
• A slice can be specified as [start:end:step].
– start is optional. Default is 0.
– end is optional. Default is the last index of the array.
– step is 1 by default.
• For multi dimensional arrays, slice can be specified in each dimension.
1 import numpy as np
2 # Creates arrray [10 11 12 13 14 15 16 17 18 19]
3 a = np . arange (10 ,20)
4 print ( a [1:7:2]) # Prints [11 13 15]
5 print ( a [:7:2]) # Prints [10 12 14 16]
6 print ( a [:7]) # Prints [10 11 12 13 14 15 16]
7 print ( a [::2]) # Prints [10 12 14 16 18]
8 print ( a [ -4: -1]) # Prints [16 17 18]
9
10 b = np . array ([[1 ,2 ,3 ,4] ,[5 ,6 ,7 ,8] ,[9 ,10 ,11 ,12]])
11 print ( b [1 ,1:3]) # Prints [6 ,7]
12 print ( b [0:2 ,2]) # Prints [3 ,7]
13 print ( b [1:3 ,1:3]) # Prints [[6 ,7] [10 ,11]]
Listing 4.17: Slicing Example

Iterating
• NumPy arrays can be iterated using for loop.
• Nested loops are required for iterating over multi dimensional array.
1 import numpy as np
2 # Creates arrray [10 11 12 13 14 15 16 17 18 19]
3 a = np . arange (10 ,20)
4 # Prints individual elements of the array
5 for e in a :
6 print ( e )
7 # Creating a 2 D Array
8 b = np . array ([[1 ,2 ,3] ,[4 ,5 ,6] ,[7 ,8 ,9]])
9 # Prints each row
10 for r in b :
11 print ( e )
12 # Prints individual elements
13 for r in b :
14 # For each element in the row
15 for e in r :
16 print ( e )
Listing 4.18: Iteration Example

• NumPy package contains an iterator object nditer, which allows to perform advanced iterations
on NumPy arrays.
• nditer allows to visit each element of an array regardless of number of dimensions of the
array.
1 import numpy as np
2 # Creating a 2 D Array
3 b = np . array ([[1 ,2 ,3] ,[4 ,5 ,6] ,[7 ,8 ,9]])
4 # Prints each element
5 for e in np . nditer ( b ) :
6 print (e , end = ' ') # Prints 1 2 3 4 5 6 7 8 9
Listing 4.19: Iteration using nditer
52 Chapter 4. Numpy Arrays and Data Visualization

• The order argument of nditer function can be used to specify the order in which the elements
are to be iterated. The default value for order argument is 'K' which the order of elements in
memory. This can be overridden with order='C' for C order (row major) and order='F' for
Fortran order (column major).
1 import numpy as np
2
3 # Creating a 2 D Array
4 b = np . array ([[1 ,2 ,3] ,[4 ,5 ,6] ,[7 ,8 ,9]])
5
6 # Prints each element in the order in memory
7 for e in np . nditer (b , order = 'K ') :
8 print (e , end = ' ') # Prints 1 2 3 4 5 6 7 8 9
9 print ()
10
11 # Prints each element in row major order
12 for e in np . nditer (b , order = 'C ') :
13 print (e , end = ' ') # Prints 1 2 3 4 5 6 7 8 9
14 print ()
15
16 # Prints each element in column major order
17 for e in np . nditer (b , order = 'F ') :
18 print (e , end = ' ') # Prints 1 4 7 2 5 8 3 6 9
19

Listing 4.20: Changing order of iteration using order argument

4.3.7 Copying Arrays


copy method can be used to create a copy of an ndarray.
1 numpy . copy (a , order )

• a is the array whose elements are to be copied.


• order is an optional argument which specifies the order in which the elements are to be
copied. For example, 'C' for row major, 'F' for column major.
1 import numpy as np
2
3 a = np . arange (10)
4 print ( a ) # Prints [0 1 2 3 4 5 6 7 8 9]
5
6 b = a
7 c = np . copy ( a )
8
9 a [1]=11
10
11 print ( a ) # Prints [0 11 2 3 4 5 6 7 8 9]
12 print ( b ) # Prints [0 11 2 3 4 5 6 7 8 9]
13 print ( c ) # Prints [0 1 2 3 4 5 6 7 8 9]
Listing 4.21: Copying an array using copy

• In line no. 6, a is assigned to b. Hence both will be representing the same object. Changing
an element in a will be reflected in b.
• In line no. 7, copy function, returns a new array containing all the elements of a and this new
array is assigned to c. Hence changes made to a will not be reflected in c.

4.3.8 Splitting Arrays


The split function splits an array into multiple sub-arrays and returns a list of these sub-arrays.
4.3 NumPy Module 53

1 numpy . split (a , indices_or_sections , axis )

• a is the array to be divided in to sub arrays.


• If indices_or_sections is an integer, N, the array will be divided into N equal arrays along
axis. If such a split is not possible, an error is raised.
• If indices_or_sections is a 1-D array of sorted integers, the entries indicate where along axis
the array is split.
• axis is optional integer which specifies the axis along which the array is to be split. Default
value for axis is 0.
1 import numpy as np
2
3 a = np . arange (8)
4 splits = np . split (a ,4)
5 print ( splits )
6 # Prints [ array ([0 , 1]) , array ([2 , 3]) , array ([4 , 5]) , array ([6 , 7]) ]
7 splits = np . split (a ,[2 ,4])
8 print ( splits )
9 # Prints [ array ([0 , 1]) , array ([2 , 3]) , array ([4 , 5 , 6 , 7]) ]
10 b = np . array ([[1 ,2 ,3] ,[4 ,5 ,6] ,[7 ,8 ,9] ,[10 ,11 ,12]])
11 splits = np . split (b ,2)
12 print ( splits )
13 # Prints [ array ([[1 , 2 , 3] ,
14 # [4 , 5 , 6]]) , array ([[ 7 , 8 , 9] ,
15 # [10 , 11 , 12]]) ]
Listing 4.22: Splitting an array using split() Function

• Line No. 4: Splits the array in to 4 equal sized sub arrays


• Line No. 7: Splits the array into 3 sub arrays. First sub array consists of elements from index
0 to 1. Second sub array consists of elements from index 2 to 4 (not including 4). Third sub
array consists of remaining elements.
• Line No. 11: Splits the 2 dimensional array into 2 sub arrays. Each sub array is a two
dimensional array.

4.3.9 Shape Manipulation


reshape() Function
The reshape() functions is used to change the shape of an array without changing its data and size.
It returns the new array.
1 numpy . reshape (a , newshape , order )

• a is the array to be reshaped.


• newshape is an integer or tuple of integers.The new shape should be compatible with the
original shape. If shape is an integer, then the result will be a 1-Dimensional array of that
length.
• order is an optional argument which specifies the order in which elements of the array a
should be read while reshaping. For example, order can be 'C' for row major and 'F' for
column major.
1 import numpy as np
2 # Creates array [0 1 2 3 4 5]
3 a = np . arange (6)
4 print ( a ) # Prints [0 1 2 3 4 5]
5 new_a = np . reshape (a ,(2 ,3) )
6 print ( new_a )
7 # 2 D Array
8 b = np . array ([[1 ,2 ,3] ,[4 ,5 ,6]])
54 Chapter 4. Numpy Arrays and Data Visualization

9 new_b = np . reshape (b ,6)


10 print ( new_b ) # Prints [1 2 3 4 5 6]
Listing 4.23: Reshaping an array using reshape() Function
• Line No. 5: Reshapes the 1D array to a to 2D array with 2 rows and 3 columns.
• Line No. 9: Reshapes the 2D array to a 1D array with 6 elements.

4.3.10 Transposing an Array


The transpose() functions is used to permute the axes of an array. It returns the modified array.
1 numpy . transpose (a , axes )

• a is the array to be transposed.


• axes is an tuple or list integers. If specified, it must be a tuple or list which contains a
permutation of [0,1,..,N-1] where N is the number of axes of a. The ith axis of the returned
array will correspond to the axis numbered axes[i] of the input. If not specified, it reverses
the order of the axes.
1 import numpy as np
2
3 # Creates a 2 D array with 2 rows and 3 columns
4 a = np . arange (6) . reshape ((2 ,3) )
5 print ( a )
6
7 # Transpose of a will have 3 rows and 2 columns
8 b = np . transpose ( a )
9 print ( b )
Listing 4.24: Reshaping an array using reshape() Function
• Line No. 5 prints the following
1 [[0 1 2]
2 [3 4 5]]

• Line No. 9 prints the following


1 [[0 3]
2 [1 4]
3 [2 5]]

4.3.11 Resizing an Array


The resize() function is used to return a new array with the specified shape.
1 numpy . resize (a , new_shape )

• a is the array to be resized.


• shape is an integer or tuple of integers. If the new array is larger than the original array, then
the new array is filled with repeated copies of a.
1 import numpy as np
2
3 # Creates a 2 D array with 2 rows and 3 columns
4 a = np . arange (6) . reshape ((2 ,3) )
5 print ( a )
6
7 # Resize the array a with 3 rows and 4 columns
8 b = np . resize (a ,(3 ,4) )
9 print ( b )
Listing 4.25: Resizing an array using resize() Function
4.3 NumPy Module 55

• Line No. 9 prints the following


1 [[0 1 2 3]
2 [4 5 0 1]
3 [2 3 4 5]]

Using resize method of ndarray object


The resize() method of an ndarray object resizes an array in to specified shape. If the new size is
larger than the original array, then the new array is filled with zeros.
1 ndarray . resize ( new_shape )

1 import numpy as np
2
3 a = np . array ([[1 ,2 ,3] ,[4 ,5 ,6]])
4 print ( a )
5
6 # Resize the array a with 3 rows and 4 columns
7 a . resize (3 ,4)
8 print ( a )
Listing 4.26: Resizing an array using ndarray.resize() Method

• Line No. 8 prints the following


1 [[1 2 3 4]
2 [5 6 0 0]
3 [0 0 0 0]]

4.3.12 Arithmetic Operations on Arrays


Arithmetic operations on arrays can be performed using some mathematical functions or operators.
For performing arithmetic operations, the arrays must of compatible size.
• add() function can be used to add two arrays element wise. The + operator can be used as a
shorthand for np.add on ndarrays.
• subtract() function can be used to subtract one array from the other element wise. The -
operator can be used as a shorthand for np.subtract on ndarrays.
• multiply() function can be used to add multiply arrays element wise. The * operator can be
used as a shorthand for np.multiply on ndarrays.
• divide() function can be used to add divide arrays element wise. The / operator can be used
as a shorthand for np.divide on ndarrays.
1 import numpy as np
2
3 a = np . array ([[1 ,2 ,3] ,[4 ,5 ,6]])
4 b = np . array ([[11 ,12 ,33] ,[44 ,55 ,66]])
5 # Element wise addition using add function
6 print ( np . add (a , b ) )
7 # Element wise addition using + operator
8 print ( a + b )
9 # Element wise subtraction using subtract function
10 print ( np . subtract (a , b ) )
11 # Element wise subtraction using - operator
12 print (a - b )
13 # Element wise multiplcation using multiply function
14 print ( np . multiply (a , b ) )
15 # Element wise multiplcation using * operator
16 print ( a * b )
17 # Element wise division using divide function
18 print ( np . divide (b , a ) )
56 Chapter 4. Numpy Arrays and Data Visualization

19 # Element wise division using / operator


20 print ( b / a )

Matrix Multiplication using dot Function and @ Operator


dot() function or @ operator can be used to perform matrix multiplication.
1 import numpy as np
2
3 a = np . array ([[1 ,2 ,3] ,[4 ,5 ,6]])
4 b = np . array ([[1 ,2] ,[3 ,4] ,[5 ,6]])
5
6 # Matrix multiplication using dot function
7 c = np . dot (a , b )
8 print ( c )
9
10 # Matrix multiplication using @ operator
11 d = a @ b
12 print ( d )

4.4 Matplotlib
• Matplotlib is a comprehensive library for creating static, animated, and interactive visualiza-
tions in Python.
• Using matplotlib, we can
– Develop publication quality plots with just a few lines of code
– Customize the plots
– Export the plots to different file formats

4.5 Pyplot
matplotlib.pyplot is a collection of command style functions. Each of the functions in pyplot
makes some change to a figure such as
• creating a figure
• creating a plotting area in a figure
• plotting some lines in a plotting area
• decorating the plot with labels.

4.5.1 plot() Function


plot() function in matplotlib is used to plot y versus x as lines and/or markers.
1 plot (x , y , format , kwargs )

• x represents a sequence (tuple, list etc.) of x values for the plot. It is optional. Default is
range(len(y)).
• y represents a sequence (tuple, list etc.) of y values for the plot.
• format is an optional string used for defining basic formatting like color, marker and linestyle.
Format string consists of a part of color, marker and line. Syntax for format string is
format = '[marker][line][color]'.
Each of them is optional. Some examples for marker, line and color are given below.
4.5 Pyplot 57
Colors
Markers
Line Styles Character Description
Character Description
Character Description b Blue
. Point
- Solid g Green
, Pixel
-- Dashed r Red
o Circle
-. Dash-dot y Yellow
+ Plus
: Dotted k Black
x x
w White
• kwargs are used to specify line properties some of which are given below.

Property Description
label Sets a label that will be displayed in the legend.
linewidth Sets the line width in points.
color Sets the color for the line.

• pyplot.show() method can be used to display the plot.


1 import matplotlib . pyplot as plt
2
3 # Values for x - axis
4 overs = list ( range (1 ,21) )
5
6 # Values for y - axis
7 runs = [10 ,16 ,22 ,35 ,40 ,48 ,52 ,62 ,75 ,91 ,
8 110 ,121 ,127 ,135 ,142 ,150 ,161 ,175 ,190 ,201]
9
10 # Plotting overs vs runs without format string
11 plt . plot ( overs , runs )
12
13 # Plotting overs vs runs using format string
14 plt . plot ( overs , runs , 'o - b ')
Listing 4.27: Example for plot() function

(a) Scoring rate without using format string (b) Scoring rate using format string

Figure 4.1: Output of Listing 4.27

4.5.2 Formatting Plots


There are many functions or commands in matplotlib library which can be used to format the plots
created using plot() function.
• xlabel() and ylabel() functions are used to give labels for x axis and y axis respectively.
• text() is used to add a text in arbitrary location. Its syntax is
1 matplotlib . pyplot . text (x , y , s )

– x and y are the coordinates of the point where the text is to be added.
58 Chapter 4. Numpy Arrays and Data Visualization

– s is a string that specifies the text to be added.


• title() is used to set title for the plot.
• xticks() is used to set tick locations and labels of the x-axis.
• legend() is used to set legends for the plot.
• grid() is used to display grid lines.
1 import matplotlib . pyplot as plt
2
3 # Values for x - axis
4 overs = list ( range (1 ,21) )
5
6 # Score of Team A after each over
7 a_runs = [10 ,16 ,22 ,35 ,40 ,48 ,52 ,62 ,75 ,91 ,110 ,
8 121 ,127 ,135 ,142 ,150 ,161 ,175 ,190 ,201]
9
10 # Score of Team B after each over
11 b_runs = [6 ,12 ,20 ,30 ,35 ,49 ,65 ,72 ,86 ,99 ,112 ,
12 129 ,140 ,151 ,158 ,165 ,178 ,185 ,195 ,203]
13
14 # Spcify the tick location for x axis as each over
15 plt . xticks ( overs )
16 # Setting label for x axis
17 plt . xlabel ( " Overs " )
18 # Setting label for y axis
19 plt . ylabel ( " Runs " )
20 # Setting title for the plot
21 plt . title ( " Over by Over Comparison " )
22 # Setting an arbitrary text
23 plt . text (12 ,50 , " Team A Vs Team B " )
24 # Turning on grid lines
25 plt . grid ()
26
27 plt . plot ( overs , a_runs , 'o - g ' , label = " Team A " )
28 plt . plot ( overs , b_runs , 'o - b ' , label = " Team B " )
29
30 # Show legend
31 plt . legend ()
Listing 4.28: Formatting plot

Figure 4.2: Output of Listing 4.28

4.5.3 Bar Charts


The bar() function can be used to draw bar plots. Basic syntax for bar() function is
4.5 Pyplot 59

1 matplotlib . pyplot . bar (x , height , width , color )

• x is the x coordinates for the bars.


• height specifies the height of the bars.
• width specifies the width of the bars.
• color specifies the color of the bars.
1 import matplotlib . pyplot as plt
2 # Values for x - axis
3 overs = list ( range (1 ,21) )
4 # Score of Team A in each over
5 a_runs = [10 ,9 ,8 ,11 ,5 ,7 ,8 ,11 ,15 ,10 ,
6 5 ,12 ,4 ,3 ,2 ,10 ,7 ,12 ,15 ,12]
7
8 # Spcify the tick location for x axis as each over
9 plt . xticks ( overs )
10 # Setting label for x axis
11 plt . xlabel ( " Overs " )
12 # Setting label for y axis
13 plt . ylabel ( " Runs / Over " )
14 # Setting title for the plot
15 plt . title ( " Runs Per Over " )
16
17 plt . bar ( overs , a_runs , label = " Team A " , width =0.5)
18 # Show legend
19 plt . legend ()
Listing 4.29: Example for bar plot

Figure 4.3: Output of Listing 4.33

When two bar plots are to be simultaneously displayed, the x-axis values for each of them
should be adjusted with offsets so that all the bar charts are visible. An example is given below.
1 import matplotlib . pyplot as plt
2 import numpy as np
3 # Values for x - axis .
4 # Using Numpy array to subtract the offset from x values easily
5 overs = np . arange (1 ,21)
6 width = 0.125
7
8 # Score of Team A in each over
9 a_runs = [10 ,9 ,8 ,11 ,5 ,7 ,8 ,11 ,15 ,10 ,
10 5 ,12 ,4 ,3 ,2 ,10 ,7 ,12 ,15 ,12]
11 # Score of Team B in each over
12 b_runs = [9 ,8 ,7 ,12 ,4 ,3 ,2 ,15 ,10 ,9 ,
13 4 ,3 ,2 ,9 ,12 ,11 ,17 ,10 ,11 ,14]
14
60 Chapter 4. Numpy Arrays and Data Visualization

15 # Spcify the tick location for x axis as each over


16 plt . xticks ( overs )
17 # Setting label for x axis
18 plt . xlabel ( " Overs " )
19 # Setting label for y axis
20 plt . ylabel ( " Runs " )
21 # Setting title for the plot
22 plt . title ( " Over by Over Comparison " )
23
24 plt . bar ( overs + width , a_runs , label = " Team A " , width =0.25)
25 plt . bar ( overs - width , b_runs , label = " Team B " , width =0.25)
26 # Show legend
27 plt . legend ()

Listing 4.30: Example for bar plot

Figure 4.4: Output of Listing 4.34

4.5.4 Histograms

hist() function is used to plot a histogram. This functions can take many parameters. Basic syntax
is as follows

1 pyplot . hist (x , bins , edgecolor )

• x is the data values.


• bins is optional which specifies the the numbers of equal bins in the histogram. This can be
either an integer or list of values. If it is an integer (n), the x values will be divided in to n
equal bins. If it is a list, then x values will divided as per the list.
• edgecolor is optional which specifies the color for edges of the bins.

1 import matplotlib . pyplot as plt


2 import math
3
4 weights = [52 ,52 ,52 ,54 ,54 ,53.5 ,54.5 ,55 ,55 ,55 ,55 ,55 ,57 ,57 ,57]
5 weight_bins = [51 ,53 ,55 ,57]
6
7 plt . hist ( weights , bins = weight_bins , edgecolor = ' black ')

Listing 4.31: Example for Histogram


4.5 Pyplot 61

Figure 4.5: Output of Listing 4.31

4.5.5 Scatter Plots


scatter() function can be user to draw a scatter plot. It plots one dot for each observation. Basic
syntax for scatter() function is,
1 scatter (x ,y , color , size )

• x and y are values for x and y axes respectively.


• color is an optional argument which can be used to specify the color of the markers.
• size is an optional argument which can be used to specify the size of the markers.
1 import matplotlib . pyplot as plt
2 import math
3
4 # Marks in Physics and Mathematics for School A
5 phy = [98 ,95 ,85 ,99 ,70 ,82 ,88 ,77 ,88 ,85 ,87]
6 mat = [100 ,90 ,88 ,92 ,60 ,78 ,90 ,72 ,80 ,82 ,83]
7
8
9 # Marks in Physics and Mathematics for School B
10 phy2 = [78 ,75 ,95 ,69 ,60 ,92 ,58 ,47 ,71 ,72 ,88]
11 mat2 = [70 ,90 ,88 ,62 ,50 ,88 ,40 ,72 ,66 ,82 ,81]
12
13
14 plt . xlabel ( ' Physics Marks ')
15 plt . ylabel ( ' Mathematics Marks ')
16
17 plt . scatter ( phy , mat , s =10 , color = ' blue ' , label = ' School A ')
18 plt . scatter ( phy2 , mat2 , s =10 , color = ' green ' , label = ' School B ')
19
20 plt . legend ()
Listing 4.32: Example for scatter plot

Figure 4.6: Output of Listing 4.32


62 Chapter 4. Numpy Arrays and Data Visualization

4.5.6 Figure and Subplots


A figure can be considered as the container for holding plots. A figure can contain multiple plots
and each of them is called a subplot.
• A figure can be created using the figure() function. Basic syntax for figure() function is
1 figure ( figsize , dpi , facecolor , edgecolor )

– figsize sets the height and width of the figure in inches.


– dpi sets the resolution of the figure in dots per inch (dpi). Default is 100dpi.
– facecolor sets the background color.
– edgecolor sets the border color.
• After creating a figure, subplots can be added to the figure using add_subplot() method of
figure object. This method returns an axes object.
• In each plot, the region of the image with the data space is called an axes object.
• An axes object has methods to format plots
– set_xlabel() sets the label for x axis
– set_ylabel() sets the label for y axis
– set_title() sets the title for the plot
– legend() shows the legend
• An axes object has methods to draw plots
– plot() to plot a y versus x as lines and/or markers
– bar() to make bar plot
– scatter() to make scatter plot
• A figure can be exported and saved to a file with specified name using the savefig(filename)
method of the figure object.
1 import matplotlib . pyplot as plt
2 import numpy as np
3
4 # Values for x - axis
5 overs = np . arange (1 ,21)
6 width = 0.125
7 # Score of Team A in each over
8 a_runs = [10 ,9 ,8 ,11 ,5 ,7 ,8 ,11 ,15 ,10 ,
9 5 ,12 ,4 ,3 ,2 ,10 ,7 ,12 ,15 ,12]
10 # Score of Team B in each over
11 b_runs = [9 ,8 ,7 ,12 ,4 ,3 ,2 ,15 ,10 ,9 ,
12 4 ,3 ,2 ,9 ,12 ,11 ,17 ,10 ,11 ,14]
13
14 fig = plt . figure ( dpi =300)
15 axes = fig . add_subplot ()
16
17 # Spcify the tick location for x axis as each over
18 axes . set_xticks ( overs )
19 # Setting label for x axis
20 axes . set_xlabel ( " Overs " )
21 # Setting label for y axis
22 axes . set_ylabel ( " Runs " )
23 # Setting title for the plot
24 axes . set_title ( " Over by Over Comparison " )
25
26 axes . bar ( overs + width , a_runs , label = " Team A " , width =0.25)
27 axes . bar ( overs - width , b_runs , label = " Team B " , width =0.25)
28 axes . legend ()
29
30 fig . savefig ( ' runsperover . png ')
Listing 4.33: Creating figures and subplots
4.5 Pyplot 63

Output of this program will be as in Figure 4.4.


• More subplots can be added to a figure using the subplots() function.

1 subplots ( nrows , ncols )

– rows and cols specifies the number of rows and columns of the subplot grid.
• The subplots() method returns a figure object and a tuple containing axes objects. The
numbers of axes objects will be equal to nrows× ncols. Each axes object is accessible by its
index.

1 import matplotlib . pyplot as plt


2 import numpy as np
3
4 # Values for x - axis
5 overs = np . arange (1 ,11)
6 width = 0.125
7 # Score of Team A in each over
8 a_runs = [10 ,9 ,8 ,11 ,5 ,7 ,8 ,11 ,15 ,10]
9 # Score of Team B in each over
10 b_runs = [9 ,8 ,7 ,12 ,4 ,3 ,2 ,15 ,10 ,9]
11
12 # Score of Team A after each over
13 a_runs2 = [10 ,16 ,22 ,35 ,40 ,48 ,52 ,66 ,75 ,91]
14 # Score of Team B after each over
15 b_runs2 = [6 ,12 ,20 ,30 ,35 ,49 ,65 ,72 ,86 ,99]
16
17 # Creating subplot grid with 1 row and 2 columns
18 fig , axes = plt . subplots (1 ,2)
19
20 # Spcify the tick location for x axis as each over
21 axes [0]. set_xticks ( overs )
22 # Setting label for x axis
23 axes [0]. set_xlabel ( " Overs " )
24 # Setting label for y axis
25 axes [0]. set_ylabel ( " Runs " )
26 # Setting title for the plot
27 axes [0]. set_title ( " Over by Over Comparison " )
28 axes [0]. bar ( overs + width , a_runs , label = " Team A " , width =0.25)
29 axes [0]. bar ( overs - width , b_runs , label = " Team B " , width =0.25)
30 axes [0]. legend ()
31
32 # Spcify the tick location for x axis as each over
33 axes [1]. set_xticks ( overs )
34 # Setting label for x axis
35 axes [1]. set_xlabel ( " Overs " )
36 # Setting label for y axis
37 axes [1]. set_ylabel ( " Runs " )
38 # Setting title for the plot
39 axes [1]. set_title ( " Runs Progression " )
40 axes [1]. plot ( overs , a_runs2 , 'o - g ' , label = " Team A " )
41 axes [1]. plot ( overs , b_runs2 , 'o - b ' , label = " Team B " )
42 # Show legend
43 axes [1]. legend ()
44
45 fig . set_size_inches (18.5 , 10.5)
46 fig . savefig ( ' runsperover . png ')

Listing 4.34: Creating multiple subplots


64 Chapter 4. Numpy Arrays and Data Visualization

Figure 4.7: Output of Listing 4.34

4.5.7 Plotting sinx


1 import matplotlib . pyplot as plt
2 import numpy as np
3 import math
4
5 angles_degrees = np . arange (1 ,361)
6 angles_radians = list ( map ( math . radians , angles_degrees ) )
7 sins = list ( map ( math . sin , angles_radians ) )
8
9 plt . title ( " Sin X Plot " )
10 plt . xlabel ( " Angle ( X ) " )
11 plt . ylabel ( " Sin X " )
12 plt . plot ( angles_degrees , sins )
Listing 4.35: Sin x Plot

Figure 4.8: Output of Listing 4.35

4.5.8 Plotting x2
1 import matplotlib . pyplot as plt
2 import numpy as np
3
4.5 Pyplot 65

4 x = np . arange ( -99 ,100)


5 x2 = x **2
6
7 plt . title ( " $X ^2 $ Plot " )
8 plt . xlabel ( " x " )
9 plt . ylabel ( " $x ^2 $ " )
10 plt . plot (x , x2 )
Listing 4.36: Sin x Plot

Figure 4.9: Output of Listing 4.36


Bibliography

URLs
[1] https://www.geeksforgeeks.org/python- programming- language/. [Online; ac-
cessed 30-March-2021].
[2] https://docs.python.org/3/. [Online; accessed 30-March-2021].
[3] https://www.youtube.com/watch?v=YYXdXT2l-Gg&list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7.
[Online; accessed 30-March-2021].
[4] https://www.tutorialspoint.com/python/index.htm. [Online; accessed 30-March-
2021].
[5] https://numpy.org/devdocs/user/quickstart.html. [Online; accessed 30-March-
2021].
[6] https : / / matplotlib . org / stable / tutorials / index . html. [Online; accessed 30-
March-2021].

Books
[7] J.V. Guttag. Introduction to Computation and Programming Using Python. PHI Learning,
2014. ISBN: 9788120348660.

You might also like