0% нашли этот документ полезным (0 голосов)
162 просмотров22 страницы

Python Programming FM REVISED

Документ представляет собой книгу, изданную компанией Pearson, посвященную программированию на Python. Он охватывает основы программирования, алгоритмы, структуры данных, функции и другие ключевые аспекты языка Python, а также включает информацию о компании Pearson и ее философии обучения. Книга предназначена для студентов и преподавателей, стремящихся улучшить свои навыки программирования.

Загружено:

syedaaliya221
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
0% нашли этот документ полезным (0 голосов)
162 просмотров22 страницы

Python Programming FM REVISED

Документ представляет собой книгу, изданную компанией Pearson, посвященную программированию на Python. Он охватывает основы программирования, алгоритмы, структуры данных, функции и другие ключевые аспекты языка Python, а также включает информацию о компании Pearson и ее философии обучения. Книга предназначена для студентов и преподавателей, стремящихся улучшить свои навыки программирования.

Загружено:

syedaaliya221
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 22

About Pearson

Pearson is the world’s learning company, with presence across 70 countries


worldwide. Our unique insights and world-class expertise comes from a long
history of working closely with renowned teachers, authors and thought leaders,
as a result of which, we have emerged as the preferred choice for millions of
teachers and learners across the world.
We believe learning opens up opportunities, creates fulfilling careers and hence
better lives. We hence collaborate with the best of minds to deliver you class-
leading products, spread across the Higher Education and K12 spectrum.
Superior learning experience and improved outcomes are at the heart of
everything we do. This product is the result of one such effort.
Your feedback plays a critical role in the evolution of our products and you can
contact us – [email protected]. We look forward to it.
Python
Programming
S. Sridhar
Department of Information Science and Technology
CEG Campus
Anna University, Chennai

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

Copyright © 2023 Pearson India Education Services Pvt. Ltd


All rights reserved. This book is sold subject to the condition that it shall not, by way of trade or
otherwise, be lent, resold, hired out, or otherwise circulated without the publisher’s prior written consent
in any form of binding or cover other than that in which it is published and without a similar condition
including this condition being imposed on the subsequent purchaser and without limiting the rights under
copyright reserved above, no part of this publication may be reproduced, stored in or introduced into
a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying,
recording or otherwise), without the prior written permission of both the copyright owner and the
publisher of this book.

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]

Compositor: MAP Systems, Bengaluru


Printed in India
This book is dedicated to my Grandmother and Father-in-Law,
Late Tmt. A. Ambujam Ekambaram and Late Shri T.C.Nagarajan
for their eternal inspiration for writing this book.
Dr. S. Sridhar

This book is dedicated to my Mother, Father, Husband, and Sister,


Tmt. A. Indrani, Shri V. Jayaraman, Shri P.Jeyakumar, and
Dr. J. Gitanjali.
I fervently hope that this book will repay the perpetual debt I owe.
Dr. J. Indumathi

This book is dedicated to my Father and my Mother


Shri S. Velmurugan and Tmt. P. Nagalakshmi, who taught
me about life.
Mr. V. M. Hariharan
CONTENTS
Preface������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ xvii
About the Authors�������������������������������������������������������������������������������������������������������������������������������������������������������������������� xxi

1.  Introduction to Programming�������������������������������������������������������������������������������1


1.1 Basics of Programming Language���������������������������������������������������������������������������������������������� 1
1.2 Programming Versus Software��������������������������������������������������������������������������������������������������� 2
1.3 Python Programming Language������������������������������������������������������������������������������������������������� 4
1.4 Compiler Versus Interpreter�������������������������������������������������������������������������������������������������������� 8
1.5 Integrated Development Environment (IDE)�����������������������������������������������������������������������������10
1.5.1 Python in interactive mode (windows OS)����������������������������������������������������������������������10
1.5.2 Python in script mode������������������������������������������������������������������������������������������������������13
1.5.3 Command Line Interpreter����������������������������������������������������������������������������������������������17
1.6 Various Resources for Python Programming�����������������������������������������������������������������������������17

2.  Problem Solving and Algorithms �����������������������������������������������������������������������25


