ultimate-python-programming-deepali-srivastava
ultimate-python-programming-deepali-srivastava
Python
Programming
Learn Python with 650+ programs,
900+ practice questions, and 5 projects
Deepali Srivastava
www.bpbonline.com
ii
First Edition 2024
ISBN: 978-93-55516-558
All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any form or
by any means or stored in a database or retrieval system, without the prior written permission of the publisher
with the exception to the program listings which may be entered, stored and executed in a computer system,
but they can not be reproduced by the means of publication, photocopy, recording, or by any electronic and
mechanical means.
All trademarks referred to in the book are acknowledged as properties of their respective owners but BPB
Publications cannot guarantee the accuracy of this information.
www.bpbonline.com
iii
Dedicated to
Deepali Srivastava has a Masterʼs degree in Mathematics and is an author and educator in the field
of computer science and programming. Her books “C in Depthˮ and “Data Structures Through C in
Depthˮ are widely used as reference materials by students, programmers and professionals looking to
enhance their understanding of programming languages and data structures. These books are known for
their clarity, depth of coverage, and practical approach to learning. In addition to her writing, Deepali
Srivastava has been involved in creating online video courses on Data structures and Algorithms, Linux
and Python programming. Her books and courses have helped 350,000+ students learn computer science
concepts. Her work has been appreciated by students and has been a valuable resource for those looking
to build their programming skills.
v
Acknowledgement
I would like to thank God for blessing me with the opportunity and inspiration to write this book, and for
giving me the strength to do it.
I am grateful to my husband Suresh Kumar Srivastava for always believing in my capabilities and
consistently inspiring me to give my best. He introduced me to book writing and helped me unleash my
potential. His thoughtful suggestions and feedback helped me improve the content and presentation of
this book.
I would like to thank my parents, my brother and my sister-in-law for their unwavering love and support.
Blessings of my parents and late parents-in-law are a major source of my inner strength.
I am indebted to my teachers in my journey of education, especially my teachers and friends in MJP
Rohilkhand University Bareilly, where I got introduced to the world of programming.
I extend my appreciation to the readers of my books and students of my online courses for their interest
in my work, and for their appreciation and suggestions. Any sort of feedback is valuable to me and helps
me in improving my work and creating better content.
I am grateful to the BPB Publications team for their guidance and support provided during every step
of the publishing journey. Special appreciation goes to the editing team, layout team, and all other
contributors involved in bringing this book to life.
vi
Preface
Python is a widely used general-purpose programming language. Its popularity can be attributed to its
simplicity and a rich set of powerful features. The clean and intuitive syntax makes it an excellent choice
for novices, allowing them to grasp the fundamentals of programming quickly, and the advanced features
make it appealing to experienced programmers too. It can run on various platforms, including Windows,
macOS, and Linux. Since it is an open-source software, it is freely available to all.
The widespread usage of Python is evident in the technology world, with major companies and
organizations such as Google, Amazon, Instagram, Facebook, and NASA using it in different ways.
Whether you are involved in machine learning, data science, artificial intelligence, scientific computing,
automation or you need to create robust web applications and games, Python provides the necessary
tools and resources. The extensive collection of libraries available in Python can be effectively utilized
across diverse domains. Therefore, adding Python to your skill set can greatly enhance your capabilities
and open up numerous opportunities in various fields.
This book provides a thorough and comprehensive introduction to Python, focusing on the core
programming concepts and problem-solving skills required for building a solid foundation in
programming. Throughout the book, there are numerous programming examples and end-of-chapter
exercises to give you a hands-on experience. The exercises include multiple-choice questions and
programming problems; multiple-choice questions will assess both your memory and comprehension
of the topic, while the programming exercises will provide you with a chance to apply the acquired
concepts. The book includes coding conventions and best practices for writing efficient, readable, and
maintainable code. The code in the book is written and tested using Python version 3.11, which is the
most recent version at the time of publishing the book.
Python is easy to learn. You can start writing Python programs within a few days. However, if you wish
to leverage all the powerful features of Python, a more in-depth exploration is required. The content in
this book can assist you in achieving that. This book includes 21 chapters that gradually introduce new
topics so learners can proceed at a sustainable pace. If you are a beginner, start from the first chapter and
go through all the chapters in order, and work out the examples and exercises along the way. If you have
a working knowledge of Python, you can quickly browse through the initial chapters and then randomly
jump to topics that are new to you or that you want to master. However, I would still recommend reading
the chapters in sequence to get the most out of the book. If you are transitioning from some other
language, you might be tempted to skip the initial information, but I would suggest you go through all the
basic details to avoid any confusion later. Here is a brief summary of the chapters presented in the book.
Chapter 1 is an introduction to Python and shows the installation process. Chapter 2 covers the fundamental
elements of Python, such as data types, variables, input, output, and many other basic concepts you need
to get started in Python. Chapter 3 provides a detailed explanation of strings that represent textual data
in Python. Chapters 4 and 5 cover the container types: lists, tuples, dictionaries, and sets. Chapter 6
provides an insight into conditional execution. In chapter 7, we will see how to perform repetitive tasks
using loops, and chapter 8 discusses some common looping techniques in Python. Chapter 9 introduces
the concept of comprehensions which help us write shorter and readable code.
vii
Chapter 10 contains detailed coverage of functions. We will see how to create our own functions
and will discuss parameters, arguments, arguments passing, function objects, and many other details
about functions. Chapter 11 shows how to create and use modules and packages. Chapter 12 is about
namespaces and scoping rules. Chapter 13 shows how to write programs that can create files, write
data into files, and read the data stored in files. Chapters 14, 15, and 16 provide you with a strong
understanding of the object-oriented concepts. We will discuss classes, objects, methods, inheritance,
polymorphism, and magic methods. Chapters 17 and 18 are devoted to advanced topics like iterators,
generators, and decorators. Chapter 19 is about functional programming and lambda functions. Chapter
20 shows how to handle run-time errors in Python, and Chapter 21 discusses context managers that are
used to automate common resource management patterns.
At the end of each chapter, you will find exercises, and their solutions are provided at the end of the book.
I would suggest that you try to solve these exercises by yourself before looking at the solution. Solving
exercises and writing code will help you to internalize the concepts presented in the book.
Some typographical conventions are followed throughout the book for a good reading experience. The
code snippets and programs in the book appear in this font to differentiate them from the regular text.
Program elements, such as variable names, types, etc., within the regular text, are in this font. Any
output produced by the code on the screen as a result of running a program or anything that the user has
to input through the screen appears in this font.
My aim was to write an absolute hands-on book that is simple enough to follow and yet gives detailed
knowledge. Reading this book will be a breeze, yet it will give you a comprehensive knowledge of Python
and instill the confidence to excel in any written test, interview, or professional work. Programming is fun
only when you get your hands dirty with code. Reading a book is not enough for learning programming.
I highly recommend that you try the coding examples and exercises presented in the book. The efforts
you put in to strengthen your fundamentals of core programming concepts will take you a long way in
your software development journey.
By the end of this book, you will develop a strong foundation in core Python skills and will get the
ability to explore the vast range of functionalities offered by the standard library and third-party libraries.
As you progress, you will continue to be amazed by the capabilities of Python and the remarkable
libraries available. With your newfound skills you can venture into diverse fields like data science or
machine learning. Moreover, if this is the first programming language you are learning, equipped with
the foundation of programming concepts and problem-solving skills, you can easily learn any other
programming language.
After using this book as a tutorial to learn the language, you can always refer to it as a handy resource
whenever you need to recall or review any concept and apply it to your work.
Writing this book was a very enjoyable, insightful, and amazingly satisfying journey for me and I am
sure my readers will have a similar experience while reading the book. I hope you enjoy reading the book
and start loving Python.
Happy programming!
viii
https://rebrand.ly/z815rfg
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 :
[email protected]
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 :
[email protected] 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.
ix
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 [email protected] with a link to the material.
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!
https://discord.bpbonline.com
x
Table of Contents
2.17 Comments..........................................................................................................................37
2.18 Indentation in Python........................................................................................................38
2.19 Container types..................................................................................................................39
2.20 Mutable and Immutable Types .........................................................................................39
2.21 Functions and methods......................................................................................................41
2.22 Importing...........................................................................................................................42
2.23 Revisiting interactive mode ..............................................................................................43
2.24 Errors.................................................................................................................................44
2.25 PEP8..................................................................................................................................45
Exercise.............................................................................................................................45
3. Strings..................................................................................................... 49
3.1 Indexing.............................................................................................................................50
3.2 Strings are immutable........................................................................................................51
3.3 String Slicing.....................................................................................................................52
3.4 String Concatenation and Repetition.................................................................................55
3.5 Checking membership ......................................................................................................56
3.6 Adding whitespace to strings.............................................................................................57
3.7 Creating multiline strings..................................................................................................57
3.8 String methods...................................................................................................................60
3.9 Case-changing methods.....................................................................................................60
3.10 Character classification methods.......................................................................................61
3.11 Aligning text within strings ..............................................................................................62
3.12 Removing unwanted leading and trailing characters.........................................................62
3.13 Searching and replacing substrings...................................................................................63
3.14 Chaining method calls.......................................................................................................66
3.15 String comparison .............................................................................................................67
3.16 String conversions.............................................................................................................68
3.17 Escape Sequences..............................................................................................................68
3.18 Raw string literals..............................................................................................................70
3.19 String formatting...............................................................................................................71
3.20 String formatting using the format() method of string class.............................................74
3.21 Representation of text - character encodings.....................................................................76
Exercise ............................................................................................................................82
9. Comprehensions.................................................................................. 214
9.1 List Comprehensions.......................................................................................................214
9.2 if clause in list comprehension .......................................................................................217
9.3 Ternary operator in list comprehension...........................................................................218
9.4 Modifying a list while iterating ......................................................................................219
9.5 Getting keys from values in a dictionary using list comprehension................................219
9.6 Using list comprehensions to avoid aliasing while creating lists of lists........................220
9.7 Multiple for clauses and Nested list Comprehensions....................................................221
9.8 Extracting a column in a matrix .....................................................................................222
9.9 Dictionary Comprehensions............................................................................................222
xv
Solutions..................................................................................................... 665
Index..................................................................................................... 683-688
Introduction to Python 1
Python is a widely used high-level and general-purpose programming language originally developed
by Guido Van Rossum in the early 1990s in the Netherlands. It is maintained by a community of core
developers who are actively engaged in its growth and advancement. Although the official logo of Python
shows two intertwined snakes, it is not named after any snake. Van Rossum named this language after a
1970s comedy show 'Monty Python's Flying Circus'.
Python has three major versions; the initial version, Python 1.0, was released in January 1994. The
second major version, Python 2.0, was released in 2000, and the third major version, Python 3.0, was
released in 2008. Python 3 is not backward compatible with Python 2; this means that the code written
in Python 2 may not work as expected in Python 3 without making some modifications. In this book,
we will use Python 3. The latest release of Python is available on its official website www.python.org.
Python is an open-source software, which means that it is free to use and distribute.
This is what happens when we execute a Python program. The intermediate compilation step is hidden
from the programmer; we can just type and run our program immediately. The programmer does not
have to explicitly compile the code, so there is no separate compile time in Python; there is only runtime.
The compilation to bytecode is done to improve the efficiency as the bytecode can be interpreted faster
than the original source code.
In this whole process, the bytecode complier is a software that converts source code to bytecode, and
PVM is a software that converts bytecode to machine code for the target platform. Python Virtual
machine contains some platform-specific components that may be implemented differently for each
platform. This allows the virtual machine to covert the bytecode into native machine code according to
the platform. It abstracts away the underlying hardware and operating system details and thus provides
a consistent runtime environment for Python programs across different platforms. Both the bytecode
compiler and the virtual machine are part of the Python interpreter software and are included in your
Python installation.
4 Ultimate Python Programming
The intermediate bytecode is generally cached for faster execution. It is stored in .pyc or .pyo files inside
a folder named __pycache__ and the programmer can just ignore these files. When the program is run
multiple times without modifying the source code, the compiled bytecode from the cached file is loaded
and executed instead of re-compiling from source code to bytecode every time. This bytecode is stored
only for imported files, not for the top-level scripts; we will see the difference between the two later in
the book.
The Jython implementation translates Python code into Java bytecode, enabling its execution on a
Java virtual machine. An advantage of Jython is its ability to directly access Java libraries. Similarly,
IronPython is designed for the .NET framework and facilitates integration with .NET components.
Some implementations of virtual machines (bytecode interpreters) use just-in-time (JIT) compilation
approach to speed up the interpretation process. The PyPy implementation of Python has better speed
as it includes a just-in-time compiler for faster execution of the bytecode. Just-in-time compiler will
compile the frequently executed blocks of bytecode to machine code and cache the result. Next time,
when the virtual machine has to execute the same block of bytecode, the precompiled(cached) machine
code is utilized and executed, resulting in faster execution. So, the JIT compiler uses the compilation
approach to improve the efficiency of bytecode execution.
Once the download is complete, double-click on the installer to execute it and begin the installation
process. On the first screen of the installer, you will be presented with two choices: "Install Now" and
Introduction to Python 5
"Customize Installation." Clicking on "Install Now" will install Python with the default features, while
clicking on "Customize Installation" will allow you to change the installation location or install other
optional and advanced features. The defaults should work well for now, so we will go with Install Now.
Before clicking on Install Now, make sure to select the Add python.exe to PATH checkbox, as this will
add Python to your system's PATH environment variable and will enable you to run Python from the
command prompt.
Click Yes if it asks for permission to make changes to your device. The installation begins, and all the
required Python files, along with the standard library, will be installed on your system.
After the installation is complete, the following pop-up box will appear. This shows that Python is installed
on your system. Click on Close to complete the installation and exit the installer. The appearance of the
images shown in the screenshots may vary depending on the version of Python that you choose to install.