Introduction To Python
Introduction To Python
Introduction To Python
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
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
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.
Versions of Python
There are 2 series of python versions available now. Python 2 series and Python 3 series.
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
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 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.
• 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
• 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 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 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 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 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 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
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
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
Code
Code
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
Code
False
Condition
True
Loop Body Code
This example prints the multiplication table for a number from 1 to 10.
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.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
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
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.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
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
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.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
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
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
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).
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
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
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)!
1! = 1 (Base case)
Therefore
n! = n ∗ (n − 1)!
(n − 1)! = (n − 1) ∗ (n − 2)!
(n − 2)! = (n − 2) ∗ (n − 3)!
..
2! = 2 ∗ 1!
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
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.
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
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
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.
Constant Description
math.pi Value of π = 3.141592...
math.e Value of e = 2.718281...
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
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.
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.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
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
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
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.
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
• 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
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.
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
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
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
• 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
• 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
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
• 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.
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
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.
• 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.
(a) Scoring rate without using format string (b) Scoring rate using format string
– x and y are the coordinates of the point where the text is to be added.
58 Chapter 4. Numpy Arrays and Data Visualization
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
4.5.4 Histograms
hist() function is used to plot a histogram. This functions can take many parameters. Basic syntax
is as follows
– 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.
4.5.8 Plotting x2
1 import matplotlib . pyplot as plt
2 import numpy as np
3
4.5 Pyplot 65
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.