2.1 Problem-solving and Computational Skills������������������������������������������������������������������������������� 25
2.2 Computational Thinking����������������������������������������������������������������������������������������������������������� 27
2.3 Software Development Cycle���������������������������������������������������������������������������������������������������� 29
2.4 Algorithm Sesign Strategies�������������������������������������������������������������������������������������������������������32
2.5 Algorithm Design�����������������������������������������������������������������������������������������������������������������������33
2.6 Flow Charts���������������������������������������������������������������������������������������������������������������������������������35
2.7 Example Algorithms�������������������������������������������������������������������������������������������������������������������37
2.7.1 Algorithm for Subtraction of Two Numbers��������������������������������������������������������������������37
2.7.2 Algorithm for Finding the Area of a Circle�������������������������������������������������������������������� 38
2.7.3 Algorithm for Finding the Largest Among Three Numbers������������������������������������������� 39
2.7.4 Factorial of a Number���������������������������������������������������������������������������������������������������� 40
2.7.5 Euclid Algorithm������������������������������������������������������������������������������������������������������������ 42
viii | Contents

2.7.6 Linear Search������������������������������������������������������������������������������������������������������������������43


2.7.7 Insertion Sort�������������������������������������������������������������������������������������������������������������������45
2.8 Analysis of Algorithms���������������������������������������������������������������������������������������������������������������47
2.9 Efficiency of the Algorithms�������������������������������������������������������������������������������������������������������52

3.  Introduction to Python�����������������������������������������������������������������������������������������55


3.1 What is a Program?���������������������������������������������������������������������������������������������������������������������55
3.2 Elements of Python Language��������������������������������������������������������������������������������������������������� 58
3.3 Python Block Structure��������������������������������������������������������������������������������������������������������������61
3.3.1 Importance of Indentation�����������������������������������������������������������������������������������������������61
3.3.2 Comments in Python�������������������������������������������������������������������������������������������������������63
3.4 Variables and Assignment Statement���������������������������������������������������������������������������������������� 65
3.5 Python Objects��������������������������������������������������������������������������������������������������������������������������� 68
3.6 Data Types in Python����������������������������������������������������������������������������������������������������������������� 70
3.6.1 Basic Data Types in Python��������������������������������������������������������������������������������������������70
3.6.2 Collection Data Types�����������������������������������������������������������������������������������������������������73
3.7 Operations���������������������������������������������������������������������������������������������������������������������������������� 77
3.7.1 Arithmetic Operators and Expressions���������������������������������������������������������������������������78
3.7.2 Compound Assignment Operators����������������������������������������������������������������������������������81
3.7.3 Boolean Operations��������������������������������������������������������������������������������������������������������81
3.7.4 Relational Operators and Boolean Expressions������������������������������������������������������������ 83
3.7.5 Bitwise Operators���������������������������������������������������������������������������������������������������������� 84
3.7.6 Identity and Membership Operators������������������������������������������������������������������������������ 85
3.8 Type Conversions����������������������������������������������������������������������������������������������������������������������� 88
3.9 Simple input/output Statements������������������������������������������������������������������������������������������������� 90
3.9.1 Reading Numbers from the Keyboard���������������������������������������������������������������������������� 90
3.9.2 print() Statement������������������������������������������������������������������������������������������������������������� 92
3.10 Formatting Using Print Statement��������������������������������������������������������������������������������������������� 94
3.10.1 Built-in Methods������������������������������������������������������������������������������������������������������������� 94
3.10.2 String Interpolation (old Style Formatting)��������������������������������������������������������������������95
3.10.3 String Formatting����������������������������������������������������������������������������������������������������������� 96
3.10.4 Formatted String Literals (F-string or f-string)������������������������������������������������������������ 98
3.11 Built-in Functions���������������������������������������������������������������������������������������������������������������������� 99
Contents | ix

4.  Decision Structures���������������������������������������������������������������������������������������������� 107


4.1 Need for Decision Structures����������������������������������������������������������������������������������������������������107
4.2 Forming Conditions������������������������������������������������������������������������������������������������������������������108
4.3 if-statement�������������������������������������������������������������������������������������������������������������������������������110
4.4 The if-else Statement����������������������������������������������������������������������������������������������������������������112
4.4.1 Inline-if-Statement���������������������������������������������������������������������������������������������������������116
4.5 if-elif Statement������������������������������������������������������������������������������������������������������������������������ 117
4.6 Nested-If Conditions���������������������������������������������������������������������������������������������������������������� 120

