Python Programing
Python Programing
MASTER OF SCIENCE
(COMPUTER SCIENCE)
PYTHON PROGRAMMING
SYLLABUS
COURSE OBJECTIVES:
COURSE OUTCOMES :
UNIT II: DATA TYPES IN PYTHON Lists, Tuples, Sets, Strings, Dictionary Modules :
Module Loading and Execution – Packages – Making your Own Module – The
Python Standard Libraries.
UNIT III: FILE HANDLING AND EXCEPTION HANDLING Files : Introduction – File
Path – Opening and Closing files – Reading and Writing files – File Position –
Exception : Errors and Exceptions, Exception Handling, Multiple Exceptions.
UNIT IV: MODULES, PACKAGES Modules : Introduction – Module Loading and Execution
– Packages – Making Your Own Module – The Python Standard Libraries for data
processing, data mining, and visualization – NUMPY, Pandas, Matplotlib, Plotly
TOTAL : 45 PERIODS
3
REFERENCES:
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, Second
Edition, Shroff,O’Reilly Publishers, 2016(http://greenteapress.com/wp/thinkpython/)
3. Guido van Rossum, Fred L. Darke Jr., “An Introduction to Python – Revised and Updated
for Python 3.2, Network Theory Ltd., First Edition, 2011
5. Charles Dierbach, “Introduction to Cmputer Science using Python”, Wiley India Edition,
First Edition, 2011
6. Timothy A. Budd, “Exploring Python”, Mc-Graw Hill Education (India) Private Ltd., First
edition, 2011
4
PYTHON PROGRAMMING
SCHEME OF LESSON
5
UNIT – 1
PYTHON BASIS
CONTENTS:
LEARNING OBJECTIVES
1.1 Introducing to python programming
1.2 Python Interpreter and Interactive mode
Interactive Shell
Execution of python program
Output and Input Statements
1.3 Variables and Identifiers
Correct Usage of Variables
Incorrect Usage of Variables
1.4 Arithmetic Operators
1.5 Boolean Expressions and Operations
Relational Operators
Membership Operators
Boolean Operators
1.6 Types and Values
1.7 Control Statements (Conditionals)
If – else Statements
Interactive Control – Loops
Break and Continue Statements
Function
Recursive Functions
Worked out Programming Problems
Learning Outcomes
Chapter Exercise
References
6
UNIT - 1
PYTHON BASICS
Learning Objectives
• Introduce the basics of Python Programming
• Familiarize with the syntax of Python programming
• Solve simple problems with Python programming
Why python?
The name python comes from the 1970s British comedy series Monty Python’s Flying
Circus.
7
Figure 1.1: Python Shell
Interactive Shell
One of the basic features in Python is the interactive shell, that comes with IDLE
environment. You can interactively work with code and see instant output through interactive
shell. Example of this shell is shown in Figure 1.1.
The shell can be used as a calculator. Try out these in your shell.
\ texttt{
>>> 75 * 4 \\
300\\
>>> " hello" \\
’ hello’\\
>>> " hello" + " world"\\
’ helloworld’\\
>>> \\
}
The first line multiplies 75*4 with the output as 300. “+” concatenates the two strings “hello”
and “world” to give the output as ’hello world’.
visible in the IDLE python interactive shell. Alternately, any python program can be executed
from the terminal by entering the command python3 <filename.py> from the directory
where the file is residing. For this example, the command is python3 hello.py.
Nowadays, python version used by default is 3 and above. So, python3 is used. If python 2.7
is used, 3 can be dropped
>>> x = 100
>>> num2 = 200
>>> x+num2
300
>>> y = " hello"
>>> Cap = " WORLD"
>>> y+Cap
’ helloWORLD’
Here, the variables are “x, num2, y and Cap”. 100 is assigned to ‘x’ and 200 to num2. Adding
the variables gives the result of 300. The string of “hello” is assigned to ’y’ and “WORLD” to
‘Cap’.
A few more examples are shown below.
example1 = 10
example_1 = 10
_example1 = 10
ex_ample = 10
Xample = 10
eXamPLe = 10
example_ = 10
_example_= 10
10
Now that some value is assigned to a variable, what really happens in the machine
when we assign a value to the variable?
Python is an object oriented language (you will see more details of it in Chapter 5) and
all values are objects itself. When you create a variable say n=67, an integer object of
67 is created and then assigned to n. In other words, n points to the value of 67. Now
consider these two lines.
1. n = 67
2. m = n
The first line indicates n pointing to 67. The second line has two variables m and n, with
m assigning to the variable n, which itself is a variable. Here, there are not two objects
created, but the variable m points to the value of n, which is equal to 67 as shown below.
n 67
Note: Variables should be readable. Do not give any names that are bizarre and irrelevant.
11
Arithmetic Operators and Precedence
The standard mathematical operations of addition, subtraction, multiplication and division are
supported in python. In addition, the truncated division, modulo and exponential are well
supported. While all these operations are binary, the unary operator of negation (negative of
a positive value) is also included. The symbols are shown in Table 1.1. Examples are shown
1. 6−4+2
2. 8**2 −5*3+4
3. −10*5
4. 4+6 ** 6//2
5. 10 ** 6//2
6. (2 ** 3) ** 3+5//2 −1
Relational Operators
The relational operators compare two objects. These are given in Table 1.2. Numerical com-
parison is straight forward. But when characters and strings are used, the alphabetical order is
used to compare. For example, since the character of b comes before d, we can write in python
as ‘‘b’’<‘‘d’’> or ‘‘cat’’<‘‘dog’’. Here, the first letter of c is before d and therefore
evaluates to True value.
Table 1.2: Relational Operators
Examples employing these operators are given below. Practice these in your shell.
>>> a = 5
>>> b = 6
>>> a == b
False
>>> a<b
True
>>> a<=b
True
>>> b>a
13
True
>>> b>=a
True
>>> a!=b
True
>>> " cat" == " cat"
True
>>> " cat" != " dog"
True
>>> " cat" < " dog"
True
Membership Operators
Python provides an elegant method to determine whether a member is in the set of values
using keyword in and not in. For example, take the even integers less than 10. This can be
represented as a list [0, 2, 4, 6, and 8]. To check whether 2 and 5 are in this list, you can
use thesekeywords as shown below.
>>> even = [0 ,2 ,4 ,6 ,8]
>>> 2 in even
True
>>> 5 not in even
True
>>> 5 in even
False
>>> 2 not in even
False
>>> 100 in even
False
Boolean Operators
The operators of not, and and or can be used in Python. The evaluation of these operators are:
True and True = True
True and False = False
False and False = False
True or True = True
True or False = True
False or False = False
not True = False
not False = True
A few examples are shown below. Practice all types of combinations similar to these.
>>> True and False
False
>>> True or False
True
14
>>> not False
True
>>> (5 <10) and (100 >6)
True
>>> (’cat’<’dog’) and (’dog’ < ’ zebra’)
True
>>> not ((’cat’<’dog’) and (’dog’ < ’ zebra’))
False
As a human you know that the text cannot be divided. But how does a machine know? To
encounter these types of problems, data types are used. For the above codes, ‘text1’ is a string
type variable - anything that is within quotation is string. This cannot be divided by two, which
throws an error as:
TypeError: unsupported operand type(s) for /: ’str’and ’int’.
By default python understands the variable as integer and float. For example, if you assign
the variable as n = 10, ‘n’ is assigned with the integer value of 10. If you assign n=10.0, ‘n’ is
assigned with the decimal value of 10.0. You need not declare explicitly as integer and float. If
you assign n=‘‘10’’, then n is considered as string. In this case, arithmetic operations cannot
be performed. To find out the datatype of the value, ’type’ is used. Try these in your python
shell and check for yourself.
>>> n = 10
>>> type(n)
<class ’int’>
>>> n=10.0
>>> type(n)
<class ’ float’>
>>> n="10"
>>> type(n)
<class ’str’>
>>> n/2
Traceback ( most recent call last):
File "<pyshell#9>", line 1, in <module >
15
n/2
TypeError: unsupported operand type(s) for /: ’str’ and ’int’
>>>
Data types can be converted from one form to another. For example, an integer can be
converted to float or vice-versa. Consider the following piece of code. Here, ‘n’ is assigned
an integer value of 15, then ‘m’ is assigned to the float value of ‘n’, which gives the output of
15.0. Here, integer is converted to float.
>>> n = 15
>>> type(n)
<class ’int’>
>>> m = float(n)
>>> m
15.0
>>> type(m)
<class ’ float’>
>>>
Now, consider the following code. Here, ‘n’ is assigned with a value of 15.8, which is of
float type. On conversion to integer as assigned in the variable ‘m’, the value is 15. When you
convert float to integer, the decimal values are ignored.
>>> n = 15.8
>>> type(n)
<class ’ float’>
>>> m = int(n)
>>> m
15
If you want to round off the value to the next integer, you have to use the keyword of round.
For example, to round off the value of n = 15.82 to the nearest integer, use int(round(n,0)).
Here, 0 indicates the number of places to be rounded and ‘int; indicates the conversion of float
to integer type.
The conversion of integer to string and string to integer can be done in a similar manner.
The following example illustrates the use of conversion from integer to string and string to float
value.
Integer to String conversion
>>> m = 15
>>> type(m)
<class ’int’>
>>> n = str(m)
>>> type(n)
<class ’str’>
String to float (Note here that there is an error when converting a string value of 15.2 to inte-
ger).
>>> n = " 15.2 "
>>> type(n)
<class ’str’>
16
>>> m = int(n)
Traceback ( most recent call last):
File "<pyshell#12 >", line 1, in <module >
m = int(n)
ValueError: invalid literal for int() with base 10: ’15.2 ’
>>> m = float(n)
>>> m
15.2
Note: When you are working with control statements and functions, be careful about inden-
tation (spaces) in python.
If - else statements
If statement is a decision control statement based on the value of some arithmetic or boolean
expressions. The syntax is given by:
if ( expression):
block 1
block 2
else:
block 3
block 4
The expression should be within simple brackets and with the indentation space, the appro-
priate statements are written. Example: Assume you have a class at 8.30 a.m. on mondays,
wednesdays and fridays. Write a program to check whether there is a class at 8.30 a.m. on any
particular day.
day = input(" Enter the day as mon, tues , wed, thurs , fri,
sat, sun")
if ( day == " mon" or day == " wed" or day == " fri"):
print(" You have a class at 8.30 a.m. Get ready")
else:
print(" You do not have a class at 8.30 a.m.")
OUTPUT
Enter the day as mon, tues , wed, thurs , fri, sat, sun: fri
You have a class at 8.30 a.m. Get ready
For multiple selective control statements, you can use else if statements, given by the fol-
lowing syntax.
17
if ( expression):
block 1
block 2
elif ( expression):
block 3
block 4
Extending the same example to other days, the code can be written as follows.
day = input(" Enter the day as mon, tues , wed, thurs ,
fri, sat, sun: ")
if ( day == " mon" or day == " wed" or day == " fri"):
print(" You have a class at 8.30 a.m. Get ready")
elif ( day == " tues"):
print(" You have a class at 11.20 a.m.")
elif ( day == " thurs"):
print(" You have a class at 10.30 a.m.")
else:
print(" Either you have entered a wrong string or it is holiday")
A nested if statement includes two or more if statements. These are used to check multiple
expressions within themselves. The syntax for nested-if statement is:
if ( expression 1):
if ( expression 2):
if ( expression 3):
block 1
block 2
Extending the above example, the user is asked for the input of course. If the course is
MCA, then another condition is checked for day and print the class timings.
course = input(" Enter your course: ")
day = input(" Enter the day as mon, tues , wed, thurs ,
fri, sat, sun: ")
if ( course == " MCA"):
if ( day == " mon" or day == " wed" or day == " fri"):
print(" You have a class at 8.30 a.m. Get ready!")
18
block 2
statement s2
Here, statement 1 is the initial condition before the while condition. If the condition is true,
blocks 1 and 2 gets executed. If the condition is false, statement 2 gets executed.
In this example, let us print the even numbers below or equal to the value of 10 using while
loop.
#print even numbers below or equal t o t h e value o f 10
1. n = 0
2. while (n <=10):
3. print (n, end = ’\t’)
# ’ t ’ i n d i c a t e s t h e space o f tab separated while p r i n t i n g on s c r e en
4. n += 2
5. print (’\n’)# n ew line
6. print(" Even numbers less than or equal to 10 are printed")
OUTPUT
0 2 4 6 8 10
Even numbers less than or equal to 10 are printed
The first line initializes the value of 0 to n. The condition of n < 10 is checked within while
loop. If the condition is true, the value is printed at line 3 and then increments by 2 at line 4.
This repeats until the value of n equals 10. When the condition is false, the newline and the
statement are printed at lines 5 and 6.
Let us write another program with while statement. Assume you are programming the
microwave oven to heat a bowl of vegetables and tea. If vegetables, cooking time is 2 minutes
and if tea, time is 40 seconds. Without importing time, we will just count down the time and
print the end statement for each of it.
dish = str( input(" enter the item whether veg or tea: "))
if dish == " veg":
n = 2 * 60
time = n
while (n>0):
n = n − 1
print (n, end=’,’)
print ("\n")
print(" Veg is cooked in", time , " seconds")
elif dish == " tea":
n = 40
time = n
while (n>0):
n = n− 1
print (n, end=",")
print ("\n")
print (" Tea is heated in", time , " seconds")
19
enter the item whether veg or tea: tea
39 ,38 ,37 ,36 ,35 ,34 ,33 ,32 ,31 ,30 ,29 ,28 ,27 ,26 ,25 ,
24 ,23 ,22 ,21 ,20 ,19 ,18 ,17 ,16 ,15 ,14 ,13 ,12 ,11 ,10 ,
9 ,8 ,7 ,6 ,5 ,4 ,3 ,2 ,1 ,0 ,
Tea is heated in 40 seconds
Try these.
1. Write a program to find the sum of first n integers.
Similar to the while loop, for loop also executes the statement if a statement is true. But,
the increment or decrement value is available in a single line. The syntax is:
for variable in range( initial_value , final_value ,
increment or decrement steps):
block 1
block 2
A program to list the odd numbers from 1 to 20 using for loop is given below.
# program to l i s t odd numbers from 1 t o 20
for i in range(1 ,20 ,2):
print(i, end = " ")
print ()
print (" Odd numbers 1 to 20 are printed")
OUTPUT
1 3 5 7 9 11 13 15 17 19
Odd numbers 1 to 20 are printed
Here, the first line indicates the numbers are in the range 1 to 20 and should be incremented by
2. The second line prints the number each time in the loop with space in between. Once the
loop is complete, both print statements are executed. An other example with strings is given
below. Here, the number of occurrence of “l” in “classical” is determined.
# number of l in c l a s s i c a l
word = " classical"
count = 0
for i in word:
if i == "l":
count += 1
print (" Number of l in classical is ", count)
OUTPUT
Number of l in classical is 2
20
Break and continue Statements
In some cases, certain programs need to be terminated and should not be going through the
loop. In such cases, break statement is used. Sometimes you might encounter a case where
the loop has to go through without doing anything. In those cases, continue is used. Examples
for these two statements are given below.
In the following program, a for loop is constructed to loop from 1 to 10. The second
line prints the number and if the value reaches 5, the program is terminated because of break
statement.
# example o f break statement
for i in range(1 ,10):
print (i)
if i == 5:
break
OUTPUT
1
2
3
4
5
For the use of continue statement, the above program is slightly modified such that when
the loop encounters 5 or 6, the values are not displayed. But the loop continues till the end.
# example of continue state m ent
for i in range(1 ,10):
if i == 5 or i == 6:
continue
print (i)
OUTPUT
1
2
3
4
7
8
9
Function
A program should never have any repeated statements. Suppose you write a program with
certain blocks and want to use that block again and again, function can be used. For instance,
take the program of heating veg or tea using while loop. If you see the program carefully, two
blocks are used and the other one for tea and one for veg, while the logic for both looks similar.
Is there a case where you could simplify those? The answer is yes. We can use functions for
these cases.
21
Use of function is done in two ways. First you have to define the function block and then
call it. The syntax of function definition is given by:
def function_name( parameters):
block 1
block 2
Here, def is the keyword and should always be started with this word when you start writing
a function. The particular name of the function is indicated by ‘function_name’, which can be
declared by the user. The parameters are variables that are entered within round brackets and
these are finite in number. The function name and parameters are associated with function call
statement, which is given by:
function_name ( parameters)
The same function name should be used and the number of parameters should be identical
with the number of variables used in the function block. An example to add two numbers using
function is given below. The function name is addition and the parameters in the function block
are x and y. Here, two numbers with variables num1 and num2 are assigned the values of 100
and 200, respectively (line 6,7). In line 8, the function with name addition is called with two
paramenters num1 and num2. This line indicates the values of 100 and 200 are the parameters
for addition function.
In line 2, the function block of addition begins with two parameters x and y. The values
of num1 is passed to the variable of x and num2 to y. Hence, x and y point to the values of
100 and 200, respectively. In line 3, total is computed with these values and in line 4 print
statement is executed.
1. # example o f f u n c t i o n f o r a d d i t i o n
2. def addition(x,y):
3. total = x+y
4. print (" Addition of two numbers ", total)
5.
6. num1 = 100
7. num2 = 200
8. addition(num1 , num2 )
OUTPUT
Addition of two numbers 300
Note: Always, write function blocks at the beginning of the program and call the particular
function after that.
The same example of heating tea and veg using microwave oven is given below, but using
function. Here, the parameters are the dish represented as string and time as integers.
# example of function
def heat(item , time):
n = time
while ( time >0):
time = time −1
22
print (time , end = ’,’)
print()
print(item , "is ready in ", n, " seconds")
dish = str( input(" enter the item whether veg or tea: "))
if dish == " veg":
heat (" veg" ,200)
elif dish == " tea":
heat (" tea" ,40)
OUTPUT
enter the item whether veg or tea: veg
199 ,198 ,197 ,196 ,195 ,194 ,193 ,192 ,191 ,190 ,189 ,..0 ,
veg is ready in 200 seconds
x = 78
y = 10
print (" Addition of two numbers ")
print ( addition(x,y))
print (" Subtraction of two numbers")
print ( subtraction(x,y))
OUTPUT
Addition of two numbers
23
88
Subtraction of two numbers
68
In the above example, the values of 78 and 10 are available in the main program. But the
variables within a particular function is accessible within that function itself. In other words,
it is called as local variable. The main program cannot access this variable. In the above
example, the variable of total is limited only to the function of addition and sub to subtraction.
You cannot use total or sub in main program. You cannot also use total in subtraction function
and sub in addition function. Let us see what happens when we use total in main function.
OUTPUT
Traceback (most recent call last):
File "fn_arithmetic.py", line 15, in <module>
print (total)
NameError: name ’total’ is not defined
The program throws an error that the variable ‘total’ is not declared although it has been
used in the function of addition. Thus, variable of total in this case is local in nature.
Suppose you want the program to recognize the total variable in the main program, you can
do it by declaring it as global. Refer to the following example for the usage of global.
x = 78
y = 10
print (" Addition of two numbers ")
a = addition(x,y)
print ( total)
print (" Subtraction of two numbers")
b = subtraction(x,y)
print ( sub)
OUTPUT
Addition of two numbers
88
Subtraction of two numbers
68
24
Recursive Functions
A function calling by itself is a recursive function. The process of calling repeats several times
and is useful in different applications. In real life, fractals, leaves and mountains with hills are
some examples where you can see the pattern are recursive in nature. In computer science,
recursion is found useful in solving problems. A few examples include Tower of Hanoi puzzle,
Fibonacci series and Ackermann functions.
An example of recursion is given in this example, which counts from 1 to 6. Here, count_recursion
is the function name and the number 6 is passed to the variable k. This value is decremented by
one in the function and calls by itself as specified in count_recursion(k − 1). The program
works such that, the value decrements until it reaches 0 with an addition of 1 in each step. The
value is then displayed in the screen. This is the reason why, the count is appearing in ascending
order although we have specified 6 and function decrements the value.
def count_recursion(k):
if(k>0):
result = count_recursion(k − 1)+1
print( result)
else:
result = 0
return result
OUTPUT
Example of Recursion Count 1
2
3
4
5
6
Another common example is the factorial which can be programmed with recursion as shown
below.
# f a c o r i a l on a number
def fact(n):
if n == 1:
return n
else:
return n* fact(n−1)
25
else:
print(" The factorial of",num,"is",fact( num))
OUTPUT
Enter a number: 6
The factorial of 6 is 720
OUTPUT
The area of triangle is 25.0
Example 1.2. With python print a pattern like the following structure.
******
*****
****
***
**
*
*
**
***
****
*****
******
for i in range (6,0,−1):
print (i * " * ")
for i in range (0 ,7 ,1):
print (i * " * ")
26
OUTPUT
Amount is Rs. 1280.08
Example 1.4. Write a program to get the number from the user and check whether it is positive
or negative.
# Check whether t h e g i v en number i s p o s i t i v e or n e g a t i v e
n = int( input(" enter the number: "))
if n>0:
print (n, "is positive")
elif n == 0:
print (n,"is equal to 0")
else:
print (n, "is negative")
Example 1.5. Write a program to find the sum of first n natural numbers.
#Sum o f f i r s t n numbers
total = 0
n = int( input(" enter the number "))
for i in range(n+1):
total = total+i
print (" Total of first ",n, " numbers is ", total)
OUTPUT
enter the numer 10
Total of first 10 numbers is 55
if num < 0:
print(" Sorry , factorial does not exist for negative numbers")
elif num == 0:
print(" The factorial of 0 is 1")
27
else:
OUTPUT
Enter a range
From: 4
To: 20
Even numbers from 4 to 20
4
6
8
10
12
14
16
18
20
Odd numbers from 4 to 20
5
7
9
11
13
15
17
19
28
Example 1.8. Write a program to print the series or 1 + x + x2 + x3 + ...xn
# sum o f s e r i e s 1+x+x ^ 2 + . . .
x = 2
n = 3
total = 0
for i in range(0,n+1):
term = pow(x,i)
print ( term)
total = total+term
print ( total)
OUTPUT
enter the value for x: 2
enter the value for n: 3
The sum is 15
OUTPUT
enter the value for n: 3
enter the value for x: 3
Series is −20
29
n = n+10
OUTPUT
3
4
−99
OUTPUT
enter the integer number to generate multiplication table 5
Multiplication table for 5
—−−−−−−−−−−−− −
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Example 1.12. For a given integer, separate the digits and print those.
# program to se parate the digits
n = int( input(" enter an integer "))
while n >0:
rem = n%10
n = n//10
print(" digit is ", rem)
OUTPUT
enter an integer 456
digit is 6
digit is 5
digit is 4
30
Example 1.13. Extend the above example 1.12 such that the given number is reversed.
# program to reverse t h e number
n = int( input(" enter an integer "))reverse
= 0
while n >0:
rem = n%10
n = n//10
reverse = ( reverse * 10) + rem
print (" The reversed number is ", reverse)
OUTPUT
enter an integer 456
The reversed number is 654
Example 1.14. Write a program to print all prime numbers from 1 to 100
# p r i n t prime numbers w i t h i n 100
OUTPUT 2
,3 ,5 ,7 ,11 ,13 ,17 ,19 ,23 ,29 ,31 ,37 ,41 ,43 ,47 ,53 ,59 ,61 ,67 ,
71 ,73 ,79 ,83 ,89 ,97 ,
Example 1.15. Write a program to print the length of the given string.
# p r i n t t h e t o t a l number o f c h a r a c t e r s i n t h e s t r i n g
word = str( input(" Enter the string "))
count = 0
for i in word:
count += 1
print (" Number of letters in the word ", word , "is ", count)
OUTPUT
Enter the string university
Number of letters in the word university is 10
31
Example 1.16. Write a program to print the number in each row such that it corresponds to the
count. For example for 1, 1 should be printed, in the second row 2 2 should be printed, in third
row 3 3 3 should be printed.
# numbers i n each row a cco rd in g t o t h e count
for i in range(1 ,6):
for j in range(1,i+1):
print (i, end = " ")
print()
OUTPUT
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
OUTPUT
enter the number of rows 6
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
Example 1.18. Write a program to print the Fibonacci numbers using recursion
#print fibonacci series
def fib(n):
if n <= 1:
return n
elif n > 1:
return ( fib(n−1)+fib(n−2))
32
for i in range(11):
print( fib(i), end = ",")
print()
OUTPUT
0 ,1 ,1 ,2 ,3 ,5 ,8 ,13 ,21 ,34 ,55 ,
Example 1.19. Write a python program to print the multiplication table of an integer in a
recursive manner.
# recursive multiplication of 5
def mul(n):
count = 0
if n<=1:
return 1
else:
count = count +1
return ("5X",count ,"=",(n−1) * 5)
n = 12
for i in range (n):
print ( mul(i))
OUTPU T
1
1
(’5X’, 1, ’=’, 5)
(’5X’, 1, ’=’, 10)
(’5X’, 1, ’=’, 15)
(’5X’, 1, ’=’, 20)
(’5X’, 1, ’=’, 25)
(’5X’, 1, ’=’, 30)
(’5X’, 1, ’=’, 35)
(’5X’, 1, ’=’, 40)
(’5X’, 1, ’=’, 45)
(’5X’, 1, ’=’, 50)
Example 1.20. This is an example taken from https://openbookproject.net/th
inkcs/python/english3e/recursion.html. Try it out changing l,a and f .
from turtle import Turtle , mainloop
def tree( plist , l, a, f):
" " " p l i s t i s l i s t o f pens
l i s l e n g t h o f branch
a is h a l f o f t h e angle bet ween 2 branches
f is f a c t o r by which branch i s s h o r t e n e d
from le v e l to l e v e l . """
if l > 6:
33
lst = []
for p in plist:
p. forward(l)
q = p. clone()
p. left(a)
q. right(a)
lst. append(p)
lst. append(q)
tree(lst, l * f, a,f)
def main():
p = Turtle()
p.color(" blue")
p.pensize(5)
p.hideturtle()
p.speed(100)
p.left(90)
p. penup()
p. goto(0, −200)
p. pendown()
Figure 1.4: OUTPUT
main()
34
Summary
1. Python can be executed in interactive mode through IDE such as IDLE
2. With an extension of *.py, Python can be saved and executed with the command python3
<filename.py>
3. Python supports variables extensively and a proper mechanism of variable format should
be provided.
4. Different datatypes such as integers, float and strings are automatically recognized with
python without any declaration
7. The loops of ‘for’ and ‘while’ help to repeat the logic multiple times
9. Functions can be also of recursive type, which helps in a number of real life example
problems
Learning Outcomes
After reading and working out the examples provided in this chapter, you should be able to:
(a) 1024
(b) 1,024
(c) 1024.0
(d) 0.25+10
35
2. Which of the following are valid string literals in python.
(a) “Hello”
(b) ’hello’
(c) “Hello”
(d) ‘Hello there’
(a) 80<=8
(b) 80==80
(c) 80!=90
(d) ’8’<=’10’
(a) 70
(b) 20
(c) 100
(d) 50
7. A boolean flag is
(a) A variable
(b) Has the value of True or False
(c) Is used as a condition for control statements
(d) All of the above
36
8. 15%2 equals
(a) 1
(b) 2
(c) 0
(d) 7
(a) if
(b) text
(c) atefc
(d) t_80
11. How many numbers will be printed in the following piece of code?
i = 5
while i >0:
print(i)
i = i − 1
(a) 4
(b) 5
(c) 6
(d) 0
12. Which statement ends the current iteration of the loop and continues to the next one?
(a) break
(b) continue
(c) skip
(d) pass
37
13. Which of the following is placed after the if condition?
(a) ;
(b) :
(c) !
(d) ::
(a) break
(b) continue
(c) skip
(d) pass
15. Which statement is used to stop the current iteration of the loop and continues with the
next loop?
(a) break
(b) continue
(c) skip
(d) pass
Descriptive Questions
1. With examples explain the correct and incorrect usage of variables in python.
2.What are the different arithmetic and boolean operators that are used in python.
5. Differentiate Break and Continue statement. When will you use Continue statement
and when will you use Break statement?
38
(e) (n>10) or (k==10 or k!=5)
(e) An if statement that displays ‘within range’ if num is between 0 and 100 , inclusive
(f) An if statement that displays ‘within range’ if num is between 0 and 100, inclusive,
and displays ‘out of range’ otherwise.
10. What is the difference between (/) and (//) operator in python? Explain with an example.
Programming Questions
1. Write a python program to print the area of triangle.
3. Write a python program to print the amount for simple interest, given principal amount,
year and rate of interest.
4. Write a python program to indicate the type of different values eg: if 345, entered value
345 is integer. if “abc”, entered value is string.
6. Write a python program to find the salary of an employee computing basic + DA (120%
of basic) + cca (20% of basic).
10. Write a python program to find whether the given year is a leap year.
12. Write a python program to find the sum and average of first n numbers.
13. Write a python program to find the sum of odd numbers and even numbers within a
certain range.
14. Write a python program to find whether the given number is an Armstrong number. Arm-
strong number is the number when the sum of the squares of the integer is equal to the
same number.
15. Write a python program to compute whether the given integer is palindrome or not.
16. Write a python program to convert the given decimal number to binary and binary to
decimal.
x x2 x3 xn
17. Write a python function to find the series 1 + + + + ... +
1! 2! 3! n!
39
18. Write a python program to emulate rock, paper and scissors game.
19. Write a python program to get the value of LCM of two integers.
References
1. Reema Thareja, Python Programming using Problem Solving Approach, Oxford Univer-
sity Press, 2019
40
UNIT - 2
CONTENTS:
Learning Objectives
Lists
Common Operations
Sequence Operations
Slicing Operation
Nested List
Looping within Lists
Assignment and Copy of Lists
Tuples
Sets
Dictionary
Strings
Length and count of particular occureces
String Cases
Type of String
Search and replace of strings
Formatting Strings
Slicing and Removal of Spaces
Minimum and Maximum characters in Strings
Split and Join methods
Comparing and Iterating Strings
Worked out Programming Problems
Application of Lists, Tuples and Strings
Summary
Learning Outcomes
Chapter Exercises
Multiple Choice Questions
Descriptive Questions
Programming Questions
Strings
References
41
UNIT II
Note: The indices always range from 0 to n − 1, where n is the number of elements in
the list.
Common operations of list are retrieve, update, insert, remove and append. For example,
consider the above list.
1. Retrieve subjects[3] will get the value of 86
2. Update subjects[1] with the value of 78 will replace 78, instead of 75
3. Insert subjects[2] with the value of 95 will result in subjects[2] = 95, subjects[3] = 80,
subjects[4]=86 and subjects[5]=68
4. Remove the value of 68 from the list will result in the range of list from subjects[0] to
subjects[3]
5. Append 89 to the list will result in subjects[5] = 89
42
Figure 2.1: List in Python
43
Common Operations
In Python, a list is denoted with square bracket and elements are separated by a comma. The
same example from Figure 2.1 in python can be written as:
>>> subjects = [70 ,75 ,80 ,86 ,68]
>>> subjects
[70 , 75, 80, 86, 68]
Here, the elements are integers. Instead of integers, strings can also be included as elements.
An empty list is indicated as []. The operations described above can be performed with python
as follows.
>>> subjects = [70 ,75 ,80 ,86 ,68]
>>> subjects
[70 , 75, 80, 86, 68]
>>> subjects[3] # R e t r e i v e s u b j e c t s [ 3 ]
86
>>> subjects[1] = 78 # r e p l a c e s u b j e c t s [ 1 ] value with 78
>>> subjects
[70 , 78, 80, 86, 68]
>>> subjects. insert(2 ,95) # i n s e r t 95 a t i ndex 2
>>> subjects
[70 , 78, 95, 80, 86, 68]
>>> del subjects[4] # d e l e t e i ndex 4
>>> subjects
[70 , 78, 95, 80, 68]
>>> subjects. append(89) # append 89
>>> subjects
[70 , 78, 95, 80, 68, 89]
>>>
Two additional opertions that you would use are sorting and reverse reorder, which is given
below.
>>> subjects
[68 , 70, 78, 80, 89, 95]
>>> subjects. reverse()
>>> subjects
[95 , 89, 80, 78, 70, 68]
Note: An important feature of list in python is that it is mutable - meaning, the values
in the list can be changed.
44
>>> text
[’dog’, ’cat’, ’ horse’, ’ binary’, ’oxen’]
>>> del text[2]
>>> text
[’dog’, ’cat’, ’ binary’, ’oxen’]
>>> text. append(’ zebra’)
>>> text
[’dog’, ’cat’, ’ binary’, ’oxen’, ’ zebra’]
>>> text. sort()
>>> text
[’ binary’, ’cat’, ’dog’, ’oxen’, ’ zebra’]
>>> text. reverse()
>>> text
[’ zebra’, ’oxen’, ’dog’, ’cat’, ’ binary’]
>>>
Sequence Operations
Python provides several ready made operations that can be performed on a list. These include
finding the total number of elements, slicing of indices to determine specific data, counting
the frequency of specific element, finding the index of the data, membership determination,
concatenation, finding minimum and maximum value. An operation of sum is also provided
which calculates the total value in the list.
Assume you have two lists, list1 and list2.
>>> list1 = [20 ,20 ,40 ,10]
>>> list2 = [60 ,70 ,70 ,70]
To find the total number of elements in the list, len can be used as len(list1), which will
result in 4. Different slicing operations can be performed such as retrieving the elements be-
tween the indices 2 to 4 as list1[2:4]. This will be dealt in Section 2.1.3. The frequency of
the elements in the list can be obtained using the keyword ‘count’. To determine the index of
the data, the keyword of index can be used, which will return the index value of that particular
data. Two lists can be concatenated using the operator of ’+’. Minimum and maximum of the
elements can be determined using ‘min’ and ‘max’ operators, respectively. If numerals are used
in lists, the keyword of ‘sum’ can be used to find the total value of elements. These operations
are provided in the code below.
>>> list1 = [20 ,20 ,40 ,10]
>>> list2 = [60 ,70 ,70 ,70]
>>> len
45
<built− in function len>
>>> len( list1 )
4
>>> list1 [2:]
[40 , 10]
>>> list1 . count(20)
2
>>> list1 . index(40)
2
>>> list1 . index(10)
3
>>> 70 in list1
False
>>> 70 in list2
True
>>> list2 . count(70)
3
>>> list3 = list1 +list2
>>> list3
[20 , 20, 40, 10, 60, 70, 70, 70]
>>> len( list3 )
8
>>> min( list3 )
10
>>> max( list3 )
70
>>> sum( list3 )
360
Slicing Operation
One of the most useful operation is to get the specific values from the list. This is done with
slicing operator ‘:’. Suppose the list is denoted as L, then the syntax is:
L[ start: end: step]
For example, refer Figure 2.1. If you want to get the the values of subjects with indices 1,2 and
3, use the following expression
subjects[1:4]
Different ways of slicing is shown below. Try and practice with more examples.
>>> words = [" apple", " banana", " orange", " pineapple",
" mango"," papaya"]
>>> len( words)
6
>>> words[2]
’ orange’
>>> words[2:4] # g e t words from 2 t o 4 . I ndex 4 i s
46
not included
[’ orange’, ’ pineapple’]
>>> words[2:] # ge t words from 2 t o end of the list
[’ orange’, ’ pineapple’, ’ mango’, ’ papaya’]
>>> words[2:5] # g e t words from 2 t o 5
[’ orange’, ’ pineapple’, ’ mango’]
>>> words[ − 1] # g e t t h e l a s t word
’ papaya’
>>> words[: − 1] # get a l l words till the l a s t word
[’ apple’, ’ banana’, ’ orange’, ’ pineapple’, ’ mango’]
>>> words[: − 2] # g e t a l l words b e f o r e t h e l a s t 2 nd word
from right
[’ apple’, ’ banana’, ’ orange’, ’ pineapple’]
>>> words[3: − 1] # g e t t h e words from 3 rd i ndex to
the last word
[’ pineapple’, ’ mango’]
>>> words[ − 3]# g e t t h e l a s t 3 rd word from the right
’ pineapple’
>>> words[:] # g e t a l l words
[’ apple’, ’ banana’, ’ orange’, ’ pineapple’, ’ mango’, ’ papaya’]
The operator ‘::’ is used to get the elements with a jump in sequence. For example, to get 0,
2 and 4 elements from the list L[0::2] can be used (An element is skipped while reading the
sequence). A few more scenarios are presented below.
>>> words[:]
[’ apple’, ’ banana’, ’ orange’, ’ pineapple’, ’ mango’, ’ papaya’]
>>> words[0::4]
[’ apple’, ’ mango’]
>>> words[1::3]
[’ banana’, ’ mango’]
>>> words[1::4]
[’ banana’, ’ papaya’]
>>> words[0::2]
[’ apple’, ’ orange’, ’ mango’]
>>> words[1::2]
[’ banana’, ’ pineapple’, ’ papaya’]
The operations discussed above such as updating, deleting can also be used with slicing. The
following program starts with an empty list, adds the even numbers to the list and deletes one
by one.
# program t o e n t e r even numbers t o a l i s t and d e l e t e
even = [] # i n i t i a l i z e t h e l i s t
47
for i in range(0 ,20):
if i % 2 == 0:
even = even+[i] # c o n v e r t i to l i s t and c o n c a t e n a t e
with even at every step
print (" Even numbers between 0 and 20 are: ")
print ( even)
print (" Deleting the list now")
del even[:]
print (" The list is empty")
print ( even)
OUTPUT
Even numbers between 0 and 20 are:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Deleting the list now
The list is empty
[]
Nested List
A nested list is a list within a list. In this case, the nested list will take one value of index
and the nested list itself has index values. Assume you have a list ‘L’ with two lists ‘L1’ and
‘L2’ within it. This can be represented as L = [[L1],[L2]]. As an example, let us take the
list as person with elements of roll number, name, courses they are taking and programming
languages known. This can be expressed as:
person = [‘ ‘2020115223 ’’ ,‘‘ Selvi’’ ,[‘‘ maths’’ ,‘‘ operating systems’’,
‘‘ data structures’’], [‘‘c’’ ,‘‘c++’ ’ ,‘‘ python’’ ,‘‘ java’’]]
Accessing the list is given below.
>>> len( person)
4
>>> person[0]
’ 2020115223 ’
>>> person[1]
’ Selvi’
>>> person[2]
[’ maths’, ’ operating systems’, ’data structures’]
>>> person[3]
[’c’, ’c++’, ’ python’, ’java’]
48
To access the list within a list [][] can be used, as shown in the following example.
>>> len( person[2])
3
>>> person[2][0] # access the f i r s t course o f t h e person list
’ maths’
>>> person[2][1] # access the second course
’ operating systems’
>>> person[2][2] # access the t h i r d course
’data structures’
>>> person [3][1:3] # g e t t h e 1 s t and 2 nd value from t h e list
# o f programming l an gua ges
[’c++’, ’ python’]
OUTPUT
apple
orange
banana
pineapple
mango
49
Looping using index
With the same list, using index the code is given below. To iterate through indices, first the
length of the list should be determined, as shown in the second line as ‘len(fruits)’, which is
assinged to the variale ‘n’. For looping, this integer is used (line 6) and the loop iterates through
index with variable ‘i’. In this case ‘fruits[i]’ indicates each item.
First time, when the loop starts, i = 0 and fruits[0] = “apple”. During the second loop, i =1
and fruits[1] = “orange” and this continues till the lenth of the list.
1. fruits = [" apple"," orange"," banana"," pineapple"," mango"]
2. n = len( fruits)
3. print ("— —−− −− ","−− −− −− − ")
4. print (" index","| "," item")
5. print ("— —−− −− ","−− −− −− − ")
6. for i in range(n):
7. print (" ",i," | ",fruits[i])
8. print ("−− −− −− ","−− −− −− −")
OUTPUT
—−− −−−−
index | item
—−− −−−−
0 | apple
1 | orange
2 | banana
3 | pineapple
4 | mango
50
OUTPUT
index | item
—−− − −−−
0 | apple
1 | orange
2 | banana
3 | pineapple
4 | mango
—−− − −−−
A quick way of iterating can be done in one line (list comprehension) as shown below.
Here, the print statement with for loop is included in square brackets.
fruits = [" apple"," orange"," banana"," pineapple"," mango"]
[ print( item) for item in fruits]
OUTPUT
apple
orange
banana
pineapple
mango
With while, the example of looping is illustrated below.
fruits = [" apple"," orange"," banana"," pineapple"," mango"]
n = len( fruits)
OUTPUT
apple
orange
banana
pineapple
mango
With while, the example of looping is illustrated below.
fruits = [" apple"," orange"," banana"," pineapple"," mango"]
n = len( fruits)
i = 0
while (i<n):
print ( fruits[i])
i+=1
51
OUTPUT
apple
orange
banana
pineapple
mango
Like variables, you can assign one variable to another. In these cases, the list that assigns point
to the same location. For example, consider the following code showing two lists numbers_1
and numbers_2. numbers_1 is assigned to numbers_2 and those give the same result.
Now, the value of 30 in numbers_2 should be updated as 200. So, the code is numbers_2[2]=200.
Try printing the values of numbers_1 and numbers_2 after this change. You will be surprised
that values in numbers_1 also is changed.
52
What really happens when you assign a variable or a list?
When you assign a variable or a list to another variable or a list, the same memory address
location is pointed where the value is stored. Take for example, numbers_1 andnumbers_2
and see the memory locations where the lists are stored. In python, to get the memory
location address in hexadecimal, use hex(id(variable_name)). Let us print the location
of numbers_1 and numbers_2.
>>> hex(id( numbers_1 )) ’0
x7fa0b987fec0 ’
>>> hex(id( numbers_2 )) ’0
x7fa0b987fec0 ’
>>> numbers_2 [2]=200
Here, both locations are one and the same. That is, data in numbers_1 are not copied to
numbers_2, but numbers_2 link to memory location of numbers_1.
When you are programming, you may come across some cases where you have to copy
the list and make changes only in the copied list and do not want just an assignment. In such
cases, you can use slicing operator [:]. To illustrate this case, let us take the above example and
instead of just assigning, use [:] and see the difference.
>>> numbers_1 = [10 ,20 ,30]
>>> numbers_2 = numbers_1 [:]
>>> numbers_1
[10 , 20, 30]
>>> numbers_2
[10 , 20, 30]
>>> numbers_2 [2] = 200
>>> numbers_1
[10 , 20, 30]
>>> numbers_2
[10 , 20, 200]
Here, value of numbers_2 alone changes without any effect on numbers_1. Another interesting
feature to explore is what happens to the memory location of the two lists. Try this code and
you will see that the two lists point to different memory locations, indicating that the second
list has a copy of the first list.
>>> hex(id( numbers_1 ))
’0 x7fa0b97b3880 ’
>>> hex(id( numbers_2 ))
’0 x7fa0b9a2f300 ’
Copying with [:] works well when there is a single element in a list. But if there is a nested
list, you should be careful. Consider the following example with list num1 which is a nested
list. num1[:] is assigned to num2 to copy the values of num1 to num2.
53
>>> num1 = [10 ,20 ,[5 ,15 ,25 ,35],50]
>>> num2 = num1 [:]
>>> num1
[10 , 20, [5, 15, 25, 35], 50]
>>> num2
[10 , 20, [5, 15, 25, 35], 50]
>>> num2 [2]
[5, 15, 25, 35]
If you want to update the value of 35 to 2005 in num2, you will probably code like this.
>>> num2 [2][3] = 2005
>>> num2
[10 , 20, [5, 15, 25, 2005], 50]
>>> num1
[10 , 20, [5, 15, 25, 2005], 50]
But on doing so, the values in both lists num1 and num2 changes to 2005.
Inorder to have the second list with the update without any modification in the first list, you
have to use the module of deepcopy as shown below. The first line imports a module called
‘deepcopy’ from ‘copy’ package. The third line uses this module to copy the contents of num1
to num2.
>>> from copy import deepcopy
>>> num1 = [10 ,20 ,[5 ,15 ,25 ,35],50]
>>> num2 = deepcopy( num1 )
>>> num1
[10 , 20, [5, 15, 25, 35], 50]
>>> num2
[10 , 20, [5, 15, 25, 35], 50]
>>> num2 [2][3] = 2005
>>> num2
[10 , 20, [5, 15, 25, 2005], 50]
>>> num1
[10 , 20, [5, 15, 25, 35], 50]
>>>
In this case, the num2 values are updated without any effect on num1.
Tuples
Tuples are similar to that of lists, but are immutable - meaning the values cannot be changed.
Tuples can be created using parantheses () separated by a comma ’,’ and can include different
data types such as integers, floats, strings, lists and tuples too. With tuples, the similar slicing
operations are possible as seen in list.
>>> text = (’dog’,’cat’,’ horse’,’ zebra’)
>>> text[0]
’dog’
>>> text[1]
54
’cat’
>>> text[2]
’ horse’
>>> text[3]
’ zebra’
>>> text[3][0]
’z’
>>> text[2][1: − 1]
’ors’
As said earlier, tuples do not accept update or changes in values. Suppose in the example,
you have to change the value of ‘horse’ to ‘ox’, in list you can assign as text[2]=‘ox’. Try
assigning the same to this tuple and you will get an error statement as shown below. This means
that values in tuple cannot be changed.
>>> text[2] = ’ox’
Traceback ( most recent call last):
File "<pyshell#7>", line 1, in <module >
text[2] = ’ox’
TypeError: ’ tuple’ object does not support item assignment
Some operations on tuples are listed below.
Two tuples can be concatenated using the operator of ‘+’. Tuples of birds and mammals
contain strings which are concatenated to animals. Another tuples of num1 and num2 contain
integers which are concatenated to form another tuple.
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Other operations such as finding the number of elements, membership, index numbers and
count operations are similar to that of a list. Examples illustrating these operations are given
below.
>>> animals = (’crow’, ’ sparrow’, ’ camel’, ’cat’, ’dog’)
>>> len( animals)
5
>>> num3 = num1 +num2
55
>>> len( num3 )
10
# f i n d t h e i ndex of cat
>>> animals. index(" cat")
3
# f i n d t h e i ndex o f dog
>>> animals. count(" dog")
1
# c o n c a t e n a t e animals with animals and a s s i gn t o animals
>>> animals = animals+animals
>>> animals
(’crow’, ’ sparrow’, ’ camel’, ’cat’, ’dog’,
’crow’, ’ sparrow’, ’ camel’, ’cat’, ’dog’)
# count t h e number o f dogs i n animals t u p l e
>>> animals. count(" dog")
2
# check whether c a t i s i n animals tuple
>>> ’cat’ in animals
True
# check whether camel i s i n animals tuple
>>> ’ camel’ in animals
True
# check whether 3 i s i n animals tuple
>>> 3 in animals
False
# check whether 3 i s not i n animals tuple
>>> 3 not in animals
True
>>>
Loops can be used to iterate within tuples like that of lists. An example is shown below.
animals = (" cat"," dog"," horse"," sparrow"," crow" ,[2 ,4 ,6])
for index , item in enumer ate( animals ):
print ( index , item)
OUTPUT
0 cat
1 dog
2 horse
3 sparrow
4 crow
5 [2 ,4 ,6]
56
Sets
A set is a datatype with the following features and provides the standard mathematical opera-
tions such as union, intersection and set difference.
1. Set is mutable
2. No duplicates in Sets
The set is represented using the syntax{}or set(). It can have any type of data such as integer,
float, string and tuple. But lists cannot be included in a set. Refer to the following example.
set1 has integers and set2 has datatype of integers, float, strings and tuple.
>>> set1 = {0 ,2 ,4}
>>> set1
{0, 2, 4}
>>> set2 = {0 ,2 ,4 ,6.8 ," hello world" ,(7 ,10.5 ,7)}
>>> set2
{0, 2, 4, 6.8 , ’ hello world’, (7, 10.5 , 7)}
As mentioned earlier, sets cannot have duplicates. In the next example set3 = 0,2,4,4,6,4,7
is entered, but the result is unique.
>>> set3 = {0 ,2 ,4 ,4 ,6 ,4 ,7}
>>> set3
{0, 2, 4, 6, 7}
To add values in the set, you can either use the keyword add or update. The former is used to
add a single element and the latter to add the set of elements. An example of using both these
keywords are given below.
>>> set3 = {0 ,2 ,4 ,4 ,6 ,4 ,7}
>>> set3
{0, 2, 4, 6, 7}
>>> set3 . add(50)
>>> set3
{0, 2, 4, 6, 7, 50}
>>> set3 . add(50)
>>> set3
{0, 2, 4, 6, 7, 50}
>>> set3 . update([60 ,70 ,80 ,90])
>>> set3
{0, 2, 4, 6, 7, 70, 80, 50, 90, 60}
>>> set3 . update({200.6 ,300.7 ,400.8 ,500.9})
>>> set3
{0, 2, 4, 6, 7, 70, 200.6 , 300.7 , 80, 400.8 , 50, 500.9 , 90, 60}
57
To delete an element in the set, use the keyword remove or discard. The difference between
these is that the former raises an error if the element is not present in the set, while the latter
does not. An example demonstrating these two keywords is shown below.
>>> set3
{0, 2, 4, 6, 7, 70, 200.6 , 300.7 , 80, 400.8 , 50, 500.9 , 90, 60}
# d i s c a r d t h e e l ement 200 . 6
>>> set3 . discard (200.6)
>>> set3
{0, 2, 4, 6, 7, 70, 300.7 , 80, 400.8 , 50, 500.9 , 90, 60}
# d i s c a r d t h e e l ement 1000 , which i s not i n t h e s e t
>>> set3 . discard(1000)
>>> set3
{0, 2, 4, 6, 7, 70, 300.7 , 80, 400.8 , 50, 500.9 , 90, 60}
58
>>> set1 − set2
{1, 3, 5, 7}
>>> set1 . difference( set2 )
{1, 3, 5, 7}
>>> set2 . difference( set1 )
{0}
>>> # symmet ri c difference − ele ments not i n both s e t 1 and s e t 2
>>> set1 . symmetric_difference( set2 )
{0, 1, 3, 5, 7}
>>> set2 . symmetric_difference( set1 )
{0, 1, 3, 5, 7}
Other methods are given in Table 2.3. Assume set1 = {1,3,5,7}, set3 = {2,4,6,8} and
set4 = {1,2,3,4,5,6,7,8}.
Table 2.1: Methods in Sets
Method Description Example Result
clear() Removes all elements set1.clear() set()
from the set
copy() Copies elements from set2 = set1.copy() set2 = {1,3,5,7}
one set to another
isdisjoint() Checks whether the two set3.isdisjoint(set1) True
sets are disjoint
issubset() Checks whether one set set3.issubset(set4) True
is a subset of another
issuperset() Checks whether one set set4.issuperset(set1) True
is a superset of another
in membership 0 in set1 False
for set, do not use {}, because {} is also used to indicate dictionary in python. Hence,
to create an empty set use the keyword set( ). In the example given below, set5 is
initialized to an empty set and then 2 is added.
>>> set5 = set ()
>>> set5
set()
>>> set5 . add(2)
59
While set( ) is mutable without any duplicates and unordered, there is another variety
which is immutable known as frozenset. An example to demonstrate this set is given below.
>>> fruits = frozenset([" apple"," banana"])
>>> fruits. add(" orange")
Traceback ( most recent call last):
File "<pyshell#31 >", line 1, in <module >
fruits. add(" orange")
AttributeError: ’ frozenset’ object has no attribute ’add’
Like other types, sets also can be iterated with loops and an example is shown below.
fruits = {" apple"," orange"," banana"," pineapple"," mango"}
for item in fruits:
print ( item)
OUTPUT
banana
pineapple
orange
apple
mango
Dictionary
A dictionary is used to indicate a key, value pair and is an unordered data structure. It is denoted
by {:}, where the key and the value are separated by ‘:’.
You can take the analogy of how the dictionary is organized as word and the corresponding
meaning.
For example, if you want to represent roll number and names of students, it can be done with
the help of dictionary as:
>>> students = {2013110022: " Raman", 2013110023: " Ragavan",
2013110024:" Sandra" ,2013110025:" Sita Lakshmi", 2013110026: " Siva"}
>>> students
{2013110022: ’ Raman’, 2013110023: ’ Ragavan’, 2013110024:
’ Sandra’, 2013110025: ’Sita Lakshmi’, 2013110026: ’Siva’}
The dictionary is unordered, meaning there are no indices like that of lists and tuples. But the
value can be accessed based on the key as shown below.
>>> students [2013110022]
’ Raman’
Dictionaries cannot have duplicate keys. Try these in your editor and check what happens when
you give duplicate keys.
60
>>> {2013110022: ’ Raman’, 2013110023: ’ Ragavan’, 2013110024: ’ Sandra’,
2013110025: ’Sita Lakshmi’, 2013110026: ’Siva’, 2013110026: " Syed"}
{2013110022: ’ Raman’, 2013110023: ’ Ragavan’, 2013110024: ’ Sandra’,
2013110025: ’Sita Lakshmi’, 2013110026: ’Syed’}
Note: The syntax of dictionary and set looks similar as both are represented using {}.
But the dictionary has a key value pair separated by :, whereas a set is a single entity. By
default, if you initialize a variable with {}, python takes it as dictionary and not set. See
the following example, where the variable num is assigned to the empty dictionary and
the keyword type(num) indicates as dictionary.
>>> num = {}
>>> type( num)
Some methods used in Dictionary are given below. These include the length of the elements,
string representation, determination of the key for that particular item, membership with in,
displaying all keys, values and updating the dictionary.
2013110022 Raman
2013110023 Ragavan
2013110024 Sandra
2013110025 Sita Lakshmi
2013110026 Syed
2014110022 Gerald
2014110023 Greshma
62
2014110024 Geiko
rollnumber name
A dictionary can have nested dictionary as illustrated below. Here, each student is the key and
the value is the marks of the course which itself is in a dictionary.
>>> mca = {" Raman":{"OS": 90, " networks":85 , " maths": 85},
" Ragavan": {"OS": 80, " networks":75 , " maths": 85},
" Sita Lakshmi" : {"OS": 95, " networks":80 , " maths": 75}}
>>> for i, j in mca. items():
print(i,j)
Strings
Python supports strings extensively. A number of natural language processing techniques are
implemented using python. Strings are expressed using inverted comma “ ”. (Here, a single of
double quote can be used). For multiline strings, three quotes can be used. An example with
multiline string is given below.
>>> str1 = ’ ’ ’ Hello , t h i s i s t h e course on python .
Here you w i l l t h e b a s i c s o f python i n Unit 1 and
data t y p e s i n Unit I I . Python i s used i n many
a p p l i c a t i o n s worldwide . ’ ’ ’
>>> str1
’Hello , this is the course on python.
Here you will the basics of python in Unit 1
and data types in Unit II. Python is used in many
applications worldwide.’
Strings like lists can be concatenated and appended using ‘+’ operator. If ‘*’ operator is
used, then the string can be seen as a multiple. A few examples are shown below.
>>> str1 = " hello"
>>> str2 = " world"
>>> # c o n c a t e n a t i o n o f s t r 1 and s t r 2
>>> str1 +str2
’ helloworld’
>>> str1 + " " + str2
’ hello world’
>>> # append with += op e r a t o r
>>> str1 += " world"
>>> str1
’ hello world’
63
>>> # m u l t i p l y s t r 1 three times
>>> str1
’ hello world’
>>> str1 *3
’ hello worldhello worldhello world’
There are several inbuilt methods available in strings. For the purose of this course, the
methods are arranged into these categories:
5.String formatting
6. Slicing operation
64
String Cases
Several methods such as capitalizing the first character in the string, change of cases and check-
ing whether the string is in a particular string are included in Python. These are illustrated
below.
>>> # c a p i t a l i z e
>>> str1 . capitalize()
’This is a course on python’
>>> str2 = " THIS IS A COURSE ON PYTHON"
>>> str2 . capitalize()
’This is a course on python’
>>> str1
’This is a course on Python’
>>> str3 = " this is a course on python"
>>> str3 . capitalize()
’This is a course on python’
>>> # upper case
>>> str3 . upper()
’THIS IS A COURSE ON PYTHON’
>>> # l ower case
>>> str2 . lower()
’this is a course on python’
>>> # check f o r l ower or upper case
>>> str2 . islower()
False
>>> str2 . isupper()
True
>>> # t i t l e case
>>> str2
’THIS IS A COURSE ON PYTHON’
>>> str2 . title()
’This Is A Course On Python’
>>> str3
’this is a course on python’
>>> str3 . title()
’This Is A Course On Python’
>>> # swapcase
>>> str4 = " ThIs iS a CoUrSe oN PyThOn"
>>> str4
’ThIs iS a CoUrSe oN PyThOn’
>>> str4 . swapcase()
’tHiS Is A cOuRsE On pYtHoN’
65
Type of String
Methods such as isalpha(), isalnum(), isdigit(), isspace(), isidentifier()
can be used to check the type of the string. These are illustrated below.
>>> str1 = " Chennai600025 "
>>> # I f s t r i n g has a l p h a b e t s and numbers , r e t u r n true
>>> str1 . isalnum()
True
>>> str2 = " C1_"
>>> str2 . isalnum()
False
>>> str3 = "C1"
>>> str3 . isalnum()
True
>>> # I f s t r i n g has a l phabet s , r e t u r n true
>>> str1 . isalpha()
False
>>> str4 = " Chennai"
>>> str4 . isalpha()
True
>>> # Check i f t h e s t r i n g consist o f space only
>>> str5 = " "
>>> str5 . isspace()
True
>>> str1 . isspace()
False
>>> # Check i f t h e s t r i n g i s only of digits
>>> str1 . isdigit()
False
>>> str6 = " 80930 "
>>> str6 . isdigit()
True
66
Search and replace of strings
Finding a part of the string with variants from the beginning or from the end are available in
Python. The returning value in these cases is the index value. If the particular index is not
found, then the find option returns -1 and index returns an error value. A replace option is
also provided which can be used to replace the string. The following example illustrate these
methods.
>>> str1 = " This is a course on Python"
>>> # f i n d " i s " from s t r 1
>>> str1 . find("is",0, len( str1 ))
2
>>> # f i n d " course " from s t r 1
>>> str1 . find(" course",0, len( str1 ))
10
>>> str1 . find(" hello",0, len( str1 ))
–1
>>> # f i n d t h e p a r t i c u l a r s t r i n g u s i ng i ndex keyword .
>>> str1 . index("is",0, len( str1 ))
2
>>> str1 . index(" hello",0, len( str1 ))
Traceback ( most recent call last):
File "<pyshell#8>", line 1, in <module >
str1 . index(" hello",0, len( str1 ))
ValueError: substring not found
>>> # Search from end u s ing f i n d
>>> str1 . rfind(" course",0, len( str1 ))
10
>>> str1 . rfind("is",0, len( str1 ))
5
>>> str1 . rindex(" hello",0, len( str1 ))
Traceback ( most recent call last):
File "<pyshell#13 >", line 1, in <module >
str1 . rindex(" hello",0, len( str1 ))
ValueError: substring not found
>>> # r e p l a c e " course " with " s u j e c t "
>>> str1 . replace(" course"," subject")
’This is a subject on Python’
Formatting Strings
To format strings for displaying in the output screen, %s symbol is used. This symbol substi-
tutes the corresponding variables. The syntax is:
‘‘<FORMAT >’’ % (<VALUES >)
An example is given below to print the rollnumber and name.
67
>>> rollnumber = 2013110022
>>> name = " Raman"
>>> print(" Roll number = %d and Name = %s" %( rollnumber , name))
Roll number = 2013110022 and Name = Raman
The strings can be formatted to center justified, left or right justified as shown below. Here,
a total of 10 character length is given with a symbol of ’*’ to indicate justification. To fill with
zeros, keyword of zfill can be used.
>>> # c e n t e r j u s t i f i e d
>>> str1 = " hello"
>>> print( str1 . center(10 ,’ * ’))
** hello ***
>>> # l e f t j u s t i f i e d
>>> str1 . ljust(10 ,’ * ’)
’ hello ***** ’
>>> # r i g h t j u s t i f i e d
>>> str1 . rjust(10 ,’ * ’)
’ ***** hello’
>>># f i l l with z e ro s
>>> str2 = " 6789 "
>>> str2 . zfill(10)
’ 0000006789 ’
68
>>> str2
’ Hello World ’
>>> str2 . lstrip()
’ Hello World ’
>>> # remove white space a t t h e end
>>> str2
’ Hello World ’
>>> str2 . rstrip()
’ Hello World’
69
[(0 , ’P’), (1, ’y’), (2, ’t’), (3, ’h’), (4, ’o’), (5, ’n’)]
Python Course
import turtle
wn = turtle. Screen()
wn. bgcolor(" lightblue")
t1 = turtle. Turtle()
t1. pensize(5)
clrs = [" yellow"," red"," purple"," blue"]
70
for i in clrs:
t1. color(i)
t1. forward(50)
t1. right(90)
wn. mainloop()
OUTPUT
Example 2.2. Write a python program to get the positive integers from the user and add those
to a list. Then, find the cube of the numbers in the list.
# g e t i n t e g e r s from user and save i t i n t h e l i s t . Find t h e cube .
numlist = []
n = 1
while n >0:
num = int( input(" Enter the positive number to be added to the list ,
to stop enter −1: "))
if num > 0:
numlist = numlist+[ num]
n = n+1
else:
n = −1
cube = []
for i in numlist:
cube = cube +[i ** 3]
print (" The cube of entered numbers ", cube)
OUTPUT
Enter the positive number to be added to the list, to stop enter − 1:
3
Enter the positive number to be added to the list, to stop enter − 1:
4
Enter the positive number to be added to the list, to stop enter − 1:
5
Enter the positive number to be added to the list, to stop enter − 1:
6
Enter the positive number to be added to the list, to stop enter − 1:
–1
The entered numbers are [3, 4, 5, 6]
The cube of entered numbers [27 , 64, 125 , 216]
71
Example 2.3. Write a python program to get the fixed numbers of integers from the user and
store as a list. Then arrange in ascending order.
# s o r t i n ascendi ng order
n = int( input(" enter the number of elements in the list: "))
numlist = []
for i in range(n):
num = int( input(" enter number " ))
numlist. append( num)
print (" Entered numbers are: ")
print ( numlist)
ascendlist = sorted( numlist)
print (" Sorted numbers are ")
print( ascendlist)
OUTPUT
enter the number of elements in the list: 5
enter number 20
enter number 10
enter number 39
enter number 45
enter number 12
Entered numbers are:
[20 , 10, 39, 45, 12]
Sorted numbers are
[10 , 12, 20, 39, 45]
Example 2.4. Write a python program to interchange the first and last element in a list.
# interchange f i r s t and l a s t e l ement in the list
nlist = [2 ,3 ,4 ,5 ,6 ,100]
interchange( nlist)
72
OUTPUT
Original list before interchange: [2, 3, 4, 5, 6, 100]
List after interchange: [100 , 3, 4, 5, 6, 2]
Example 2.5. Write a python program to reverse the numbers in a list.
#reverse t h e numbers in the list
def revslice( listn):
print (" Original list before reverse: ", listn)
# use s l i c i n g o p e r a t i o n
revlist = listn[:: − 1]
print (" List after reverse using slice operation: ", revlist)
nlist = [2 ,3 ,4 ,5 ,6 ,100]
revslice( nlist)
revbuiltin( nlist)
OUTPUT
Original list before reverse: [2, 3, 4, 5, 6, 100]
List after reverse using slice operation: [100 , 6, 5, 4, 3, 2]
Original list before reverse: [2, 3, 4, 5, 6, 100]
List after reverse using builtin: [100 , 6, 5, 4, 3, 2]
Example 2.6. Write a python program to find the sum of numbers in the list.
# sum o f e l e m e n t s in a l i s t
73
nlist = [2 ,3 ,4 ,5 ,6 ,100]
total( nlist)
totalbuiltin( nlist)
OUTPUT
Original list: [2, 3, 4, 5, 6, 100]
Total using for loop = 120
Original list: [2, 3, 4, 5, 6, 100]
Total with builtin sum = 120
Example 2.7. Write a python program to find the smallest number in a list.
# s m a l l e s t number i n t h e l i s t
74
OUTPUT
Example 2.8. Write a python program to print the items of even indices in a list.
#print t h e even numbers in the list
nlist = [2 ,3 ,4 ,5 ,6 ,100]
even( nlist)
OUTPUT
Original list: [2, 3, 4, 5, 6, 100]
Index
Index
Index
75
Example 2.9.
Write a python program to add two matrices with nested list.
# a d d i t i o n o f two m a t r i c e s
mat1 = [[1 ,2 ,3],[1 ,2 ,1],[2 ,3 ,5]]
mat2 = [[1 ,2 ,3],[1 ,2 ,1],[2 ,3 ,5]]
total = [[0 ,0 ,0],[0 ,0 ,0],[0 ,0 ,0]]
OUTPUT
Matrix 1 [[1 , 2, 3], [1, 2, 1], [2, 3, 5]]
Matrix 2 [[1 , 2, 3], [1, 2, 1], [2, 3, 5]]
Addition of matrix [[2 , 4, 6], [2, 4, 2], [4, 6, 10]]
Example 2.10. Write a python program to get the kth column of the matrix.
# get k t h column o f a mat ri x
mat1 = [[1 ,2 ,3 ,4],[1 ,2 ,1 ,4],[2 ,3 ,5 ,4]]
# number o f rows
print (" The matrix is ", mat1 )
rows = len( mat1 )
OUTPUT
The matrix is [[1 , 2, 3, 4], [1, 2, 1, 4], [2, 3, 5, 4]]
Number of rows = 3
Enter the column number to be printed 3
The column 3 is:
4
4
4
76
Example 2.11. Write a python program to convert the list elements to a tuple and vice versa.
#convert l i s t to t u p le
listn = [2 ,3 ,4 ,5 ,6]
print (" The list elements are ", listn)
# c onv e rt to tu p le
tuplen = tuple( listn)
print (" The converted tuple elments are", tuplen)
# c o n v e r t i n g back t o l i s t
converted_list = list( tuplen)
print (" Converting tuple back to list ", converted_list)
OUTPUT
The list elements are [2, 3, 4, 5, 6]
The converted tuple elments are (2, 3, 4, 5, 6)
Converting tuple back to list [2, 3, 4, 5, 6]
Example 2.12. Write a Python program to join two tuples if the last element of first tuple is
equal to the first element of second tuple and print only unique elements.
# j o i n two t u p l e and print unique elements
tuple1 = (2 ,3 ,4 ,5)
tuple2 = (5 ,6 ,7 ,8)
OUTPUT
Tuple1 is (2, 3, 4, 5)
Tuple2 is (5, 6, 7, 8)
The unique elemen ts a re: {2, 3, 4, 5, 6, 7, 8}
77
Example 2.13. Write a Python program to check whether the even number indices of a tuple
are same.
# check whether the tu p l e o f immedi at e even number indices are same
tuple1 = (1 ,0 ,1 ,2 ,1 ,3 ,1)
for i in range(0, len( tuple1) − 2):
if tuple1 [i] == tuple1 [i+2]:
print (" indices ", i, i+1, " are same with ")
print ( tuple1 [i], " ", tuple1 [i+2])
OUTPUT
indices 0 1 are same with 1
1
indices 2 3 are same with 1
1
indices 4 5 are same with 1
1
bama@bama−Veriton−M4660G
Example 2.14. Write a Python program to generate the jumbled words of a given string.
# p ermu ta te t h e g i v en string
from itertools import permutations
word = str( input(" Enter the word: "))
word = word. lower()
perm_list = []
for i in permutations( word):
perm_list = perm_list+ ["". join(i)]
OUTPUT
Enter the word: HELLO
Total number of jumbled words are 120
The jumbled words are
[’ hello’, ’ helol’, ’ hello’, ’ helol’, ’ heoll’, ’ heoll’, ’ hlelo’,
’ hleol’, ’ hlleo’, ’ hlloe’, ’ hloel’, ’ hlole’, ’ hlelo’, ’ hleol’,
78
’ hlleo’, ’ hlloe’, ’ hloel’, ’ hlole’, ’ hoell’, ’ hoell’, ’ holel’,
’ holle’, ’ holel’, ’ holle’, ’ ehllo’, ’ ehlol’, ’ ehllo’, ’ ehlol’,
’ eholl’, ’ eholl’, ’ elhlo’, ’ elhol’, ’ ellho’, ’ elloh’, ’ elohl’,
’ elolh’, ’ elhlo’, ’ elhol’, ’ ellho’, ’ elloh’, ’ elohl’, ’ elolh’,
’ eohll’, ’ eohll’, ’ eolhl’, ’ eollh’, ’ eolhl’, ’ eollh’, ’ lhelo’,
’ lheol’, ’ lhleo’, ’ lhloe’, ’ lhoel’, ’ lhole’, ’ lehlo’, ’ lehol’,
’ lelho’, ’ leloh’, ’ leohl’, ’ leolh’, ’ llheo’, ’ llhoe’, ’ lleho’,
’ lleoh’, ’ llohe’, ’ lloeh’, ’ lohel’, ’ lohle’, ’ loehl’, ’ loelh’,
’ lolhe’, ’ loleh’, ’ lhelo’, ’ lheol’, ’ lhleo’, ’ lhloe’, ’ lhoel’,
’ lhole’, ’ lehlo’, ’ lehol’, ’ lelho’, ’ leloh’, ’ leohl’, ’ leolh’,
’ llheo’, ’ llhoe’, ’ lleho’, ’ lleoh’, ’ llohe’, ’ lloeh’, ’ lohel’,
’ lohle’, ’ loehl’, ’ loelh’, ’ lolhe’, ’ loleh’, ’ ohell’, ’ ohell’,
’ ohlel’, ’ ohlle’, ’ ohlel’, ’ ohlle’, ’ oehll’, ’ oehll’, ’ oelhl’,
’ oellh’, ’ oelhl’, ’ oellh’, ’ olhel’, ’ olhle’, ’ olehl’, ’ olelh’,
’ ollhe’, ’ olleh’, ’ olhel’, ’ olhle’, ’ olehl’, ’ olelh’, ’ ollhe’,
’ olleh’]
Example 2.15. Write a python program to simulate a game of jumbled word. Ask the user to
enter the correct word and try for 10 times. If correct, print the user is correct with the number
of attempts. The program should print the user has lost the game, if the user has tried for 10
attempts.
# S i m u l a t e a word j umble game f o r 10 a t t e m p t s
word = " reuosc"
print (" The word in jumbled form is ", word)
print (" The game starts ")
print ("— —−− −− −− −− −− −− −− −− ")
print (" You have ten chances to type the correct word")
n = 10
attempt = 1
while n >0:
w = str( input(" enter the word "))
wrd = w. lower()
if w == " course":
print (" You are correct")
print (" Number of attempts ", attempt)
break
else:
print (" Try again")
attempt +=1
n = n− 1
if n ==0:
print(" You have lost the game")
79
OUTPUT
The word in jumbled form is reuosc
The game starts
—−−−−−−−−
You have ten chances to type the correct word
enter the word resocu
Try again
enter the word rescor
Try again
enter the word scourse
Try again
enter the word course
You are correct
Number of attempts 4
Example 2.16. Write a Python program to check whether the string starts with a particular
sequence of characters. Also check whether the string ends with a different sequence of char-
acters.
# program t h a t s t a r t s and ends with p a r t i c u l a r s t r i n g
words = [" character"," class"," remark"," channel", " miss"]
for word in words:
if word. startswith("ch"):
print(" The word starts with ch in ", word)
if word. endswith("ss"):
print(" The word ends with ss in ", word)
OUTPUT
The word starts with ch in character
The word ends with ss in class
The word starts with ch in channel
The word ends with ss in miss
Example 2.17. Write a Python program to get a sentence from the user and find the frequency
of the words. Use words and the count as keys and values, respectively.
# Count t h e f r e q u e n c y o f word i n a s e n t e n c e . Use d i c t i o n a r y
# with key as word occurren ce as value
80
OUTPUT
Enter the sentence: The cat went to the hut and
saw another cat in the same hut
Frequency of words in the sentence:
{’The’: 1, ’cat’: 2, ’went’: 1, ’to’: 1, ’the’: 2,
’hut’: 2, ’and’: 1, ’saw’: 1, ’ another’: 1,
’in’: 1, ’same’: 1}
Example 2.18. Write a Python program to get the digit in number and print the corresponding
letters. Use dictionary.
# Get t h e d i g i t from t h e user and p r i n t t h e
# c o r re s p o n d in g number i n l e t t e r s . Use d i c t i o n a r y
n_dict = {0:" Zero",1:" One",2:" Two",3:" Three",
4:" Four",5:" Five",6:" Six",7:" Seven",
8: " Eight", 9: " Nine"}
n = int( input(" Enter the number from 0 to 9: "))
print (" The entered number is ", n)
for i,j in n_dict. items():
if i == n:
print ("In letters ", n_dict[i])
OUTPUT
Enter the number from 0 to 9: 9
The entered number is 9
In letters Nine
Example 2.19. Write a Python program to find the unique values in a dictionary.
#print unique values in a d i c t i o n a r y
dict1 = {"a":199 ,"b":299 ,"c":399 ,"d":199 ,"e":299}
print (" The dictionary is ")
print ( dict1 )
values = []
for key, value in dict1 . items():
values = values + [ dict1 [ key]]
print (" The values from dictionary are ", values)
unique_values = set( values)
print (" The unique values are ", unique_values)
OUTPUT
The dictionary is
{’a’: 199 , ’b’: 299 , ’c’: 399 , ’d’: 199 , ’e’: 299}
The values from dictionary are [199 , 299 , 399 , 199 , 299]
The unique values are {399 , 299 , 199}
81
Example 2.20. Write a Python program to sort the dictionary according to the values. Use any
relevant library.
# S o r t by value
from collections import Counter
dict1 = {"a":499 ,"b":299 ,"c":399 ,"d":199 ,"e":99}
X = Counter( dict1 )
print (" The dictionary is ")
print ( dict1 )
print (" The sorted values are ")
print (X. most_common())
OUTPUT
The dictionary is
{’a’: 499 , ’b’: 299 , ’c’: 399 , ’d’: 199 , ’e’: 99}
The sorted values are
[(’a’, 499), (’c’, 399), (’b’, 299), (’d’, 199), (’e’, 99)]
Summary
1. Lists in Python are ordered, mutable and can have duplicate elements.
2. Tuple is a collection that are ordered and non mutable. It can have duplicate elements.
3. Set is a collection that is unordered and not indexed. It does not have duplicate elements.
4. Dictionary is a collection that is unordered and mutable. It cannot have duplicate key
elements.
82
Learning Outcomes
On completion of this chapter, you should be able to:
3. Program using Sets for mathematical and other real world problems.
Chapter Exercises
Multiple Choice Questions
1. What is the range of index values for the values from 1 to 10.
(a) 0 to 9
(b) 0 to 10
(c) 1 to 10
(d) 1 to 9
(a) retreive
(b) delete
(c) interleave
(d) append
(a) 10,20,30,40,
(b) 20,10,30,40,
(c) 30,40,10,20,
(d) 30,40,20,10,
83
(a) 10,20,30,
(b) 10,20,30,40,
(c) 10,30,20,
(d) 30,40,20,10,
5. For nums = [12,4,11,23,18,41,27], what is the value of k when the loop terminates?
k = 0
while k< len( nums) and nums [k]!=18:
k = k+1
(a) 3
(b) 4
(c) 5
(a) strings
(b) lists
(c) tuples
7. Which of the following is the correct way to denote a tuple of one element?
(a) 9
(b) (9)
(c) (9,)
(d) 9
84
10. Which of the following can be used as a key in Python dictionaries?
(a) Strings
(b) Lists
(c) Tuples
(d) Range of Numerical values
(a) a
(b) “apple”
(c) “banana”
(d) “abc”
85
14. What is the output of the following segment?
>>> t1 = (100 ,200 ,300)
>>> t1 [1] = 2
>>>t1
(a) Error
(b) (100,2,300)
(c) 2
(d) 200
15. What happens with (66, 4, 17, 4) < (66, 4, 16, 5)?
(a) True
(b) False
Descriptive Questions
1. What happens to the memory location when you assign a variable to another variable?
2. What happens to the memory location when you assign a list to another list without
slicing operator?
3. What happens to the memory location when you assign a list that has a nested list with
slicing operator?
4. What happens to the memory location when you use the module deepcopy to copy the
items from one list to another?
10. How will you convert the string to a list and vice-versa?
11. With examples, explain the data structure of dictionary. How is it iterated?
86
Programming QuestionsList
1. Write a python program to find the square of all numbers in the list.
4. Write a python program to print all even and all odd numbers in the list.
Tuple
1. Write a python program to find the size of the tuple.
2. Write a python program to find the maximum and minimum k elements in tuple.
Sets
1. Write a Python program to create a set.
5. Write a Python program to remove an item from a set if it is present in the set.
87
6. Write a Python program to create an intersection of sets.
14. Write a Python program to find maximum and the minimum value in a set.
17. Write a Python program to check if two given sets have no elements in common.
18. Write a Python program to check if a given set is superset of itself and superset of another
given set.
19. Write a Python program to find the elements in a given set that are not in another set.
20. Write a Python program to check a given set has no elements in common with other given
set.
21. Write a Python program to remove the intersection of a 2nd set from the 1st set.
Strings
1. Write a program that counts the occurrences of a character in a string. Do not use use
built-in functions.
3. Write a program to parse an email id such that it has only the date and time.
5. Write a program that prints only words that starts with a vowel.
6. Write a program that accepts a comma separated sequence of words and print only unique
words
8. Write a program to remove the nth index character from a non-empty string.
9. Write a program to get the information as First name and Last name and print the initial
with first name.
88
10. Write a program to count the number of digits, upper case letters, lower case letters and
special characters in the given string.
11. Write a program to print the first n characters in the given string.
12. Write a program with two functions to delete the first and last characters of a string.
13. Write a python program to find the bigger length of two strings
17. Write a python program to create a password with different types such that the entered
value should be not less than six characters long and should have an integer and special
character.
References
• Reema Thareja, Python Programming using Problem Solving Approach, Oxford Univer-
sity Press, 2019
• Charles Dierbach, Introduction to Computer Science using Python A Computational
Problem-Solving Focus, Wiley Publications, 2015
• https://www.w3schools.com/python/python_datatypes.asp
• https://openbookproject.net/thinkcs/python/english3e/varia
bles_expressions_statements.html
• https://openbookproject.net/thinkcs/python/english3e/funct
ions.html
• https://openbookproject.net/thinkcs/python/english3e/itera
tion.html
• https://openbookproject.net/thinkcs/python/english3e/strin
gs.html
• https://openbookproject.net/thinkcs/python/english3e/lists
.html
• https://openbookproject.net/thinkcs/python/english3e/tuple
s.html
• https://openbookproject.net/thinkcs/python/english3e/recur
sion.html
Following links give some references of day to day applications/ modules that use list,
tuples, sets and strings
• https://www.programiz.com/python-programming/directory
• https://www.tensorflow.org/
• https://scikit-learn.org/stable/
• https://www.nltk.org/
89
CHAPTER - 3
CONTENTS:
LEARNING OBJECTIVES
Files
File Path
File Position
Exception handling
Multiple Exceptions
Summary
Learning Outcomes
Chapter Exercises
References
Learning Objectives
90
• To read and write external files through Python Program
• To perform different string operations in text files through Python Program
• To introduce exception error handling
• To write efficient programs without errors
In this Chapter, you will see how external files can be accessed with Python in Section 3.1.
Since the language supports string extensively, you will see many examples with respect to
text files. Apart from files, you will study about the class of errors that can be caught while
programming. These are called Exceptions, which are provided in Section 3.2.
Files
To open a file from your folder, you will probably follow these steps.
• First navigate to that folder
• Select the file with mouse and click
Alternately, you can also open the file with a command by ‘cd’ to the specific folder and then
type the name of the file with an extension. Assuming the file is a text file, you can edit the text
and save it for future use. All these operations can be done using Python.
File path
A file path is the location of the file and it generally constitutes three parts:
Folder path, that provides the location of the folder or directory.
File name
Extension of the file
The path in Windows and Linux Environment folder path differ. Suppose you have a text
file named ‘test.txt’ in Desktop, then the path for this file through Windows will be similar to
‘C:/Users/tom/Desktop/test.txt’, assuming ’tom’ is the user.
In Linux, the file path is ‘/home/tom/Desktop/test.txt’.
This path is important and should be specified when working with files in Python. When
talking about files, two types of files can be classified.
1. Textfiles containing characters with a common structure of a single line (sentence). When
you read the text you understand that one sentence through the mark of full-stop. In
Python, the mark is through a newline character \n.
2. Binaryfiles contain binary data, which can be recognized only by machine.
91
‘file_variable’ indicates the specific file which can be referred in the program. This vari-able can be
linked to the file object.
‘file_name’ indicates the name of the file
‘access_mode’ denotes the mode the file is to be accessed such as read, write, append
etc.
‘buffering’ is optional. If set to 0 no buffering occurs. Default is -1, which is the system
buffer size.
‘file_variable’ indicates the specific file which can be referred in the program. This
vari-able can be linked to the file object.
‘file_name’ indicates the name of the file
‘access_mode’ denotes the mode the file is to be accessed such as read, write, append
etc.
‘buffering’ is optional. If set to 0 no buffering occurs. Default is -1, which is the system
buffer size.
4. ‘rb+’ - opens a file for both reading and writing in binary format.
7. ‘w+’ - opens a file for reading and writing. It overwrites the existing file and creates a
new file.
8. ‘wb+’ - opens a file for reading and writing in binary format. Like ‘w+’, it creates a new
file if it does not exist. If exists, the file overwrites with the information.
12. ‘ab+’ - Opens the file for appending and reading in binary format.
Once the file is opened through the ‘file_name’ variable, it can be used with different meth-
ods such as:
92
These methods are illustrated in the following example. The file ‘course.txt’ is located in
the same folder where this python code also resides. The first line specifies the opening of
the file with the access mode of ‘a+’ and different objects are called. Try these with
different access methods.
OUTPUT
Check whether the file is open or closed: False
Access mode of the file: a+
Name of the file: course. txt
To close a file, filename.close() can be used as shown in the following example.
f = open(" course. txt",’a+’)
f. close()
print (" Check whether the file is closed ", f. closed)
OUTPUT
Check whether the file is closed True
The files can be opened using with keyword also. If this is used, you need not explicitly close
the file. An example is given below.
with open(’ course. txt’,’r’) as file:
for line in file:
print( line)
OUTPUT
This is a file to experiment with python handling.
93
If there are multiple lines, use filename.readlines() to read line by line.
To write the content to the file, use filename.write() with appropriate access method.
An example is shown below, which write the statement to the file ‘course.txt’.
f = open(" course. txt",’a+’)
str = " Python supports text files extensively. "
f. write( str)
print (" The content is written to the file")
f. close()
File Position
When reading files, a specific pointer to the file position can be created using the methods tell
and seek. The tell method gives the current position within the file. The seek method has the
syntax of (offset,from), where ‘offset’ indicates the position in terms of bytes to be moved
and ‘from’ indicates the reference position from where the bytes are moved. Consider the
example below. Here, read(10) indicates 10 bytes to be read. Now, the variable of position1
is assigned to this number through ‘f.tell()’. The position1 is given as offset value to ‘seek’ with
‘from’ value as 0. According to these positions, the text is displayed as shown in the output.
Try varying the values instead of 10, ‘offset’ and ‘from’ and check for yourself.
# opening file
f = open(" course. txt",’r+’)
str = f. read(10)
print (" Reading 10 characters from file ..... ")
print( str)
print ("−− −− −− −− −− −− −− ")
#close the f i l e
f. close()
94
Reading 10 characters from file ........
This is a
—−−−−−−
The current file position: 10
—−−−−−−
Reading again ...
OUTPUT
enter any integer to find the square of the number 6
The square of the number is 12
Another class of programs pass syntax error but throw errors like ‘type error’ which include
‘divide by zero’. These types of errors are already built in so that these can be easily surpassed
in a program. For example, the math module has a factorial function that calculates the factorial
of integers. But when -1 is entered, Value error arises as shown below.
# program d e m o n s t r a t i n g Value error
import math
n = int( input(" enter any integer to find the factorial
of a number "))
print (" The factorial of the number is ", math. factorial(n))
OUTPUT
enter any integer to find the factorial of a number − 1
Traceback ( most recent call last):
File " exception_error1 .py", line 4, in <module >
95
print (" The factorial of the number is ", math. factorial(n))
ValueError: factorial() not defined for negative values
These types of exception can be well handled within a program.
Exception handling
Exception can be handled using the blocks try, except and finally. The exceptions can be
defined either by the programmer or can be caught from the errors from Python such as Value
error. To start with, see what happens when you type print(n) and execute. You will see this
error.
OUTPUT
Traceback ( most recent call last):
File " exception_error2a.py" , line 1, in <module >
print(n)
NameError: name ’n’ is not defined
This error can be handled within Program using try and except.
try:
print(n)
except:
print("An exception occured because the variable is not assigned")
OUTPUT
An exception occured because the variable is not assigned
Multiple Exceptions
You can define multiple blocks to find the particular error.
try-except-except
Continuing with the same example, here two blocks are provided with exception. First, the try
block executes and if this fails, the next except block executes and if successful, prints the
message. Else the next except message gets executed.
try:
print(n)
except NameError:
print(" Variable not defined")
except:
print(" Something else is wrong")
OUTPUT
Variable not defined
96
try-except*-else
If nothing went wrong and you want to check that, you can include else as shown below.
try:
n = 5
print(n) except
NameError:
print(" Variable not defined")
except:
print(" Something else is wrong")
else:
print(" Nothing is wrong")
OUTPUT
5
Nothing is wrong
try-except*-else-finally
finally is executed regardless of other blocks being executed. See the example below. Here,
the blocks try, except nameError and finally are executed.
try:
#n = 5
print(n)
except NameError:
print(" Variable not defined")
except:
print(" Something else is wrong")
else:
print(" Nothing is wrong")
finally:
print(" relevant blocks are executed")
OUTPUT
Variable not defined
relevant blocks are executed
raise exception
A keyword of raise can be used in the program to indicate that the error will occur. In the
following example, the exception is raised if string is used instead of integers.
n = " abc"
if not type(n) is int:
raise TypeError(" Enter only integers")
97
Traceback ( most recent call last):
File " exception_error5 .py", line 3, in <module >
raise TypeError(" Enter only integers")
TypeError: Enter only integers
Here, you have seen an example of NameError. This is a built-in exception available in Python.
A few other exceptions are given in Table 3.1.
Example 3.1. Write a Python program to display the contents of the file in the form of list.
# program to display the contents of f i l e in list .
f = open(’ course. txt’,’r’)
print ( list(f))
f. close()
OUTPUT
[’This is a file to experiment with python handling.\n’,
’ Python supports text files extensively. ’
98
Example 3.2. Write a program to split the words and count the number of words in each
sentence in the file.
OUTPUT
Actual Sentence: This is a file to experiment with python handling.
Number of words = 9
Actual Sentence: Python supports text files extensively.
Number of words = 5
Example 3.3. Write a Python program to copy the file to another file.
OUTPUT
File is copied to file2
In this example, the contents of course.txt is copied to copied.txt.
99
Example 3.5. Write a Python program to create a directory named as ‘tenfiles’. Within that 10
files, create 10 textfiles with names file0, file1, ...,file10. In each of these files, write the text
content - ‘This is file 1’, ‘This is file 2’ appropriately.
# c r e a t e 10 t e x t f i l e s i n a new d i r e c t o r y and e n t e r t h e s t r i n g
# " This i s f i l e 1 , This i s f i l e 2 , . . " i n each o f t h e f i l e s import
os
directory = " tenfiles"
os. mkdir( directory)
for i in range(11):
fname = " tenfiles/ file"+str(i)
with open( fname ,’w+’) as f:
content = " This is file " + str(i)
f. write( content)
OUTPUT
#delete a file
import os os.
remove(" copied. txt")
print (" The text file named copied. txt is removed")
OUTPUT
The folder can be checked for the file ’copied.txt’ which no longer exists after the execution of
this code.
10
Example 3.7. Write a Python program to count the number of tabs, spaces and newline char-
acters in a string. The poem.txt has these contents.
The song I came to sing
remains unsung to this day.
I have spent my days in stringing
and in unstringing my instrument.
OUTPUT
Tabspace = 1
Spaces = 42
newlines = 10
Example 3.8. Write a Python program to take a text file from URL and save those to a text
file.
# copy the text content from u r l t o a f i l e
import urllib. request
10
file = open(’ urltext’,’w+’)
file. write( str( data))
file. close()
print (" The content is written")
OUTPUT
The content is written
Example 3.9. Write a Python program to copy the file in such a way that the words in each
sentence is reversed.
# program t o copy t h e contents o f one f i l e t o anot her with
# r e v e r s a l words
with open(’ course1 . txt’,’r’) as file1 :
with open (’ copied. txt’,’a+’) as file2 :
text = file1 . readlines()
for line in text:
words = line. split()
words. reverse()
reverse_sent = " ". join( words)
print ( reverse_sent)
file2 . write( reverse_sent)
file2 . write(’\n’)
OUTPUT
line. first the is This
line. second the is This
line. third the is This
Example 3.10. Write a Python program to print a random line from a text file.
import random
with open (’poem. txt’,’r’) as file:
lines = file. readlines()
print ( random. choice( lines))
OUTPUT
and in unstringing my instrument.
10
Example 3.11. Write a Python program to demonstrate divide by zero error through excep-
tion.
def divide(nr,dr):
try:
quotient = nr/dr
except ZeroDivisionError:
print(" You cannot divide a number by 0")
n = 10
divide(n,0)
OUTPUT
You cannot divide a number by 0
Example 3.12. Write a Python program to demonstrate index error in a list. (Index error arises
when the index value is out of range).
#demonstration o f i ndex error
def count( list1 ):
print(" The number of elements in list ", len( list1 ))
try:
last_element = list1 [3]
except IndexError:
print(" Index value should be less than 3")
OUTPUT
The number of elements in list 3
Index value should be less than 3
103
n = ’ 15.64 ’
gettype(n)
OUTPUT
The actual type is of 15.64 is <class ’str’>
Now, try convert this type to int
Throwing exception .....
String cannot be converted to integer value
Example 3.14. Write a Python program to raise an exception for the values of month. In other
words, if the user enters the value other than 1 to 12, the program should raise an exception.
# g e t t h e i n p u t o f 1 t o 12 f o r month . Else r a i s e e x c e p t i o n
month = int( input(" Enter the month in values from 1 to 12 "))
if month < 1 or month > 12:
raise ValueError(" Enter only values between 1 to 12")
else:
print(" The value of month is ", month)
OUTPUT
Enter the month in values from 1 to 12 − 2
Traceback ( most recent call last):
File " month.py", line 4, in <module >
raise ValueError(" Enter only values between 1 to 12")
ValueError: Enter only values between 1 to 12
OUTPUT
^CCaused by KeyboardInterrupt
104
Example 3.16. Write a Python program to write to file and raises an IOError exception.
# f i l e input output err or
try:
# The access mode o f t h e f i l e i s read ,
# but t h e c o n t e n t i s t o be w r i t t e n .
# So , exception o f IOerror b l ock gets executed
with open("eg. txt",’r’) as file:
file. write(" Adding a new statement. ")
except IOError:
print (" Error working with file ")
else:
print (" Written the statement to file")
OUTPUT
Error working with file
Example 3.17. Write a Python program to print the values infinitely. Then call an exception
of StopIteration to print only upto 10 natural numbers.
# i l l u s t r a t i o n of S t op It e r a t io n
def add( num):
while True:
try:
num = num + 1
if num == 11:
raise StopIteration
except StopIteration:
break
else:
print( num)
x = 0
add(x)
1
2
3
4
5
6
7
8
105
9
10
106
except IOError:
print (" Error working with file ")
else:
print (" Written the statement to file")
OUTPUT
Error working with file
Example 3.17. Write a Python program to print the values infinitely. Then call an exception
of StopIteration to print only upto 10 natural numbers.
# i l l u s t r a t i o n of S t op It e r a t io n
def add( num):
while True:
try:
num = num + 1
if num == 11:
raise StopIteration
except StopIteration:
break
else:
print( num)
x = 0
add(x)
1
2
3
4
5
6
7
8
9
10
107
Example 3.18. Write a Python program to illustrate overflow exception. This exception occurs
when the value is out of range.
# i l l u s t r a t i o n of overflow exception
import math
try:
n = math. exp(863)
except OverflowError:
print(" Overflow exception is raised. ")
else:
print (" Success , the value of e^(863) is ", n)
OUTPUT
Overflow exception is raised.
If the value is changed from 863 to 5, the output Success, the value of eˆ
(5) is
7.225973768125749e+86 occurs.
n = −5
try:
assert n > 5
print(" number is positive")
except AssertionError:
print(" Assertion error exception raised")
OUTPUT
Assertion error exception raised
OUTPUT
5
Exception raised
108
Summary
Text files and binary files can be handled with Python extensively.
Files can be accessed through the file path in any operating system by
importing os
module.
Each files ends with end-of-file marker, which can be used for programming.
open() method creates file object
close() method closes the file. However if withkeyword is used, close() is not
necessary.
Read, Write and Append access methods are available for both text and
binary files.
tell() and seek() methods provide the location of file pointer information
Exceptions can be handled −using try except block.
Several built-in methods of exception can be integrated while programming.
User defined exceptions are also possible to catch exception.
Multiple blocks of exception can be used to find the exact error.
Learning Outcomes
After reading and working out the examples in this chapter, you should be able to:
Chapter Exercises
Multiple Choice Questions
1. To access files, this function is used.
(a) access()
(b) open()
(c) read()
(d) write()
109
2. To close a file, you use
(a) close(file)
(b) file.close()
(c) cl.file
(d) file.close
3. To get the entire contents of the file, you use the method
(a) file.read()
(b) file.access()
(c) file.read
(d) read(file)
(a) r
(b) rw
(c) w+
(d) b
6. When you open a file for reading, the file pointer is located at location
(a) 0
(b) 1
(c) 2
(d) k
110
8. In the seek method, the reference postion of from at the current position of the file is at
(a) 0
(b) 1
(c) 2
(d) -1
9. An exception is a
(a) module
(b) object
(c) procedure
(d) method
(a) IOError
(b) NameError
(c) AssignmentError
(d) ValueError
11. Which of the following errors executes the program but gives wrong results?
(a) Exception
(b) Logical Error
(c) Syntax Error
(d) None of these
(a) try
(b) except
(c) catch
(d) raise
(a) raise
(b) throw
(c) assert
(d) print
111
14. Which of the following blocks handle exception?
(a) try
(b) except
(c) finally
(d) def
(a) TypeError
(b) ValueError
(c) True
(d) False
(a) try
(b) except
(c) finally
(d) except-else
Descriptive Questions
1. What are files? How are those handled in Python?
3. What are the different access modes in Python? Explain any five with examples.
112
14. Explain any three built-in exceptions with examples.
Programming Questions
1. Write a Python program to read a text file and count the number of particular words in
the file.
2. Write a Python function to read a text file and display the words starting with the letter
’R’.
4. Write a Python Program to combine two text files and place in the third file.
5. Write a Python program to read all the contents from one file. Then copy into another
file with the conversion of lower-case to upper-case.
6. Write a Python program to enter details into two files separately and merge those.
7. Write a Python program to read the file. From the content, count the number of articles.
Copy the file to another file, remove the articles.
8. Write a Python program to append the content to an already available text file and display
those.
10. Write a Python program to find the longest word in the text file.
12. write a Python program to remove a newline character from the file.
13. Write a Python program to extract the characters from the text file and include those in a
list.
14. Write a program to find the square root of a number. If the number is negative, raise an
assertion error.
15. Write a program to get the input of a number from the user. If the user enters a string
value, the program should catch the error through an exception.
16. Write a program that validates the user’s name with an initial as fullstop. If ’fullstop’ is
not entered by the user, the program should raise an exception.
18. Write a program to add the even numbers to the list infinitely. Raise an exception such
that the list should store only 20 even numbers.
19. Consider the list [20,30,40,80]. Ask the user to get the index value and display the
113
corresponding element. Add an exception such that the user can only give the index
values from this list.
114
CHAPTER - 4
LEARNING OBJECTIVES
Modules
Creating your own module
Module Loading and Execution
Packages
The Python Libraries for data Processing, Data Mining and Visualization
Numpy
Pandas
Matplotlib
Worked Out Programming Problems
Summary
Learning Outcomes
Chapter Exercises
Multiple Choice Questions
Descriptive Questions
Programming Questions
References and External Learning
Learning Objectives
To understand how external modules can be imported.
To create a customized module.
To develop a package with Python programs.
To use numpy, pandas and plotting libraries in Python.
Modules
Modules are small pieces of code, which can be collectively put together for a common purpose.
To give an analogy, assume how the construction of a simple chair takes place. The legs,
handles and body of the chair have to be built separately and then assembled together. In
a similar way, when you are writing a program it is always a good practice to separate into
smaller chunks of code that does a specific job. These smaller chunks of code constitute a
module. Here are a few advantages to use modules in programming.
115
1. Portability: Each module constitute a specific function or functions, which are smaller in
size.
Python provides an efficient way of importing and create modules. A Python module consti-
tutes definition and statements. By default, a python program that is executed is considered to
be a main module of the program. These are given a special name main . These provide
the basis for the entire program and include other modules too.
The standard library of Python has a set of pre-defined standard modules, some of which
you have used already like math, random and os.
# prog 2 . py
import simple
print( simple. function2 ())
On execution of these programs, you will notice that the print statement from simple.py is
printed as shown below.
116
OUTPUT from prog1 .py
module simple loaded
function1 called
OUTPUT from prog2 .py
module simple loaded
function2 called
To see all functions in the module, dir(modulename) is used. For example, prog1.py is
modified as shown below to include dir(simple).
# prog 1 . py
import simple
print ( dir( simple))
print( simple. function1 ())
The output of (dir(simple)) lists all the functions as listed below, which include both in-built
and user defined functions.
OUTPUT
module simple loaded
[’ __builtins__’, ’ __cached__’, ’ __doc__’, ’ __file__’, ’
__loader__’, ’ __name__’, ’ __package__’, ’ __spec__’, ’
function1 ’, ’ function2 ’]
function1 called
Python provides an alternate import constructs in the form
from modulename import something and import modulename as somename. The first
construct instructs the particular function or variable to be imported and the second specifies
the name of module as something else. An example of the first construct is explained below.
Consider the example of finding a total of three numbers in a list. The function of total is
stored in ‘totavg.py’ as:
# module
def total(l1 ):
tot = l1 [0]+l1 [1]+l1 [2]
return tot
This file acts as a module and can be used by other programs. Here, the following program
imports the above program using from totavg import total line. The values of 5,6
and 7 are passed to the function located at totavg. In the line print (total(list1)), note
that total(list1) is used, which indicates the function from line 2.
1. # t o t a l . py
2. from totavg impo rt total
3. list1 = [5 ,6 ,7]
4. print(" Sum of the numbers of ", list1 )
5. print ( total( list1 ))
117
OUTPUT
Sum of the numbers of [5, 6, 7]
18
Like functions, the variables from the module can also be called. Consider the module
named student.py which stores the details of student as:
# s t u d e n t . py
person = {" Rollnumber": 250123 , " Name": " Tamil Selvan", " Course":" MCA"}
num = 50
From another program, the name of this person can be accessed as:
# prog 3 . py
from student import person
print (" Printing the name of the person from Student module ")
print ( person[" Name"])
OUTPUT
Printing the name of the person from Student module
Tamil Selvan
Note here that ‘person’ is the variable from module student.
Change the import statement to from student import person as st and accordingly
change the last line to print(st[‘‘Name’’]). See the result for yourself.
Other alternatives of import statements in Python are
from modulename import function1, function2, which imports two functions from the
module and from modulename import *, which imports all functions from module.
Namespace in Python provides an efficient way to address the identifier. Using namespace
avoids the nameclash incase the same identifier is used. For example, consider two modules
module1.py and module2.py which have the same function double, but different functionality.
# module 1
def double( num):
print ( num * 2)
# module 2
def double( num):
print (num, num)
The main program hence will have a nameclash. In such cases to identify the specific func-
tion from a module, the namespace is specified through a module in the form of
modulename.function. For this example, the namespaces are module1.double() and
module2.double().
118
import module1
import module2
print ( module1 . double(5))
print ( module2 . double(5))
OUTPUT
10
None
5 5
the subsequent execution which saves computational time in loading again. If the module is
modified, accordingly the compiled files also gets updated.
Packages
When you are developing a software, you will have to create many programs as modules. To
bundle up these, a package is required so that the relevant modules are in one place. Python
provides an efficient way of packaging and distributing across different platforms.
Here, you will understand how to develop a package with multiple modules. For simplicity,
Two modules namely, add.py and subtract.py can be considered as follows.
# a d d i t i o n module
def ad(n1 ,n2 ):
print(" Addition of two numbers ", n1 , n2 , " ", n1+n2)
119
# s u b t r a c t i o n module
def subtraction(n1 ,n2 ):
print(" Subtraction of two numbers ", n1 , n2 , " ", n1−n2)
To execute, one way is to call these modules from another program such as calc.py, which is
located where the two modules add.py and subtract.py are located.
# c a l c . py
from add import ad as total
from subtract import subtraction
a = 10
b = 5
total(a,b)
subtraction(a,b)
On executing this program, you will get the following output.
Addition of two numbers 10 5 15
Subtraction of two numbers 10 5 5
To bundle up all the modules and other information, you can use packaging mechanism.
To create a package in Python, first a directory should be created where the modules are to be
placed. Along with the modules, an empty file with init .py should be included. This
file indicates that the package is in place. The structure of the example files looks like:
package
|
| ---- init .py
|
| ---- add.py
|
| ---- subtract.py
First create a directory named ‘package’ and within that place the modules ‘add.py’ and ‘sub-
tract.py’. Along with that, create an empty file called init .py. Now, outside the
directory have a python file with these information.
1. from package import add , subtract
2. a = 100
3. b = 80
4. add.ad(a,b)
5. subtract. subtraction(a,b)
The first line denotes the package directory to be considered as package and import the modules
add and subtract. There are other variants of import statements which can also be included.
Line 3 and Line 4 indicate the modules to be executed from the package. The output of running
this program is shown below.
120
Addition of two numbers 100 80 180
Subtraction of two numbers 100 80 20
Numpy
Numpy is a library to perform numerical computations with ready made functionalities, par-
ticularly in the form of matrices. It stands for Numerical Python. This library is also op-
timized to work with various CPU architectures. First you have to install numpy. Refer
https://pip.pypa.io/en/stable/installing/ to install pip and through
that you have to install numpy with the command pip install numpy.
With numpy, following topics are discussed.
Creating Array
Iterating Arrays
Creating Array
An array can be created using an array keyword. In the following example, an array of integer
numbers [2, 4, 6, 8] is created.
>>> import numpy as np
>>> a = np. array([2 ,4 ,6 ,8])
>>> a
array([2 , 4, 6, 8])
The first line indicates the module numpy imported as np. This is then used in the second line
to convert to an array. Note that the array is represented with a tuple and then square bracket. If
only square bracket is given, it will lead to an error. Arrays are declared using dtype, which
are different from the data structure of list. Manipulations with arrays are faster than that of
looping within lists.
121
>>> a = np. array([200 ,400 ,600])
>>> a
array([200 , 400 , 600])
>>> type(a)
<class ’ numpy. ndarray’>
1-D, 2-D and higher dimension arrays can be created with numpy. Example of creating 2-D
and 3-D arrays are shown below.
# Example o f 2 —D and 3 −D array
import numpy as np
# c r e a t i o n o f 2 − d array
arr = np. array([[1 ,2 ,3],[4 ,6 ,8]])
print( arr)
# shape
print( arr. shape)
# creation o f 3 − d array
arr2 = np. array([[[1 ,2 ,3],[4 ,5 ,6]],[[7 ,8 ,9],[10 ,11 ,12]]])
print ( arr2 )
print ( arr2 . shape)
print ( arr2 . ndim)
[[ 7 8 9]
[10 11 12]]]
The shape of an array is (2, 2, 3)
The dimension of array is 3
You can create an array with zeros or 1 instantly. See these examples below.
>>> m2 = np. zeros(4)
>>> m2
array([0., 0., 0., 0.])
>>> m3 = np. ones(4)
>>> m3
array([1., 1., 1., 1.])
>>> m5 = np. zeros((3 ,5)) # Creat i ng a 3X5 mat ri x
>>> m5
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
122
To have values within a range arange can be used. In the following example, an array of
numbers in the range 2 to 20 in the steps of 2 is shown below.
123
Here is another example of converting a 3X2 array to 6X1.
>>> import numpy as np
>>> m2 = np. array([[1 ,2 ,3],[4 ,5 ,6]])
>>> m2
array([[1 , 2, 3],
[4, 5, 6]])
>>> np. reshape(m2 ,6)
array([1 , 2, 3, 4, 5, 6])
Iterating Arrays
Like lists and tuples, the array can be iterated. An example is shown below.
>>> import numpy as np
>>> m2 = np. array([[1 ,2 ,3],[4 ,5 ,6]])
>>> for i in m2:
print(i)
[1 2 3]
[4 5 6]
numpy provides a way to enumerate through indexes. The keyword to indicate the index is
ndenumerate as shown below.
>>> import numpy as np
>>> m2 = np. array([[1 ,2 ,3],[4 ,5 ,6]])
>>> for idx,x in np. ndenumerate(m2 ):
print(idx,x)
(0, 0) 1
(0, 1) 2
(0, 2) 3
(1, 0) 4
(1, 1) 5
(1, 2) 6
Pandas
Pandas is a python library for working with large datasets. It is used widely to analyse data. It
can be installed using the command of pip3 install pandas. In this section, you will
see some introductory material of how data are read through the structure of dataframe, getting
the data through csv format and performing standard operations like maximum, minimum and
average values of data.
A dataframe in Pandas is a two dimensional structure. Suppose, we have two columns of
data with food and calories. Each column can represented as a list and the whole data as a
dictionary. These are converted to a dataframe through Pandas as shown below.
124
import pandas as pd # i m p o r t i n g t h e mo d u le p a n d a s
data = {" fruits": [" apple", " apricot"," grapes", " lemon"],
" calories":[95 ,17 ,62 ,17]}
df = pd. DataFrame( data)
print(df)
OUTPUT
fruits calories
0 apple 95
1 apricot 17
2 grapes 62
3 lemon 17
To select the row, you can use loc[0]. Add an extra line in the above program as
print(df.loc[0]) and check for yourself. To read csv files, you can use
pd.read_csv(<filename>). An example is shown below, assuming the same data
OUTPUT
fruits calories
0 apple 95
1 apricot 17
2 grapes 62
3 lemon 17
Determination of sum, average, maximum and minimum of data is straight forward indicated
by the respective column title. For the same example, the code is given below.
import pandas as pd
data = pd. read_csv(’ fruits. csv’)
df = pd. DataFrame( data)
print(df)
print ("— —−− −− −− −− −− −− −− −− −− −− ")
print(" Sum: ",df[" calories"]. sum())
print("Mean: ",df["calories"].mean())
print("Maximum: ",df["calories"].max())
OUTPUT
125
fruits calories
0 apple 95
1 apricot 17
2 grapes 62
3 lemon 17
—−−−−−−−−−−
Sum: 191
Mean: 47.75
Maximum: 95
Minimum: 17
Matplotlib
Matplotlib is a plotting library that is predominantly used. You can install this library by the
command pip3 install matplotlib. Here, an example is shown below to plot data
with two functions y = 2 ∗ x and y = x2.
import numpy as np
import matplotlib. pyplot as plt
x = np. arange(0 ,10) # v a l u e s i n x a x i s
y = 2* x # double x
z = x* x # x squared
print("x values are", x)
print("y values are", y)
print("z values are", z)
# Give t h e t i t l e
plt. title("An example plot")
# Name x and y a x i s
plt. xlabel("x")
plt. ylabel("y")
# p l o t x with y and x with z
plt. plot(x,y)
plt. plot(x,z)
# add l egend t o l ower r i g h t corner
plt. legend(["2x", "x − squared"], loc =" lower right")
plt. grid()
plt. show()
OUTPUT
x values are [0 1 2 3 4 5 6 7 8 9]
y values are [ 0 2 4 6 8 10 12 14 16 18]
z values are [ 0 1 4 9 16 25 36 49 64 81]
126
Worked Out Programming Problems
Example 4.1. Use the module of glob to print all files in the current directory
# use module g lob and print the files
import glob
for i in glob. iglob(’ * . * ’, recursive=True):
print(i)
Example 4.2. Use the module of random to print random words from the dictionary.
# g e t random words from dictionary
# h t t p s : / / www. w 3 resource . com / python − e x e r c i s e s /
# math / python — math − e x e r c i s e − 54. php
import random
with open(’/ usr/ share/ dict / words ’, ’rt’) as f:
# change t h i s d i r e c t o r y i f u s i ng windows
words = f. readlines()
words = [w. rstrip() for w in words]
for w in random. sample( words , 7): # p r i n t i n g 7 random words
print(w)
OUTPUT
Isabelle’s
fanboys
trussed
Bishkek’s
councilmen
Cognac
sureness’s
127
Example 4.3. Use the module of time to print the execution of program to find the sum of first
10,000 numbers.
# get execution t ime o f a program
import time
start_time = time. time()
s = 0
for i in range(1 ,10000): s
= s+i
print(" sum of 10 ,000 numbers: ", s)
end_time = time. time()
duration = end_time − start_time
print (" time for execution of adding 10000 numbers is ",
duration , " seconds")
OUTPUT
sum of 10 ,000 numbers: 49995000
time for execution of adding 10000 numbers
is 0.0009145736694335938 seconds
Example 4.4. Use the module of urllib and read the data from internet.
Example 4.5. Write a python program with a main program having a number. Have two
modules for calculating the number two times and square of the number.
# main program calling sqr and t w i c e function
from double import twice
from sq import sqr
n = 6
print(" Entered number is ", n)
print(" Twice the number is", twice(n))
print(" Square of the number is", sqr(n))
as response:
# double . py
def twice (n):
return 2*n
128
# square f u n c t i o n sq . py
def sqr (n):
return n* n
OUTPUT
Entered number is 6
Twice the number is 12
Square of the number is 36
Example 4.6. Create a Vector with first 6 numbers and print the dimension. Convert it to an
array of 2X3.
# c r e a t i o n o f v e c t o r with f i r s t 6 v a l u e s and p r i n t t h e d imen sion .
# Convert i t t o mat ri x o f 2X3
import numpy as np
m1 = np. arange(1 ,7)
print(" The vector is", m1)
print(" The shape is ", m1. shape)
m2 = m1. reshape(2 ,3)
print(" Converted to 2X6: ", m2)
print(" The shape of m2 is ", m2. shape)
OUTPUT
The vector is [1 2 3 4 5 6]
The shape is (6 ,)
Converted to 2X6: [[1 2 3]
[4 5 6]]
The shape of m2 is (2, 3)
Example 4.7. Create a 3X3 identity matrix
# c r e a t e a 3X3 i d e n t i t y mat ri x
import numpy as np
z = np. eye(3)
print(z)
OUTPUT
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.
129
Example 4.8. Create a 3X3 matrix with random values.
# c r e a t e a 3X3 mat ri x with random v a l u e s
import numpy as np
z = np. random. random((3 ,3))
print(z)
Example 4.10. Write a Python Program to add and subtract two matrices.
130
print (" matrix 1 \n", m1)
print (" matrix 2 \n", m2)
m3 = m1+m2
print(" Addition of two matrices \n", m3)
m4 = m1 − m2
print(" Subtraction of two matrices \n", m4)
OUTPUT
matrix 1
[[13 45 67]
[ 2 4 89]
[45 67 89]]
matrix 2
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
Addition of two matrices
[[14. 46. 68.]
[ 3. 5. 90.]
[46. 68. 90.]]
Subtraction of two matrices
[[12. 44. 66.]
[ 1. 3. 88.]
[44. 66. 88.]]
Example 4.11. Write a Python program to multiply two matrices.
OUTPUT
matrix 1
[[13 45 67]
[ 2 4 89]
[45 67 89]]
matrix 2
[[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
131
Matrix multiplication
[[125. 125. 125.]
[ 95. 95. 95.]
[201. 201. 201.]]
Example 4.12. Write a Python program to multiply the corresponding elements of two matri-
ces.
# Multiplication e l ement wise
import numpy as np
m1 = np. array([[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]])
m2 = np. array([[2 ,2 ,2],[1 ,1 ,1],[3 ,3 ,3]])
m3 = m1 * m2
print (" matrix 1 \n", m1)
print (" matrix 2 \n", m2)
print(" Multiplication of corresponding elements \n", m3)
OUTPUT
matrix 1
[[1 2 3]
[4 5 6]
[7 8 9]]
matrix 2
[[2 2 2]
[1 1 1]
[3 3 3]]
Multiplication of corresponding elements
[[ 2 4 6]
[ 4 5 6]
[21 24 27]]
Example 4.13. Write a Python program to multiply the scalar value of 5 to a matrix.
#scalar operation
import numpy as np
m1 = np. array([[1 ,2 ,3],[4 ,5 ,6],[7 ,8 ,9]])
m2 = 5
m3 = m1 *5
print (" matrix 1 \n", m1)
print (" scalar \n", m2)
print(" Multiplication of matrix by scalar \n", m3)
OUTPUT
matrix 1
[[1 2 3]
[4 5 6]
[7 8 9]]
scalar
132
5
Multiplication of matrix by scalar
[[ 5 10 15]
[20 25 30]
[35 40 45]]
Example 4.14. Write a Python program to compute row wise and column wise sum of a ma-
trix.
OUTPUT
Column wise sum [ 60 116 245]
Row wise sum [125 95 201]
Example 4.15. Create a random sequence of 6X4 array using numpy. With these, create a
dataframe and add labels as A, B, C, D
# c r e a t e a random sequ en ce o f 6X4 array with numpy
# Create a d ata fra me and add l a b e l s as A , B , C, D import
numpy as np
import pandas as pd
m = np. random. random((6 ,4))
df = pd. DataFrame(m, columns = list (’ABCD’))
print (df)
133
Example 4.16. With the same dataframe as above, get first three rows of column A and C
# With same dataf rame as above , g e t columns A , C f i r s t t h r e e rows
import numpy as np
import pandas as pd
m = np. random. random((6 ,4))
df = pd. DataFrame (m, columns = list (’ABCD’))
splitdf = df[[’A’,’C’]]
print( splitdf[0:3])
OUTPUT
A C
0 0.826541 0.247127
1 0.027224 0.116862
2 0.649350 0.844085
# Change t h e column t o a d i f f e r e n t d a t a t y p e
import pandas as pd
ser1 = pd. Series([’10 ’,’20 ’,’30 ’,’40 ’,’50 ’])
print (" The series is \n ", ser1 )
print(" Now changing to numeric ")
ser2 = pd. to_numeric( ser1 )
print( ser2 )
OUTPUT
The series is
0 10
1 20
2 30
3 40
4 50
dtype: object
Now changing to numeric
0 10
1 20
2 30
3 40
4 50
dtype: int64
134
Example 4.18. With matplotlib, write a Python program for scatter plot.
# s c a t t e r p l o t with m a t p l o t l i b
import matplotlib. pyplot as plt
import numpy as np
x = [2 ,3 ,5 ,8 ,3 ,4 ,10 ,9 ,7 ,8]
y = [1 ,2 ,1 ,3 ,4 ,5 ,6 ,7 ,3 ,5]
print("x values are", x)
print("y values are", y) #
Give the t i t l e
plt. title(" Scatter plot")
# Name x and y a x i s
plt. xlabel("x")
plt. ylabel("y")
plt. scatter(x,y)
plt. show()
OUTPUT
135
plt. xlabel("x")
plt. ylabel("y")
plt. bar(x,y)
plt. show()
OUTPUT
Summary
• Python supports modularity. A simple python program with .py can be imported as a
module.
• A function within a program can be called from an external program.
• Python libraries can be installed and can be imported as modules.
• A number of Python programs can be stacked together and can be built as a package.
• Modules of numpy and pandas can be used for mathematical calculations and these can
scale well.
• Plotting libraries such as plotly and matplotlib can be incorporated within a Python pro-
gram to draw graph.
Learning Outcomes
After reading and working out examples from this chapter, you should be able to:
136
Chapter Exercises
Multiple Choice Questions
1. A Python module is a file with extension
(a) .pym
(b) .py
(c) .pt
(d) .ht
(a) import
(b) add
(c) insert
(d) update
3. A function named add is used in the program adder. In the main program, the correct
statement is
(a) data
(b) dataframe
(c) framest
(d) series
137
6. Dataframe in Pandas is
(a) 1-D
(b) 2-D
(c) 3-D
(d) 0-D
7. Series in Pandas is
(a) 1-D
(b) 2-D
(c) 3-D
(d) 4-D
8. How do you change the shape of numpy array?
(a) shape
(b) reshape
(c) shape.reshape
(d) reshape.shape
9. How do you convert a numpy array to a list?
(a) list(array)
(b) array(list)
(c) list
(d) array[list]
10. What is the datatype of numpy array?
(a) ndarray
(b) int
(c) float
(d) str
Descriptive Questions
1. Why do we need modules?
2. How do you create your own module and add to main program. Explain with an example.
138
4. What is the difference between package and module? Explain with an example.
9. How will you find the largest size file in the current directory with Python?
10. With an example explain how will you plot a 2-D graph with Python.
Programming Questions
1. Write a Python program to get the input from the user as starting date and ending date.
Display the number of hours, minutes and seconds between the two dates. Between
these two dates, write modules to convert days to hours, hours to minutes and minutes to
seconds.
5. Find the number of rows and number of columns in a matrix. Transpose the matrix and
then find the number of rows and number of columns (Use numpy module).
6. Write a Python program to read columns of data and find the unique value (Use pandas).
7. Write a Python program to give the statistical measure of all column data in terms of
mean, standard deviation, percentile (Use pandas).
8. Create a new column of data by adding the existing two columns of data.
9. Write a Python program to create multiple types of charts (a simple curve and plot some
quantities) on a single set of axes.
10. Write a Python programming to create a pie chart of the popularity of programming
Languages.
139
References and External Learning
• Reema Thareja, Python Programming using Problem Solving Approach, Oxford Univer-
sity Press, 2019
• Charles Dierbach, Introduction to Computer Science using Python A Computational
Problem-Solving Focus, Wiley Publications, 2015
To understand modules, refer to these websites.
• https://docs.python.org/3/tutorial/modules.html
• https://www.w3schools.com/python/python_modules.asp
• https://www.learnpython.org/en/Modules_and_Packages
To get more details of the entire package mechanism these sites will help.
• https://www.python-course.eu/python3_packages.php
• https://packaging.python.org/tutorials/packaging-projects/
Case study and use of external modules for datascience
• https://runestone.academy/runestone/books/published/httlad
s/Statistics/cs1_exploring_happiness.html
• https://runestone.academy/runestone/books/published/httlad
s/Statistics/cs2_new_business_data.html
• https://runestone.academy/runestone/books/published/httlad
s/MovieData/toctree.html
Links on numpy, pandas and matplotlib
• https://www.python-course.eu/numpy.php
• https://www.datacamp.com/community/blog/python-numpy-cheat
-sheet
• https://pandas.pydata.org/
• https://www.kaggle.com/kashnitsky/topic-1-exploratory-data
-analysis-with-pandas
• https://matplotlib.org/stable/tutorials/index.html
• https://s3.amazonaws.com/assets.datacamp.com/blog_assets/
Python_Matplotlib_Cheat_Sheet.pdf
140
CHAPTER - 5
CONTENTS:
LEARNING OBJECTIVES
Creating a Class
Class Methods
Class Inheritance
Encapsulation
Polymorphism
Class Methods vs Static Methods
Python Object Presistence
Worked out Programming Problems
Summary
Course Outcomes
Chapter Exercises
Multiple Choice Questions
Descriptive Questions
Programming Questions
References
Learning Objectives
• To understand the creation of classes and methods.
• To know the creation of instances associated with classes.
• To understand the concept of inheritance and encapsulation.
• To work with different methods.
• To explore the permanent storage of objects.
Python supports object oriented programming extensively. In this Chapter, you will learn
the basics of structuring the program by creating objects with the associated properties and
behaviors.
141
Creating a Class
An object is like a component which has some features and has certain functionalities. For
example, assume a motorbike, which is an object with features of model, colour and speed.
One of the functionality is to make noise through horn.
A class is more like a blueprint, which helps to create a mode of template associated with
features and functionalities. In Python, the keyword of class is used to create a class with a
property. The name of the class is usually capitalized. In the following example, the class of
Circle is created and the property of the class is radius = 8.
class Circle:
radius = 8
Now, assume there are two instances of objects c1 and c2 as two circles. These can be written
as:
c1 = Circle()
c2 = Circle()
Here, self.model = model creates an attribute of name through self. The model value is as-
signed to this attribute. A similar explanation is applicable to self.color and self.speed.
These attributes are called as instance attributes and are specific to that particular class. All
bikes have model, color and speed specification. Now, we will create two instances A and B as
follows:
A = Bike(" Hero"," Red","70 Kmph")
B = Bike(" TVS"," Blue","60 Kmph")
142
Each instance specifies the class name with parameters. For the instance of A, “Hero”, “Red”
and “70Kmph” are passed as parameters to the class as model, color and speed, respectively.
To access the instance attributes, the notation of instance.attribute can be used. In the
following example, A.model, A.color and A.speed represent the instance attributes.
print (A. model , A. color , A. speed)
print (B. model , B. color , B. speed)
The whole code and the output is given below.
class Bike:
type = " two wheeler" # c l a s s attribute
def __init__( self, model , color , speed):
self. model = model
self. color = color
self. speed = speed
OUTPUT
Hero Red 70 Kmph
TVS Blue 60 Kmph
The values of instance attributes can be changed. You can change the speed of B as B.speed =
75Kmph.Other than instance attributes, class attributes can also be defined. In the above
program, the second line indicates the type as a class attribute of two wheeler. This type is also
mutable. Asa continuation of the above program, enter these lines and check.
print(A. type)
A. type = " three wheeler"
print(A. type)
You will see that, first the class is two wheeler and then three wheeler.
Class Methods
With classes and instances, you can create some functionality. These are called as methods. In
the same example with Bike class, two methods are added. The methods for a specific class are
defined through the statement def. The first method gives a description with model, color and
speed. The second method indicates the nature of noise it creates.
143
class Bike:
type = " two wheeler"
def __init__( self, model , color , speed):
self. model = model
self. color = color
self. speed = speed
Class Inheritance
A class can belong to another class. For example, Bike can have two classes PedalBike and Mo-
torBike. These can be included as class PedalBike(Bike) and class MotorBike(Bike).
The new class that is created is called the child class and the one already available, the parent
class. In this example, MotorBike and PedalBike are child classes and Bike is the parent
class. Always the childclass should have a unique name and the parent class should be included
within the round brackets. See the example below.
class Bike:
// same as above code//
class PedalBike( Bike):
pass
class MotorBike( Bike):
pass
We can instantiate the childclass with the same attributes as that of parent class. The child
class inherits the parent class. See the example below, where A and C are instances of Motor-
Bike and PedalBike, respectively. When these are instantiated, the parent class attributes are
invoked.
144
class Bike:
// same as above code//
class PedalBike( Bike):
pass
class MotorBike( Bike):
pass
A = MotorBike(" Hero"," Red","70 Kmph")
C = PedalBike(" Atlas"," Blue","30 Kmph")
print(A. description())
print(C. sound(" Ringer"))
145
def sound( self,snd= " ringer"):
return f"{ self. model} has { snd}"
class MotorBike( Bike):
pass
A = MotorBike(" Hero"," Red","70 Kmph")
C = PedalBike(" Atlas"," Blue","30 Kmph")
print(C. description())
print(C. sound())
Encapsulation
Encapsulation wraps variables and methods, so that it cannot be changed accidentally. This
can be accomplished using underscore before the variable as ‘ <variablename>’. These
are private instance variables belonging to that particular class and are protected - meaning
that the assignment of the variable cannot be changed. Consider the following example of class
Banana. Here, the variable self. length has the assignment of ‘6cms’ in the 4th line. From
outside the class at 10th line the value is changed to 12cm. Now if these are displayed, you will
notice that the value of 6cms is not changed. This is because of the private variable indicated
by self. length.
1. # E n c a p s u l a t i o n example
2. class Banana:
3. def __init__( self):
4. self. __length = "6 cms"# p r i v a t e v a r i a b l e
5.
6. def long( self):
7. print (" The maximum length : {}". format ( self . __length ))
8. b = Banana()
9. b. long()
10. b. __length = "12 cms"
11. print(" The length is changed to 12 cms in the program , but...")
12. b. long()
OUTP UT
The maximum length: 6 cms
The length is changed to 12 cms in the program , but...
The maximum length: 6 cms
An underscore before the variable name indicates the private variable. Any change
in value to this variable is not permitted.
Now, what if you want to change this value? You can always change the value by creating a
function inside the class and pass the value as an argument to this function. Let us take the same
example. Add the function as setlength(self,length) with the argument as length. The
146
value for the variable is passed through b.setlength=‘‘12cms’’. After these changes, if you
run the program you will notice that the value changes to 12cms.
# Enc apsulation example
class Banana:
def __init__( self):
self. __length = "6 cms"# p r i v a t e variable
b = Banana()
b. long()
b. __length = "12 cms"
print(" The length is changed to 12 cms in the program , but...")
b. long()
print(" Pass the value of length as 12 cms to function.")
b. setlength("12 cms")
print(" The value should change now.")
b. long()
OUTPUT
The maximum length: 6 cms
The length is changed to 12 cms in the program , but...
The maximum length: 6 cms
Pass the value of length as 12 cms to function.
The value should change now.
The maximum length: 12 cms
Polymorphism
Polymorphism as the name suggests takes many forms (Poly - many, morphism - forms). It
means that the same function can take different forms. For example, consider banana and
lemon. Here, both are yellow in color but one is a fruit and the other is a vegetable. We can
indicate such cases through the concept of polymorphism. In the following code, there are two
classes Banana and Lemon with two similar functions type and col. But the functionality of
each of class is different. When instantiating the object, you can see that one belongs to Banana
class and the other to Lemon. These attributes pass to the respecive class and methods. Note
that there is no common parent class here and therefore no inheritance.
147
class Banana:
def __init__( self,typ, color):
self. typ = typ
self. color = color
def type ( self):
print(f" Banana is { self. typ}")
def col( self):
print(f" Banana is { self. color} in color.")
class Lemon:
def __init__( self,typ, color):
self. typ = typ
self. color = color
def type ( self):
print(f" Lemon is { self. typ}")
def col( self):
print(f" Lemon is { self. color} in color.")
OUTPUT
Banana is fruit
Banana is yellow in color.
Lemon is vegetable
Lemon is yellow in color.
In the above program, since the function is common to both classes, a for loop is used to
access the respective methods.
class MyClass:
def method( self):
return ’ instance method called’
@classmethod
def classmet ho d( cls):
return ’ class method called’
@staticmethod
def stati cmetho d ():
return ’ static method called’
OUTPUT
instance method called
−−−−−− −−−−− − −−− − −
class method called
—−−−−−−−−−
static method called
—−−−−−−−−−
Now, extend the program to access the function directly without an object. You will see
that the methods of class and static are executed.
149
\\ same as above program \\
print ( MyClass . classmet hod ())
print(" —
—−− −− −− −− −−− −− −− −− −− −− −− ")
print ( MyC lass. staticmethod ())
print ("−− −− −− −− −− −− −− −− −− −− −− −− ")
OUTPUT
class method called
—−−−−−−−−−−−
static method called
—−−−−−−−−−−−
But what happens when you call Myclass.method()?. Add the following extra line to the
program.
\\ same as above program\\
print ( MyClass. objectmethod ())
OUTPUT
Traceback ( most recent call last):
File " method1 .py", line 23, in <module >
print ( MyCl ass. method ())
TypeError: method() missing 1 required positional argument: ’self ’
You will notice that there is a type error since the object method is called without creation.
OUTPUT
Traceback ( most recent call last):
File " method1 .py", line 23, in <module >
print ( MyCl ass. method ())
TypeError: method() missing 1 required positional argument: ’self ’
You will notice that there is a type error since the object method is called without creation.
150
One of the mechanisms you have seen earlier in Chapter 3 is the use of Pickle files, where
the content are loaded as binary format in a file. Another common mechanism is the use of
‘Shelf’, a persistent dictionary like object.
The shelf module uses the data structure of dictionary to store the data to the disk. As
an example, consider the following program containing the data of a student with roll number,
name and course. First a name is defined and opened as shelf, which is similar to that opening
a file. Here, the name of student.db is created and assigned to the variable s. This variable
with the index of ’key1’ assigns the dictionary of student information with roll number, name
and course. The shelf record after necessary operation should close as indicated by s.close.
import shelve
s = shelve. open(’ student. db ’)
s[’key1 ’] = {’Roll number’ :202111520 , ’Name’:" Geiko",’ Course’:" MCA"}
s. close()
print(" Stored as a persistent data"
After execution of this program, you can see that a file with name ‘student.db’ is available in
the same directory, from where you run the program. It should be visible like this image.
Having stored the information, you can retrieve it from another file using the same shelf
name as shown in the following example.
import shelve
t = shelve. open(’ student. db ’)
print (t[’key1 ’])
t. close()
OUTPUT
{’Roll number’: 202111520 , ’Name’: ’ Geiko’, ’ Course’: ’MCA’}
Here, the same shelf student.db is used and the program prints key1.
Now, what if the values need to be updated? To modify the value, writeback=True is
to be used as shown below.
151
Now if you retreive the information from student.db, you should see this output.
OUTPUT
{’Roll number’: 202111520 , ’Name’: ’ Geiko’,
’ Course’: ’MCA Distance Education’}
Example 5.1. Create a class named number with the variable num.
class Number:
def __init__( self,num):
self. num = num
print(f" The number is { self. num}")
OUTPUT
The number is 6
Example 5.2. Add a method to Example1 and find the square of two numbers.
# Add a method to f i n d square
class Number:
def __init__( self,num):
self. num = num
def sq( self):
self. square = self. num * self. num
print (f" The square of { self. num} is { self. square}")
n = Number(6)
n.sq()
n = Number(7)
n.sq()
OUTPUT
The square of 6 is 36
The square of 7 is 49
152
Example 5.3. Extend the above program to find the square of first ten numbers.
Number. FirstTen()
OUTPUT
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
The square of 8 is 64
The square of 9 is 81
The square of 10 is 100
Example 5.4. With a parent class as Number, create two child classes Integers and Floating-
Point.
# Create two c h i l d c l a s s e s w i t h i n numbers as
# i n t e g e r s and f l o a t i n g p o i n t
class Number:
def __init__( self,num):
self. num = num
class Integers( Number):
pass
class FloatingPoint( Number):
pass
153
Example 5.5. Extend the above program and add methods. The program should identify the
type of the number entered outside the class and print accordingly.
class Number:
def __init__( self,num):
self. num = num
class Integers( Number):
def description( self):
return f"{ self. num} is integer"
n = 45
if type(n) == int:
n1 = Integers(n)
print(n1. description())
elif type(n) == float:
n1 = FloatingPoint(n)
print(n1. description())
OUTPUT
45 is integer
Example 5.6. In the above example, check the class of n1 and check whether it is an instance
of FloatingPoint.
\\ Same as above program \\
n = 45
if type(n) == int:
n1 = Integers(n)
print(" Check the class of n1 ", type(n1 ))print
(" check whether n1 is an instance of
FloatingPoint ", isinstance(n1 , FloatingPoint))
Example 5.7. Create a class with Number and a child class named Integers. Demonstrate
inheritance.
# Create a c h i l d c l a s s e s w i t h i n number as integers
# d emo n s t ra t e i n h e r i t a n c e
154
class Number:
def __init__( self,num):
self. num = num
class Integers( Number):
def double( self):
self. twice = self. num * 2
# self . num i s i n h e r i t e d from parent c l a s s
return f"{ self. twice} is double of { self. num}" n
= Integers(45)
print(n. double())
90 is double of 45
Example 5.8. Create a class with Number and a child class named Integers. Demonstrate
overriding.
# Create two c h i l d c l a s s e s w i t h i n numbers as i n t e g e r s
# d emo n s t ra t e o v e r r i d i n g
class Number:
def __init__( self,num):
self. num = num
def description( self):
return f" called from parent class − the number is { self. num}"
class Integers( Number):
def description( self,num = 1000009): # o v e r r i d e s t h e parent c l a s s
return f" called from child class − the number is { num}"
n1 = Number(35)
print(n1. description())
n2 = Integers(35)
print(n2. description())
OUTPUT
called from parent class − the number is 35
called from child class − the number is 1000009
Example 5.9. Create a child class named Integers with Number as parent class. Demonstrate
the use of super()
# Create a c h i l d c l a s s w i t h i n number as integers
# d emo n s t ra t e super ( )
class Number:
def __init__( self,num):
self. num = num
def description( self):
155
return f" called from parent class
– the number is { self. num}"
class Integers( Number):
def description( self,num = 1000009):
return super(). description()
return f" called from child class
— the number is { num}"# t h i s has no e f f e c t
n1 = Number(35)
print(n1. description())
n2 = Integers(35)
print(n2. description())
OUTPUT
called from parent class − the number is 35
called from parent class − the number is 35
Example 5.10. Create a class named Days In Year and assign 365 to the variable of
self.days.Change it to 366 from the instance of the class.
y = DaysInYear()
print(y. describe())
y. days = 366
print(y. describe())
OUTPUT
days in year = 365
days in year = 366
Example 5.11. Consider the above example. Use private variable such that 365 is not changed
in the above program.
156
class DaysInYear:
def __init__( self):
self. __days = 365
def describe( self):
return f" days in year = { self. __days}"
y = DaysInYear()
print(y. describe())
y. __days = 366
print(y. describe())
OUTPUT
days in year = 365
days in year = 365
Example 5.12. Use encapsulation in the above program and see what different it makes.
# s e t t h e number o f days i n a year as 365 i n c l a s s Days In Year .
# Change i t t o 366 .
# But t h e o u t p u t shoul d s t i l l remain a t 365
# Use E n c a p s u l a t i o n and change the value t o 366
class DaysInYear:
def __init__( self):
y = DaysInYear()
print(y. describe())
y. LeapYear(366)
print(y. describe())
OUTPUT
days in year = 365
days in year = 366
157
Example 5.13. Create two classes Integers and FloatingPoint. Use the same function to find
the cube of that number and demonstrate polymorphism.
# Have two classes i n t e g e r s and floats .
# Have a same f u n c t i o n o f cube and demonst rat e
# t hrough pol ymorphi sm
class Integers:
def __init__( self,num):
self. num = num
class FloatingPoint:
def __init__( self,num):
self. num = num
n1 = Integers(5)
n2 = FloatingPoint (5.5)
print(n1. cube())
print(n2. cube())
OUTPUT
Cube of 5 is 125
Cube of 5.5 is 166.375
Example 5.14. Create a class with name Bird and add a class method.
# Have a c l a s s b i r d and add a c l a s s method
class Bird:
def __init__( self, name , color):
self. name = name
self. color = color
@classmethod
def description(cls,name , color):
return cls(name , color)
158
OUTPUT
Parrot is Green
Example 5.15. Extend the above program with a static method and see the difference.
# Have a c l a s s b i r d and add a c l a s s method
class Bird:
def __init__( self, name , color):
self. name = name
self. color = color
@classmethod
def description(cls,name , color):
return cls(name , color)
@staticmethod
def isParrot( name):
if name == " Parrot":
return f"{ name} can fly"
OUTPUT
Parrot is Green
Parrot can fly
Summary
Python is an Object Oriented Programming Language.
Objects and the corresponding properties can be well aligned using Python.
The class is initiated using init function.
A number of methods can be written within a class.
Child classes can be created within a Parent class, thereby supporting inheritance.
If there is a specific property associated only to child class, the program can be
designedas per the child’s specific property. However, using super(), the parent
property can alsobe called.
Python supports polymorphism.
With encapsulation, the private variables in a class cannot be changed, thereby
preventingthe user to change the parameter of a particular class.
Python provides the flexibility of using three methods - instance method, class
methodand static methods.
Python object persistance through the module of shelf provides a way to store the
detailsof data in the disk.
159
Course Outcomes
Afer reading this Chapter and working out programs, you should be able to:
5. Develop complex programs with instance method, class method and static method.
Chapter Exercises
Multiple Choice Questions
1. To create a class called Flower, the syntax is
2. Assume there is a class Flower. The instance of Flower can be represented as:
(a) f = Flower()
(b) f = Flower
(c) Flower
(d) f
(a) init
(b) init
(c) default
(d) con()
160
4. Consider the following piece of code. What is the output?
(a) name
(b) sunflower
(c) f
(d) error
5. For the code mentioned in previous question, which creation of object is not valid?
(a) f1 = Flower(’fl’)
(b) f = Flower(’rose’)
(c) f3 = Flower(’jasmine’)
(d) f4 = newFlower(’rose’)
(a) name
(b) Flower
(c) f.name
(d) f
7. is a convention that is used to represent the instance of a class and to access
the attributes and methods of the class.
(a) method
(b) self
(c) class
(d) instance
8. In the following block of code, how many classes and methods are there?
class Number:
def __init__( self,num):
self. num = num
def sq( self):
self. square = self. num * self. num
print (f" The square of { self. num} is { self. square}")
161
def FirstTen():
for i in range(1 ,111):
n = Number(i)
n.sq()
Number. FirstTen()
10. Which among the following is the correct way to initialize the class?
11. Which among the following is the correct representation of private variable?
(a) Polymorphism
(b) Encapsulation
(c) Inheritance
(d) Data hiding
13. Which among the following is not a method in Object Oriented Programming?
Descriptive Questions
1. How do you create Parent Class and Child Class. Explain with an example.
9. What is the difference between class method and static method? When will you use these
methods?
Programming Questions
1. Create a class and defines the init method with one parameter, “name”. Add a
method to it and return that name.
2. Construct a class named Dog. The init method has parameters of “name” and “age”.
Also create the method updateAge, that increases the age by 1.
3. Extend the above program to create a class of Cat. The init method has “name” and
“age” as parameters. Then define the “make_sound” method, returning the cat’s meow
and another description to introduce itself.
4. Construct a class named ‘Book’ that has an init method with the parameters title and
author. Then create an instance of the ‘Book’ class named newbook.
163
5. In Example 5.3, add an other method to write the multiplication table of the number.
6. Create two classes Car and Bus as child classes with Parent class as Vehicle.
8. Create a parent class with two child classes Ostrich and Parrot. In the main class have a
method called fly and return the value that “Birds can fly”. Create a method in Ostrich
class namely, fly and return the value that “Ostrich cannot fly”. Create a method in
Parrot class namely, fly and return the value that “Parrots can fly”. Create an instance for
Parrot and Ostrich. Demonstrate inheritance, overriding and the user of super() with this
example.
9. Create a class called Person with variables name and age. Set the age as 2 as private
variable. Add a method called adult and return the age as age+16. Use encapsulation for
this program.
10. Create two classes UnderGraduates and PostGraduates. For each of the classes create the
same function courses and return the values as Bachelors and Masters. Demonstrate the
concept of polymorphism through this program.
11. Assume there is a list of books that needs to be stored as a persistent object. Write a
program to store that using the module of shelf.
12. For the above program, update the value of a book and store back again. Retrieve the list
of books from another program.
13. Create a parent class called Polygon and child classes Triangle, Rectangle, pentagon and
Hexagon. For each of these, add methods to return the number of sides and the area.
14. Define a class called Bike that accepts a string and a float as input, and assigns those
inputs respectively to two instance variables, color and price. Assign to the variable
testOne an instance of Bike whose color is blue and whose price is 89.99. Assign to the
variable testTwo an instance of Bike whose color is purple and whose price is 25.0.
15. Create a class named Vehicle. Its constructor should take three parameters, the year, the
name of the make and the name of the model, which should be stored in variables named
year, make, and model, respectively. Create an instance of the Vehicle class to represent
a vehicle of your choice.
16. Use your existing Vehicle class as a starting point. Create a method named years_old().
It should return how many years old the vehicle is. You can find the current year using
this code:
from datetime import datetime
current_year = datetime. now(). year
Create an instance of the Vehicle class to represent a vehicle of your choice. Call the
years_old() function and print the return value.
165