(This page has no text content)
(This page has no text content)
Python for Everyone Learn and polish your coding skills in Python Saurabh Chandrakar Dr. Nilesh Bhaskarrao Bahadure www.bpbonline.com
Copyright © 2023 BPB Online All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor BPB Online or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. BPB Online has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, BPB Online cannot guarantee the accuracy of this information. First published: 2023 Published by BPB Online WeWork 119 Marylebone Road London NW1 5PU UK | UAE | INDIA | SINGAPORE ISBN 978-93-5551-815-6 www.bpbonline.com
Dedicated to Dedicated to my Parents Dr Surendra Kumar Chandrakar and Smt. Bhuneshwari Chandrakar brother Shri Pranav Chandrakar to my wife Priyanka Chandrakar and to my lovely son Yathartha Chandrakar Saurabh Chandrakar Dedicated to my Parents Smt. Kamal B. Bahadure and Late Bhaskarrao M. Bahadure to my in-laws Smt. Saroj R. Lokhande and Shri. Ravikant A. Lokhande and to my wife Shilpa N. Bahadure and to beautiful daughters Nishita and Mrunmayee And to all my beloved students. Dr. Nilesh Bhaskarrao Bahadure
About the Authors Saurabh Chandrakar is a Research & Development Engineer (Dy. Manager) at Bharat Heavy Electricals Limited (BHEL) Hyderabad. He is the winner of the best executive award on Operations Division by BHEL Hyderabad. Recently, he has been awarded the prestigious BHEL Excellence Award under Anusandhan category for Redundant Composite Monitoring System of Power Transformers project. He has 20 copyrights and 1 patent granted. Additionally, he has 6 patents filed. Moreover, he has published 3 books in reputed publications such as BPB New Delhi (Programming Techniques using Python), Scitech Publications Chennai (Programming Techniques using matlab) and IK International publishers (Microcontrollers and Embedded System Design). He has also launched 1 video course on BPB titled “First Time Play with Basic, Advanced Python concepts and complete guide for different python certification exams all in one umbrella.” Dr. Nilesh Bhaskarrao Bahadure received the Bachelor of Engineering degree in Electronics Engineering in 2000, the Master of Engineering degree in Digital Electronics in 2005, and the Ph.D. degree in Electronics in 2017 from KIIT Deemed to be University, Bhubaneswar, India. He is currently an Associate Professor in the Department of Computer Science and Engineering at Symbiosis Institute of Technology (SIT), Nagpur, Symbiosis International (Deemed University) (SIU), Pune, Maharashtra, India. He has more than 20 years of experience. Dr. Bahadure is a life member of IE(I), IETE, ISTE, ISCA, SESI, ISRS, and IAENG professional organizations. He has published more than 40 articles in reputed international journals and conferences, and has 5 books to his credit. He is the reviewer of many indexed journals such as IEEE Access, IET, Springer, Elsevier, Wiley and so on. His research interests are in the areas of Sensor Technology, the Internet of Things, and Biomedical Image Processing
Acknowledgements First and foremost, I would like to thank you all for selecting this book. It has been written with the beginner reader in mind. First of all, I take this opportunity to greet and thank my mentor"Prof. Nilesh Bahadure Sir" for motivating me and always communicating his expertise fully on topics related to Python. I am very thankful of being his protégé. I appreciate his belief in mee, for always standing behind me, and pushing me to achieve more. The phrase "Journey of Thousand Miles Begins with a Single Step" is something he always reminds me of. My parents, Dr. Surendra Kumar Chandrakar and Smt. Bhuneshwari Chandrakar, my brother, Shri Pranav Chandrakar, my beloved wife, Mrs. Priyanka Chandrakar, my adorable son, Yathartha Chandrakar, and all of my friends have inspired me and given me confidence over the years. Last but not least, I would like to express my sincere gratitude to the staff at "BPB Publications Private Limited" for their contributions and insights that made parts of this book possible. — Saurabh Chandrakar It was my privilege to thanks Dr. S. B. Mujumdar, Chancellor of the Symbiosis International University, Pune and Shri. Vijay Kumar Gupta, Chairman of Beekay Industries Bhilai and BIT Trust, for his encouragement and support. I would like to thank my mentors Dr. Arun Kumar Ray, Dean, School of Electronics Engineering, KIIT Deemed to be University, Bhubaneswar and Dr. Anupam Shukla, Director, SVNIT Surat. I would like to thank Dr. Vidya Yeravdekar, Principal Director of Symbiosis Society, and the Pro Chancellor of Symbiosis International University, Pune, Dr. Rajani R.Gupte, Vice Chancellor of the Symbiosis International University, Pune, and Dr.Ketan Kotecha, Dean, Faculty of Engineering, Symbiosis International University, Pune, and Dr. Mukesh M. Raguwanshi, Director, SIT Nagpur, for their advice, and encouragement throughout the preparation of the book. I would also like to thank Dr. Sanjeev Khandal, HOD, Department of Aeronautical Engineering, SGU Kolhapur, my well-wisher Dr. Prasenjeet D. Patil, Associate Professor, MIT ADT University, Pune and my colleagues in Symbiosis Institute of Technology Nagpur for providing valuable suggestions and lots of encouragement throughout the project. I am thankful to Prof. Dr. N. Raju, Sr. Assistant Professor, SASTRA University, Thanjavur, Tamil Nadu, for his support, assistance during writing, and for his valuable suggestions. I would also like to thank Dr. Ravi M. Potdar, Sr. Associate Professor, BIT Durg, and Dr. Md. Khwaja Mohiddin, Associate Professor, BIT Raipur for providing valuable suggestions and lots of encouragement throughout the project. Writing a beautiful, well balanced and acquainted book is not a work of one or two days or a month; it takes a lot of time and patience, as well as hours of hard work. Many thanks to my family members, my parents, wife, children and my well- wishers for their kind support. Without them and their faith and support, writing this classic book, would have remained just a dream. I also like to thank my students, who have always been with me, for relating problems and to finding solutions too. The perfection in any work does not come in a day. It needs a lot of effort, time and hard work, and sometimes, proper guidance.
It is my privilege to thank Prof. (Dr.) Ram Dhekekar, Professor, Department of Electronics & Telecommunication Engineering, SSGMCE Shegaon and Dr. C. G. Dethe, Director UGC Staff College Nagpur. Last but not the least, I would like to offer an extra special thanks to the staff at “BPB Publications Private Limited" for their insight and contribution in polishing this book. Most significantly, I want to thank Lord Ganesha for all of the work I was able to put into the book's preparation. I would not be as zealous as I am now if it weren't for God's amazing creation of the universes. For since the creation of the world God’s invisible qualities - his eternal power and divine nature - have been clearly seen, being understood from what has been made, so that men are without excuse." — Dr. Nilesh Bhaskarrao Bahadure
Preface The purpose of this book is to introduce readers with little to no programming experience to Python and provide them with the foundational knowledge and skills necessary to begin writing code in the language. By mastering Python, readers will be able to apply this technology to solve real-world problems and create useful applications. The first part of the book covers core python concepts. Then we shall see some advanced Python concepts along with some data science libraries like numpy, matplotlib and pandas. Finally, in the later part of the book, we shall see some powerful observations while writing python code. This book covers a wide range of topics, from basic syntax and data types to more advanced concepts along with a little touch of data science. Overall, the book provides a solid foundation for beginners to start their journey for getting trained in Python language. This book is divided into 11 chapters. Each chapter's description is listed as follows. Chapter 1: Basic Python Introduction – will cover the basic elements of writing a Python program where readers can gain an understanding of the fundamental topics. Chapter 2: Concept of Strings in Python – will cover strings in detail, as well as different string methods, usage of command-line arguments, and string access with some examples. Chapter 3: Concept of Flow Control Statements in Python – will cover the concept of conditional, iterative, and transfer statements, with loop patterns such as star pattern, alphabet pattern, and number pattern, with examples. Chapter 4: Concept of Exception Handling in Python – will cover the concept of multiple ways of using the try-except block, for preventing errors during runtime. Users will be able to create their exceptions for handling the errors. Moreover, the user will see different use cases and control flow of Python exception hierarchy. Chapter 5: Concept of Regular Expressions in Python – will cover the declarative mechanism for the representation of a group of strings, according to a particular pattern called regular expressions, which is quite difficult to understand, and also perform its usage. Each regex expression is explained in a very lucid manner with examples. Chapter 6: Concept of Functions in Python – will cover function types, and different types of function arguments such as positional arguments, keyword arguments, default arguments, variable length arguments, and kwargs. Moreover, concepts on local, global and non-local variable are well explained with examples, along with Python closures. Chapter 7: Concept of Data Structures in Python – will cover non-primitive inbuilt data structures such as list, tuple, set and dictionary, which are unique on their own. All the data structures definitions, methods, and different types of comprehensions such as list comprehension, tuple comprehension, set comprehension, and dictionary comprehension are well discussed. Chapter 8: Concept of Packages in Python – will cover the demonstration of package examples, with different approaches to module usage.
Chapter 9: Numpy Introduction – will cover different examples of scientific computing and data analysis library, that is, numpy library. Chapter 10: Data Visualization Introduction – will cover Matplotlib data visualization library by creating a line plot with examples. Chapter 11: Pandas Introduction – will cover Pandas Series and Pandas DataFrame with examples.
Code Bundle and Coloured Images Please follow the link to download the Code Bundle and the Coloured Images of the book: https://rebrand.ly/33uiwxo The code bundle for the book is also hosted on GitHub at https://github.com/bpbpublications/Python-for-Everyone. In case there's an update to the code, it will be updated on the existing GitHub repository. We have code bundles from our rich catalogue of books and videos available at https://github.com/bpbpublications. Check them out! Errata We take immense pride in our work at BPB Publications and follow best practices to ensure the accuracy of our content to provide with an indulging reading experience to our subscribers. Our readers are our mirrors, and we use their inputs to reflect and improve upon human errors, if any, that may have occurred during the publishing processes involved. To let us maintain the quality and help us reach out to any readers who might be having difficulties due to any unforeseen errors, please write to us at : errata@bpbonline.com Your support, suggestions and feedbacks are highly appreciated by the BPB Publications’ Family. Did you know that BPB offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.bpbonline.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at: business@bpbonline.com for more details. At www.bpbonline.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on BPB books and eBooks.
Piracy If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at business@bpbonline.com with a link to the material. If you are interested in becoming an author If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit www.bpbonline.com. We have worked with thousands of developers and tech professionals, just like you, to help them share their insights with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions. We at BPB can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about BPB, please visit www.bpbonline.com. Join our book's Discord space Join the book's Discord Workspace for Latest updates, Offers, Tech happenings around the world, New Release and Sessions with the Authors: https://discord.bpbonline.com
Table of Contents 1. Basic Python Introduction Introduction Structure Objectives Benefits of Python Uses of Python Limitations of Python Keywords and reserved words Identifiers Line joining methods Implicit line joining method Using curly braces Using square brackets Using parenthesis Explicit joining method Example 1 Example 2 Print function Different styles to use print function Variables Importance of mnemonic variable names in Python Concept of immutability vs fundamental data types Conclusion Points to remember Questions 2. Concept of Strings in Python Introduction Structure Objectives Reading dynamic input from the keyboard raw_input() input() Using Try Except Using eval function Command Line arguments Python sys.argv Python getopt module Exception getopt.GetoptError Short form options Long form options
Python argparse module Python argparse Positional arguments Python argparse positional arguments default values Python argparse argument help Python argparse Data Type Python argparse optional arguments Short names for optional arguments with argparse Python argparse with optional and positional arguments Python argparse with required Python argparse dest action Python argparse append action Allowing or disallowing abbreviations Strings Python multiline strings Python string access Using index Using slice operator In forward direction In backward direction Conclusion Points to remember Questions 3. Concept of Flow Control Statements in Python Introduction Structure Objectives Flow of execution of the program Selection statements/Conditional statements if if-else if-elif-else if-elif-else ladder Iterative statements for while Transfer statements break continue pass in keyword usage Loop patterns Star pattern Printing stars in pyramid shape Alphabet pattern Number pattern
Conclusion Points to remember Questions 4. Concept of Exception Handling in Python Introduction Structure Objectives Errors Syntax error Runtime Error Importance of exception handling Python exception hierarchy Customized exception handling Control flow in try-except Case-1 - No raising of exception Case-2 - Exception raised at st3 and corresponding except block is matched Case-3 - Exception raised at st3 and corresponding except block is not matched Case-4 - Exception raised at st5 Case-5 - Exception raised at st6 Exception information printing to the console Try with multiple except blocks Single except block that can handle multiple exceptions Default except block Possible combinations of except block finally except block Control flow in try-except and finally Case-1 - No exception is raised Case-2 - Exception raised at st3 and corresponding except block is matched Case-3 - Exception raised at st3 and corresponding except block is not matched Case-4 - Exception raised at st5 Case-5 - Exception raised at st6 or st7 Nested try-except finally block Control flow in Nested try-except finally block Case-1 - If there is no exception Case-2 - Exception raised at st3 and corresponding except block is matched Case-3 - Exception raised at st3 and corresponding except block is not matched Case-4 - Exception raised at st6 and inner except block is matched Case-5 - Exception raised at st6 and inner except block is not matched but outer except block is matched Case-6 - Exception raised at st6 and both inner and outer except block is not matched Case-7 - Exception raised at st7 and the corresponding except block is matched Case-8 - Exception raised at st7 and the corresponding except block is not matched Case-9 - Exception raised at st8 and the corresponding except block is matched Case-10 - Exception raised at st8 and the corresponding except block is not matched Case-11 - Exception raised at st9 and the corresponding except block is matched
Case-12 - Exception raised at st9 and the corresponding except block is not matched Case-13 - Exception raised at st10 Case-14 - Exception raised at st11 or st12 Else block with try-except finally block Conclusion Points to remember Questions 5. Concept of Regular Expressions in Python Introduction Structure Objectives compile() finditer() Character classes Pre-defined character classes Quantifiers Functions of re module match fullmatch search findall sub subn split escape Metacharacters [] (Square brackets) . (Period) ^ (Caret) $ (Dollar) * (Star) + (Plus) ? (Question Mark) {} (Braces) | (Alternation): () (Group) \ (Backslash) r prefix Conclusion Points to remember Questions 6. Concept of Functions in Python Introduction Structure
Objectives Functions in Python Function types Built in functions User defined functions Function arguments Positional arguments Keyword arguments Default arguments Variable length arguments Keyword variable length arguments (kwargs) Nested function Python closures Function passing as a parameter Local, global, and non-local variables Local variables Global variables Non-local variables Recursive function Python Lambda functions Nested lambda functions Passing lambda functions to another function Conclusion Points of remember Questions 7. Concept of Data Structures in Python Introduction Structure Objectives List data structure Creating a list Creating an empty list Creating a list when elements are known Creating a list with dynamic input List creation using list() function List creation using split() function Lists versus immutability Accessing elements of list By using index By using index and for loop By using Index and while loop By using list slicing List comprehension List comprehension with for loop List comprehension with for loop and if statement
List comprehension with for loop and nested if statement List comprehension with if else statement and for loop Nested list comprehension with for loop Tuple data structure Tuple creation An empty tuple creation Single valued tuple creation Multiple valued tuple creation Using tuple() function Accessing elements of tuple By using index By using index and for loop By using index and while loop By using tuple slicing Tuple versus immutability Tuple comprehension List versus tuple comparison Set data structure Set creation Set comprehension Set comprehension with for loop Set comprehension with for loop and if statement Set comprehension with for loop and nested if statement Set comprehension with if else statement and for loop Dictionary data structure Creation of an empty dictionary By using dict() function By using curly braces only Creation of a dictionary Accessing dictionary Accessing dictionary Deleting dictionary item Dictionary comprehension Dictionary comprehension with for loop Dictionary comprehension with for loop and if statement Dictionary comprehension with for loop and nested if statement Dictionary comprehension with if else statement and for loop Conclusion Points of remember Questions (Long/Short/MCQs) 8. Concept of Packages in Python Introduction Structure Objectives Packages
Structure for package of games Using “import” in Packages Accessing objects like variables, functions, classes, and lists Using “from import” in Packages Accessing objects like variables, functions, classes, and lists Using “from import *” in Packages Accessing games package using different approaches Conclusion Points to remember Questions 9. Numpy Introduction Introduction Structure Objectives Similarities between list and numpy array Differences between list and numpy array Numpy arrays creation 1-D array creation using list 1-D array creation using tuple 2-D array creation using Nested lists Array creation with a particular dtype Object type array creation 1-D array creation with arange() function Using linspace() Using zeros() Using ones() Using full() Using eye() Using diag() Using empty() Comparison between zeros and empty Conclusion Points to remember Questions 10. Data Visualization Introduction Introduction Structure Objectives Python data visualization tools Line plot creation by passing 2 ndarrays Adding title, xlabel and ylabel to the line plot Advanced line plot linestyle property color property
default color Peep in a shortcut way to set color, marker and linestyle mlc form clm form If no color is mentioned, then default color is blue alpha property linewidth and markersize property markerfacecolor property Customizing the figure size Plotting multiple lines in a same plot Conclusion Points of remember Questions 11. Pandas Introduction Introduction Structure Objectives Pandas Series Pandas Series constructor Creating Pandas Series by passing a list Creating Pandas Series by passing a dictionary Creating Pandas Series by passing a numpy array Accessing elements in Pandas Series Pandas Series slicing Pandas Series filtering Usage of apply method to Pandas Series Aggregating of Pandas Series Pandas DataFrame Pandas DataFrame constructor Pandas DataFrame creation Accessing data in Pandas DataFrame Data modification in Pandas DataFrame Data aggregation in Pandas DataFrame Conclusion Points to remember Questions Index
Loading comments...
Reply to Comment
Edit Comment