5.  Looping Statements�������������������������������������������������������������������������������������������� 123


5.1 Introduction to Looping����������������������������������������������������������������������������������������������������������� 124
5.2 Python Built-in Functions for Looping������������������������������������������������������������������������������������125
5.3 Loop Statements�����������������������������������������������������������������������������������������������������������������������127
5.3.1 while Loop���������������������������������������������������������������������������������������������������������������������128
5.3.2 for Loop�������������������������������������������������������������������������������������������������������������������������133
5.3.3 Nested Loops�����������������������������������������������������������������������������������������������������������������138
5.4 Jump Statements�����������������������������������������������������������������������������������������������������������������������140
5.4.1 break Statement�������������������������������������������������������������������������������������������������������������140
5.4.2 continue Statement��������������������������������������������������������������������������������������������������������143
5.4.3 pass Statement���������������������������������������������������������������������������������������������������������������146

6.  Introduction to Functions��������������������������������������������������������������������������������� 157


6.1 Introduction to Functions���������������������������������������������������������������������������������������������������������157
6.2 Types of Functions��������������������������������������������������������������������������������������������������������������������160
6.3 Anatomy of a User-defined Function���������������������������������������������������������������������������������������161
6.4 Types of Functions Based on Parameters���������������������������������������������������������������������������������165
6.4.1 Non-Parameterised Function����������������������������������������������������������������������������������������165
6.4.2 Parameterised Functions����������������������������������������������������������������������������������������������166
6.5 Void Functions and Fruitful (Value Returning) Functions������������������������������������������������������168
6.5.1 Void Function����������������������������������������������������������������������������������������������������������������168
6.5.2 Fruitful Functions���������������������������������������������������������������������������������������������������������169
x | Contents

6.6 Types of Function Arguments��������������������������������������������������������������������������������������������������171


6.6.1 Functions with No Arguments���������������������������������������������������������������������������������������171
6.6.2 Functions with Positional Arguments���������������������������������������������������������������������������172
6.6.3 Keyword Arguments������������������������������������������������������������������������������������������������������175
6.6.4 Default Arguments��������������������������������������������������������������������������������������������������������176
6.6.5 Variable Length Arguments������������������������������������������������������������������������������������������177
6.6.6 Variable Keyword-Based Arguments����������������������������������������������������������������������������179
6.6.7 Python Anonymous Functions���������������������������������������������������������������������������������������180
6.7 Passing of Objects Reference����������������������������������������������������������������������������������������������������181
6.8 Namespaces, Global Variables, and Scope�������������������������������������������������������������������������������183

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

8.6 Built-in Function and Tuples����������������������������������������������������������������������������������������������������257


8.7 Built-in Methods in Tuples������������������������������������������������������������������������������������������������������ 263
8.8 Nested Tuples��������������������������������������������������������������������������������������������������������������������������� 266
8.9 Selection����������������������������������������������������������������������������������������������������������������������������������� 268
8.10 Looping with Tuples�����������������������������������������������������������������������������������������������������������������271

9.  Sets and Dictionary����������������������������������������������������������������������������������������������277


9.1 Introduction to Sets�������������������������������������������������������������������������������������������������������������������277
9.2 Creating a Set����������������������������������������������������������������������������������������������������������������������������278
9.3 Basic Operation in Sets�������������������������������������������������������������������������������������������������������������281
9.4 Mathematical Operations of Sets��������������������������������������������������������������������������������������������� 286
9.5 Looping Operations in Sets����������������������������������������������������������������������������������������������������� 296
9.6 Frozen Sets������������������������������������������������������������������������������������������������������������������������������� 296
9.7 Introduction to Dictionary������������������������������������������������������������������������������������������������������� 297
9.8 Creating Dictionaries��������������������������������������������������������������������������������������������������������������� 298
9.9 Basic Dictionary Operations��������������������������������������������������������������������������������������������������� 300
9.10 Operations on Python Dictionary�������������������������������������������������������������������������������������������� 302
9.11 Nested Dictionary�������������������������������������������������������������������������������������������������������������������� 307
9.12 Looping Over a Dictionary�������������������������������������������������������������������������������������������������������310

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

11.  Advanced Functions������������������������������������������������������������������������������������������ 357


11.1 Introduction to Functional Programming��������������������������������������������������������������������������������357
11.2 Functions as Objects�����������������������������������������������������������������������������������������������������������������359
xii | Contents

