Python Programming FM REVISED
Python Programming FM REVISED
J. Indumathi
Department of Information Science and Technology
CEG Campus
Anna University, Chennai
V. M. Hariharan
Vels Infoway
Chennai
Disclaimer: Python and PyCon are trademarks or registered trademarks of the Python Software Foundation.
Python, its standard libraries, and Jython, are distributed under the Python License. The intellectual property
rights behind Python and Jython are held and managed by the Python Software Foundation PSF makes no
representations or warranties, express or implied. By way of example, but not limitation, PSF makes no and
disclaims any representation or warranty of merchantability or fitness for any particular purpose or that the
use of python will not infringe any third party rights. 5. PSF shall not be liable to licensee or any other users
of python for any incidental, special, or consequential damages or loss as a result of modifying, distributing,
or otherwise using python, or any derivative thereof, even if advised of the possibility thereof.
Although the author and publisher have made every effort to ensure that the information in this book was
correct at the time of editing and printing, the author and publisher do not assume and hereby disclaim
any liability to any party for any loss or damage arising out of the use of this book caused by errors or
omissions, whether such errors or omissions result from negligence, accident or any other cause. Further,
names, pictures, images, characters, businesses, places, events and incidents are either the products of the
author’s imagination or used in a fictitious manner. Any resemblance to actual persons, living or dead or
actual events is purely coincidental and do not intend to hurt sentiments of any individual, community,
sect or religion.
In case of binding mistake, misprints or missing pages etc., the publisher’s entire liability and your
exclusive remedy is replacement of this book within reasonable time of purchase by similar edition/reprint
of the book.
Senior Manager—Production: Neha Goomer
Senior Editor—Production: C. Purushothaman
ISBN 978-93-560-6933-6
First Impression
Published by Pearson India Education Services Pvt. Ltd, CIN: U72200TN2005PTC057128.
Head Office: 1st Floor, Berger Tower, Plot No. C-001A/2, Sector 16B, Noida - 201 301, Uttar Pradesh, India.
Registered Office: 7th Floor, SDB2, ODC 7, 8 & 9, Survey No. 01 ELCOT IT/ ITES-SEZ,
Sholinganallur, Chennai – 600 119, Tamilnadu, India.
Phone: 044-66540100
Website: in.pearson.com, Email: [email protected]
7. Lists��������������������������������������������������������������������������������������������������������������������������� 191
7.1 Introduction to Iterable Object��������������������������������������������������������������������������������������������������191
7.2 List �������������������������������������������������������������������������������������������������������������������������������������������192
7.2.1 Creating a List���������������������������������������������������������������������������������������������������������������192
7.2.2 Indexing in a LIST���������������������������������������������������������������������������������������������������������194
7.2.3 List Slicing���������������������������������������������������������������������������������������������������������������������195
7.3 Operations in the List���������������������������������������������������������������������������������������������������������������199
7.4 Built-in Functions and Methods in List����������������������������������������������������������������������������������� 202
7.5 Nested List ������������������������������������������������������������������������������������������������������������������������������ 209
7.6 Mutability of List����������������������������������������������������������������������������������������������������������������������217
7.7 Looping with List����������������������������������������������������������������������������������������������������������������������221
7.8 List as a Stack�������������������������������������������������������������������������������������������������������������������������� 225
7.9 List as Queue���������������������������������������������������������������������������������������������������������������������������� 230
8. Tuples����������������������������������������������������������������������������������������������������������������������� 239
8.1 Introduction to Tuples���������������������������������������������������������������������������������������������������������������239
8.2 Creating a Tuple������������������������������������������������������������������������������������������������������������������������241
8.3 Indexing and Slicing in a Tuple������������������������������������������������������������������������������������������������245
8.4 Operations in Tuples���������������������������������������������������������������������������������������������������������������� 249
8.5 Immutability in Tuples������������������������������������������������������������������������������������������������������������� 254
Contents | xi
10. Strings�������������������������������������������������������������������������������������������������������������������� 321
10.1 Introduction to Strings��������������������������������������������������������������������������������������������������������������322
10.2 Creating a String�����������������������������������������������������������������������������������������������������������������������322
10.3 Operations in Strings����������������������������������������������������������������������������������������������������������������324
10.4 Built-in Methods for Strings�����������������������������������������������������������������������������������������������������330
10.5 Built-in Functions for Strings���������������������������������������������������������������������������������������������������342
10.6 Looping with Strings��������������������������������������������������������������������������������������������������������������� 344
10.7 Regular Expressions���������������������������������������������������������������������������������������������������������������� 346
13. Inheritance����������������������������������������������������������������������������������������������������������� 433
13.1 Introduction�������������������������������������������������������������������������������������������������������������������������������433
13.2 Single Inheritance���������������������������������������������������������������������������������������������������������������������439
13.3 Multiple Inheritance���������������������������������������������������������������������������������������������������������������� 443
13.4 Multi-Level Inheritance����������������������������������������������������������������������������������������������������������� 445
13.5 Hybrid Inheritance������������������������������������������������������������������������������������������������������������������� 448
Contents | xiii
Bibliography������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 665
Index���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������667
xvi | Contents
ONLINE CHAPTERS
Python Installation
Appendix 1: ���������������������������������������������������������������������������������������������������������������������������������������� 1
Appendix 2: Anaconda Installation���������������������������������������������������������������������������������������������������15
Appendix 3: Installation of Python Packages and Command Line Interpreter (CLI)�����������������������19
Appendix 4: Turtle����������������������������������������������������������������������������������������������������������������������������� 25
Appendix 5: Optimization������������������������������������������������������������������������������������������������������������������33
Case Studies������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������1
PREFACE
In the 20th Century, One of the most game-changing technological advancements was the invention
of personal computers. Everyone uses computers for a variety of activities like sending and receiving
emails, games, online chats, and accessing government records online. Basic knowledge is required
to operate computers even for those who are not exposed to the usage of computers. The development
of such proficiency is necessary for everyone in the present society.
Computer Science and Information Technology students are expected to go further to develop software
applications by satisfying the increasing demands of society, schools, colleges, and universities. As a
direct consequence, the programming profession is in great demand. It is predicted that the students
will need to have an in-depth understanding of the fundamentals of programming to have a successful
professional career in IT industry. Python is an open-source programming language that emerges as
a popular choice among students for its ease of learning and simplicity.
The knowledge of Python along with problem-solving skills are rated as the greatest requirements
of any modern IT Industry. This book is an attempt to provide Python programming knowledge and
problem-solving skills.
• This book explains python in a light and approachable manner and does not require much
background knowledge.
• Complete syllabus coverage of most Indian Universities
• Special focus on Computational Thinking, algorithm writing, algorithm analysis, and Data
structures such as lists, tuples, sets, dictionaries, strings, stacks, and queues.
• Functional Oriented Programming - List Comprehension, Iterator, Generators, higher-order
functions, functional decorators, Object Oriented Programming, Meta Class
• Focus on python packages: os, sys, sympy, math, pycompile, pickle, tkinter, turtle, cython.
• Special Focus on Python tools: doctest, pytest, unittest, cProfile, timeit, Pdb, Numpy,
Pandas, Matplotlib and Scikit-learn, Sqlite, beautifulsoup.
• Focus on Concepts such as Context Manager, Multi-threading, Socket programming,
cryptography, ethics of programming, and web scrappers.
• Special topics like Python Debugging, Testing, Profiling, Databases like SQLite, Network,
and Optimization techniques
• Provide real-world examples as case studies online.
• Helps by providing Summary, Glossary, Try-out questions, Programming Questions, and
Multiple-choice questions.
• Rich pedagogy techniques like crossword, and jumbled words to reinforce the concepts.
• Instructor manual, and PowerPoint Presentations to assist Instructors.
Chapter 7 illustrates the list data structure. The chapter focuses on list creation, list processing, list
functions, and methods.
Chapter 8 illustrates the tuple data structure. This chapter focuses on tuple creation, tuple processing,
tuple function, and methods.
Chapter 9 titled, “Sets and Dictionary” provides the reader with an introduction to the unordered
collection of items as well as their respective implementations. This chapter introduces sets, set
operations, and set methods. This chapter also focuses on dictionary operations.
Chapter 10 is about strings. This chapter focuses on the storage and manipulation of strings. The
chapter also focuses on string functions and methods.
Chapter 11 titled, “Advanced functions”, introduces the functional programming paradigm. It takes
the basics of chapter 6 and illustrates the advanced function concepts like higher-order functions like
map, filter, and reduce. This chapter also introduces recursion and function decorators.
Chapter 12 titled, “Object Oriented Programming”, explains the fundamentals of object-oriented
programming (OOP), including class, objects, attributes, and methods.
Chapter 13 titled, “Inheritance” focuses on the intricacies of working with inheritance in Python.
This chapter deals with the fundamentals of inheritance, different forms of inheritance, and the
significance of UML in object-oriented programming.
Chapter 14 titled, “Advanced class” introduces concepts like overloading, overriding, static methods,
and class methods, as well as abstract base class (ABC) and metaclass.
Chapter 15 titled, “Modules in python” focus on modules and packages. The construction of large
Python programs using modules and packages is explained in this chapter. Also, this chapter focuses
on built-in packages like sys, os, sympy and py_compile.
Chapter 16 titled, “Errors and Exceptions” explains errors and error handling using try-except, try-
except-else statements. Multiple exceptions and user-defined exceptions are discussed in this chapter.
Chapter 17 titled “Debugging and Testing” focuses on Python tools like Pdb which is helpful in
debugging programs. The chapter also deals with Python testing tools like docTest, Unittest, and
Pytest. The chapter ends with profiler tools like cProfile.
Chapter 18 is about File handling. This chapter provides a general overview of files and file handling.
This chapter also assists in recognizing the differences between the processing of text, Excel, and
binary files using Pickle.
Chapter 19 titled “Introduction to GUI”, covers not only the graphic user interface (GUI), but also
the process of designing a GUI in Python, in addition to a wide range of graphical user interface
components known as widgets.
Chapter 20 titled, “Introduction to data analytics with python”, introduces data analytics. This
chapter provides an overview of the fundamentals of data science. Python tools like NumPy, Pandas,
Matplotlib, and Scikit-Learn are explained in this chapter.
xx | Preface
Chapter 21 titled, “Database and Parallel programming”, focuses on the concepts behind the database.
CRUD operations of SQLite are discussed in this chapter. The chapter provides a working knowledge
of asynchronous programming, threads, their interactions, and multiprocessing functionality.
Chapter 22 titled, “Networks and Security” introduces networks and security. It also provides an
overview of networking and socket, the process of web scraping, and finally, the cryptographic
algorithms are presented.
Appendix 1 provides information about the Installation of Python, Path, Directory, and File Handling
commands. Appendix 2 deals with the Installation of an Anaconda Edition. Appendix 3 offers Third-
party Python Packages, Virtual Environment, and pip commands. Appendix 4 provides information
about the Python package Turtle and finally Appendix 5 deals with the Optimization, Speed Gains in
Python, and Cython and annotations.
Acknowledgment
A book of this nature could not have been possible without the help of friends, colleagues, and well-
wishers. We thank all the students who have motivated us to write a book on Python Programming. We
express our gratitude to all our colleagues at the Department of Information Science and Technology,
Anna University, National Institute of Technology, Thiruchirapalli, Vellore Institute of Technology,
Vellore, SRM University, MGR University for motivating us and providing constructive suggestions
for the betterment of this book. Dr. S. Sridhar acknowledges the support provided by Dr. N. Vasandhi,
Dr. S. Shobika, and Dr. S. Shreevarshika for providing constant support and encouragement. Dr. J.
Indumathi acknowledges and accolades Ms. A. Indrani, Mr. V. Jayaraman, Mr. P.Jeyakumar, and Dr.
J. Gitanjali for being her pillar of strength. Mr. V. M. Hariharan acknowledges the support provided
by Mr. S. Velmurugan and Ms. P. Nagalakshmi for providing constant support and encouragement.
The authors also acknowledge the support provided by Ms. Neha Goomer and the Pearson Editorial
Team and reviewers of the book. The authors express their gratitude to Pearson Education for its
continuous encouragement and support.
Dr. S. Sridhar
Dr. J. Indumathi
Mr. V. M. Hariharan
ABOUT THE AUTHORS
Dr. S. Sridhar is a Professor and Head of the Information Science and
Technology College of Engineering, Guindy Campus, Anna University, Chennai.
He possesses a doctorate in Medical Image processing from Anna University.
He has around 30 years of academic experience in active teaching and research.
He has served Anna University, the National Institute of Technology (NIT),
Tiruchirappalli, and for around two years at SRM University.
He has many International and National papers to his credit. He has conducted
seminars and workshops on Image Processing and Matlab. He served as a
resource person for many Faculty Development Programs.
He has delivered video lectures on algorithms in EDUSAT television Programmes of Anna University
and E-Pathasala. He has also worked on student projects in the Council of Scientific and Industrial
Research (CSIR), Chennai, Indian Space Research Organization (ISRO), Bengaluru.
He has already authored three books for Oxford University Press on Digital Image Processing, Design
and Analysis of Algorithms, and Machine Learning. His expertise includes Machine Learning,
Programming, Digital Image Processing, Algorithms, Deep Learning, and Big Data.
Dr. J. Indumathi, a polymath, has taught and researched for over 33 years.
At present, she is serving as a Professor in the Department of Information
Science and Technology at Anna University, Guindy campus, Chennai.
ISMS (Information Security Management System) Lead Auditor, Project
Management Professional (PMP), Privacy Lead Assessor, Information
Privacy Manager, Information Privacy Professional/Europe, Network
Defense Architect (CNDA), and Test Manager, are a few of her value-
added credentials. She is a Fellow of bodies like the Institution of Engineers
(I.E), I.E.T.E, etc., including life member of professional organizations,
such as the IEEE, ACM, CSI, High Tech Crime Investigation Association, ISSA, IAAP. She serves
as an expert in international technical committees, editorial advisory boards, and review boards.
Apart from routine academic work, she has conducted many continuing technical edification
programmes. She has given technical invited talks, plenary talks, keynotes, and chaired conference
sessions worldwide; besides the talks on television/radio like EduSat Anna University, Doordarshan,
and All India Radio. She has undertaken and accomplished efficaciously, several project consultancy
services and her pooled rich experience has set up an imperturbable empire; providing Consultancy
services to various categories of organizations such as Government, Industry, Academic, Public
Welfare, Police, and Judiciary. Owing to her noteworthy, illustrious, Consultancy works, she was
honored with an Active Consultant Award, in addition to other 78 awards. She has guided several M.
Tech projects, B.E/B.Tech projects successfully and guided research scholars for their Ph.D. In toting
xxii | About the Authors
up to the above she served several other positions till 2018 which includes, the First Lady Secretary
for Tamil Nadu Engineering Admissions/ Tamil Nadu Common Admissions.
Dr. J. Indumathi has half a dozen granted patents and over 156 scientific papers in reputable journals.
Her expertise spans diverse cutting-edge technologies. Being a privacy researcher and activist, she
works at the intersection of Technology, Law, and Policy. She has a zeal for investigation, and research
and has innovated and improvised expansive projects which have made a milestone in the perfection
of the lifestyle of humankind.