11.3 Lambda Functions��������������������������������������������������������������������������������������������������������������������361


11.4 List Comprehensions����������������������������������������������������������������������������������������������������������������363
11.5 List Comprehension with Sequence Processing���������������������������������������������������������������������� 368
11.5.1 Map Function��������������������������������������������������������������������������������������������������������������� 368
11.5.2 Filter Function��������������������������������������������������������������������������������������������������������������370
11.5.3 reduce Function������������������������������������������������������������������������������������������������������������372
11.6 Iterators�������������������������������������������������������������������������������������������������������������������������������������374
11.7 Generators���������������������������������������������������������������������������������������������������������������������������������376
11.7.1 Generator Expressions������������������������������������������������������������������������������������������������� 380
11.7.2 Itertools, Special Iterators, and Generators�����������������������������������������������������������������381
11.8 Recursion��������������������������������������������������������������������������������������������������������������������������������� 384
11.9 Closed Functions and Function Annotators or Decorators������������������������������������������������������388

12.  Object-Oriented Programming (OOP)��������������������������������������������������������395


12.1 Introduction to Object Oriented Programming (OOP)�������������������������������������������������������������395
12.2 Classes and Objects������������������������������������������������������������������������������������������������������������������398
12.3 Class Attributes�������������������������������������������������������������������������������������������������������������������������401
12.4 Methods in Class���������������������������������������������������������������������������������������������������������������������� 408
12.4.1 Private Methods������������������������������������������������������������������������������������������������������������412
12.4.2 Constructor ������������������������������������������������������������������������������������������������������������������414
12.4.3 Destructor���������������������������������������������������������������������������������������������������������������������416
12.5 Built-ins������������������������������������������������������������������������������������������������������������������������������������ 422
12.5.1 Built-in Methods in Class����������������������������������������������������������������������������������������������422
12.5.2 Built-in Attributes in Objects����������������������������������������������������������������������������������������427

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

14.  Advanced Class��������������������������������������������������������������������������������������������������� 453


14.1 Overloading�������������������������������������������������������������������������������������������������������������������������������453
14.1.1 Method Overloading�����������������������������������������������������������������������������������������������������454
14.1.2 Operator Overloading���������������������������������������������������������������������������������������������������459
14.2 Method Overriding ����������������������������������������������������������������������������������������������������������������� 465
14.3 class Method and static Method���������������������������������������������������������������������������������������������� 469
14.4 Abstract Base Class (ABC) �����������������������������������������������������������������������������������������������������472
14.5 Meta Class���������������������������������������������������������������������������������������������������������������������������������475

15.  Modules in Python��������������������������������������������������������������������������������������������� 479


15.1 Introduction to Modules and Packages in Python��������������������������������������������������������������������479
15.2 Creation of a Module��������������������������������������������������������������������������������������������������������������� 480
15.3 Importing Modules������������������������������������������������������������������������������������������������������������������ 482
15.4 Uses of Standard Modules in Python�������������������������������������������������������������������������������������� 490
15.4.1 Math and Sympy Packages������������������������������������������������������������������������������������������� 490
15.4.2 os Module����������������������������������������������������������������������������������������������������������������������492
15.4.3 sys Module���������������������������������������������������������������������������������������������������������������������495
15.4.4 py_compile��������������������������������������������������������������������������������������������������������������������501
15.5 Packages����������������������������������������������������������������������������������������������������������������������������������� 502

16.  Errors and Exceptions����������������������������������������������������������������������������������������507


16.1 Introduction to Errors and Exceptions������������������������������������������������������������������������������������ 508
16.2 Handling Exceptions�����������������������������������������������������������������������������������������������������������������516
16.3 Multiple Exceptions������������������������������������������������������������������������������������������������������������������521
16.4 Raising Exceptions�������������������������������������������������������������������������������������������������������������������525
16.5 Exception Chaining������������������������������������������������������������������������������������������������������������������527
16.6 Built-In Exceptions�������������������������������������������������������������������������������������������������������������������528
16.7 User-Defined Exceptions����������������������������������������������������������������������������������������������������������532
16.8 Clean-Up Actions����������������������������������������������������������������������������������������������������������������������533
xiv | Contents

17.  Debugging and Testing������������������������������������������������������������������������������������� 541


17.1 Introduction to Python Debugger���������������������������������������������������������������������������������������������541
17.1.1 Python Debugger (pdb)�������������������������������������������������������������������������������������������������542
17.1.2 pdb through Primitive GUI Mode in IDLE�������������������������������������������������������������������549
17.2 Testing in Python����������������������������������������������������������������������������������������������������������������������551
17.2.1 Doctest���������������������������������������������������������������������������������������������������������������������������554
17.2.2 Unittest��������������������������������������������������������������������������������������������������������������������������557
17.2.3 Pytest�����������������������������������������������������������������������������������������������������������������������������561
17.3 Introduction to Profiling�����������������������������������������������������������������������������������������������������������563
17.3.1 Python timeit()���������������������������������������������������������������������������������������������������������������563
17.3.2 cProfile��������������������������������������������������������������������������������������������������������������������������565

18.  File Handling�������������������������������������������������������������������������������������������������������� 571


18.1 Introduction to Files������������������������������������������������������������������������������������������������������������������577
18.2 Types of Files����������������������������������������������������������������������������������������������������������������������������583
18.3 Input and Output Operations����������������������������������������������������������������������������������������������������574
18.4 File Handling Operations in Text Files�������������������������������������������������������������������������������������577
18.5 File Handling Operations in Binary Files��������������������������������������������������������������������������������582
18.5.1 Pickle�����������������������������������������������������������������������������������������������������������������������������583
18.6 File Handling Operations in Excel Files.����������������������������������������������������������������������������������585
18.7 Python Context Manager����������������������������������������������������������������������������������������������������������587

19.  Introduction to Graphical User Interface��������������������������������������������������� 595


19.1 Introduction�������������������������������������������������������������������������������������������������������������������������������595
19.2 Tkinter Module�������������������������������������������������������������������������������������������������������������������������596
19.2.1 Display Text with Label Widgets�����������������������������������������������������������������������������������596
19.2.2 Button Widgets ������������������������������������������������������������������������������������������������������������ 600
19.2.3 Frame Widget��������������������������������������������������������������������������������������������������������������� 604
19.2.4 Input Text Box��������������������������������������������������������������������������������������������������������������� 606
19.2.5 Grid������������������������������������������������������������������������������������������������������������������������������ 609
Contents | xv

20.  Introduction to Data Analytics with Python�������������������������������������������� 615


20.1 Introduction to Data Analysis���������������������������������������������������������������������������������������������������615
20.2 Dataset and Data Analysis��������������������������������������������������������������������������������������������������������617
20.3 Arrays in Python���������������������������������������������������������������������������������������������������������������������� 620
20.3.1 Importing and Creating an Array���������������������������������������������������������������������������������621
20.3.2 Array Operations����������������������������������������������������������������������������������������������������������622
20.4 Introduction to NumPy������������������������������������������������������������������������������������������������������������ 624
20.4.1 Array Creation in NumPy���������������������������������������������������������������������������������������������625
20.4.2 NumPy Properties���������������������������������������������������������������������������������������������������������627
20.4.3 Indexing and Slicing Operations����������������������������������������������������������������������������������628
20.4.4 Arithmetic Operations on NumPy���������������������������������������������������������������������������������629
20.4.5 Data Analysis Using NumPy�����������������������������������������������������������������������������������������630
20.5 Pandas���������������������������������������������������������������������������������������������������������������������������������������631
20.5.1 Series in Pandas������������������������������������������������������������������������������������������������������������632
20.5.2 CRUD Operations with Pandas������������������������������������������������������������������������������������633
20.5.3 Series Indexing��������������������������������������������������������������������������������������������������������������636
20.5.4 Series Statistical Methods���������������������������������������������������������������������������������������������636
20.5.5 Data Frames with Pandas���������������������������������������������������������������������������������������������638
20.5.6 Indexing in Data Frames����������������������������������������������������������������������������������������������641
20.5.7 Data Manipulation in Data Frames���������������������������������������������������������������������������� 646
20.5.8 Data Analysis using Pandas����������������������������������������������������������������������������������������� 648
20.6 Data Visualization Using Pandas and Matplotlib��������������������������������������������������������������������651
20.7 Scikit-Learn and Data Analysis����������������������������������������������������������������������������������������������� 660

Bibliography������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ 665
Index���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������667
xvi | Contents

ONLINE CHAPTERS

21.  Database and Parallel Programming������������������������������������������������������������������1


21.1 Databases and Python������������������������������������������������������������������������������������������������������������������ 1
21.1.1 Connecting to Database��������������������������������������������������������������������������������������������������� 4
21.1.2 CRUD in Database����������������������������������������������������������������������������������������������������������� 6
21.2 Threading Module����������������������������������������������������������������������������������������������������������������������21
21.2.1 Thread Objects����������������������������������������������������������������������������������������������������������������22
21.2.2 Lock�������������������������������������������������������������������������������������������������������������������������������� 28
21.2.3 Event Objects�������������������������������������������������������������������������������������������������������������������32
21.2.4 Asynchronous Programming������������������������������������������������������������������������������������������35
21.3 Multiprocessing �������������������������������������������������������������������������������������������������������������������������39

22.  Networks and Security������������������������������������������������������������������������������������������1


22.1 Introduction���������������������������������������������������������������������������������������������������������������������������������� 1
22.2 Network Programming���������������������������������������������������������������������������������������������������������������� 8
22.2.1 Socket Programming ������������������������������������������������������������������������������������������������������� 9
22.2.2 Internet Modules in Python���������������������������������������������������������������������������������������������15
22.2.3 Sending Emails����������������������������������������������������������������������������������������������������������������16
22.3 Web Scraping������������������������������������������������������������������������������������������������������������������������������17
22.4 Security���������������������������������������������������������������������������������������������������������������������������������������21
22.4.1 Classical Ciphers������������������������������������������������������������������������������������������������������������21
22.4.2 Asymmetric and Symmetric Algorithms��������������������������������������������������������������������������23

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.

About the Book


The book Python Programming is designed to be a textbook for undergraduate and postgraduate
students. The book aims to provide knowledge of Python programming. The book begins with the
basics of Python Programming followed by the basics of algorithms and further focuses on topics like
Introduction to programming language, looping, functions, and data structures like lists, tuples, sets,
dictionary, and strings. It covers functional programming concepts such as higher-order functions. It
also covers Object Oriented Programming concepts such as inheritance and polymorphism. The book
also deals with modules and packages, errors and exceptions, Python Testing, Profiling, Debugging,
and File Handling. The book then focuses on GUI Programming. An introduction to data analytics,
databases, network programming, and security is provided in this book.
The book is also helpful for diploma courses, school curricula, competitive examinations like GATE,
coding interviews, and coding competitions. The industry can use this book for importing training
and certificate courses. This book is also ideal for self-study who wishes to make a career in the IT
field.

Features of this Book


This book will help the reader navigate Python, whether a beginner or an experienced coder. This
book will help the reader to maximize Python’s power, versatility, and general-purpose nature as a
programming language.
xviii | Preface

• 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.

Organisation of the Book


This book, there are twenty-two chapters.
Chapter 1 titled “Introduction to Programming” introduces the basic concepts of programming. The
reader is taken on a journey through the fundamentals of Python as well as the terminologies that are
associated with Python.
Chapter 2 titled “Problem Solving and Algorithms” introduces the basics of computational skills
that are necessary for solving problems. This chapter places a strong emphasis on the importance of
algorithms. This chapter deals with algorithm writing, flowcharts, algorithm analysis, and asymptotic
notations.
Chapter 3 titled “Introduction to Python,” sheds light on the basics of programming in Python, data
types, and how to manipulate them with different operators.
Chapter 4 titled “Decision Structures” provides insights into how to take decisions. if statements, if-
else statements, if-elif statements, and nested-if statements are dealt in this chapter.
Chapter 5 titled “Looping Statements” deals with elaboration on how the computer can assist
repetition using programming constructs like while, for, and nested loops. In this chapter, statements
like break, continue, and pass statements are discussed.
Chapter 6 is on functions. The chapter illustrates how a function should be constructed.
Preface | xix

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.

Mr. V.M. Hariharan is presently CEO of Vels Infoway, an MSME-based


IT company. He has worked across 34 international IT projects. He also has
4 years of teaching experience as part of TechZ Academy. He is presently
working on a skill development project which provides an e-platform
for students and academicians to learn professional skills. His expertise
includes topics like Data Analytics, Machine Learning, Deep Learning, and
DevOps.

Вам также может понравиться