Mastering
Python 3
Programming
Ultimate guide to learn
Python coding fundamentals
and real-world applications
Subburaj Ramasamy
[Link]
First Edition 2024
Copyright © BPB Publications, India
ISBN: 978-93-55517-128
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.
LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY
The information contained in this book is true to correct and the best of author’s
and publisher’s knowledge. The author has made every effort to ensure the
accuracy of these publications, but publisher cannot be held responsible for any
loss or damage arising from any information in this book.
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.
[Link]
Dedicated to
My better half Chandra and my sons Prabhu
and Kumar
About the Author
Dr. Subburaj Ramasamy, currently an independent
research professor, specializes in machine learning for
artificial intelligence, programming languages, secure
coding and software reliability engineering. He is an Udemy
instructor and has published courses on machine learning,
Python and C++. He served as a professor and consultant in
the Department of Information Technology, SRM Institute of
Science and Technology, Kattankulathur, for 17 semesters.
Earlier, he was a Scientist “G”/ Senior Director in the
Ministry of Electronics and Information Technology,
Government of India. He obtained his PhD degree from the
University of Madras. He holds a Masters degree from Indian
Institute of Technology, Delhi and Bachelors degree from
Alagappa Chettiar College of Engineering and Technology.
He guided four research scholars till award of the Ph.D.
degree, having published about 90 research papers in
international journals and conferences with 500 citations. He
was teaching and providing project guidance to [Link] and
[Link] students at the School of Computing in SRMIST. Dr.
Subburaj is an esteemed member of various associations,
such as the Computer Society of India and IETE. He received
the 17th IETE Lal C Verman Award in 2003. He is the author
of several books on topics such as Total Quality
Management, Software Reliability Engineering, Programming
in Python, Programming in C, and Object Oriented
Programming with C++. He was an authorized trainer of
Carnegie Mellon University/SEI, USA, for software CMM and
certified by Stanford University/Course era on Machine
Learning.
About the Reviewer
Peyush Kumar is an experienced IT professional, with a
distinguished career that spans over 25 years. Graduating
with a [Link] in Computer Science from Punjabi University,
his journey has been marked by impactful contributions
from major tech players, including Zensar, Wipro, and
HCLTech. This includes employment in global settings while
residing for an extended period in the USA. Beyond
showcasing his prowess as a skilled programmer, Peyush
has proved himself as a proficient manager, steering
software development teams towards success.
Peyush’s enthusiasm extends beyond coding; he is also a
passionate educator. His teaching legacy is witnessed in the
diverse array of students, spanning from high school
enthusiasts to seasoned graduates, who have benefited
from his insightful guidance. Residing in Noida with his
family, Peyush balances his love for technology with an
unwavering commitment to family values.
Acknowledgement
I would like to express my sincere gratitude to all those who
contributed to the successful completion of this book.
First and foremost, I extend my appreciation to my family
and friends for their unwavering support and
encouragement throughout this journey.
I am immensely grateful to BPB Publications for their
guidance and expertise in bringing this book to fruition. I
would like to especially appreciate the alert, sharp and
knowledgeable technical reviwer for reviewing the
manuscript thoroughly. I also thank the editors and
administrators of BPB for their support and assistance,
which were invaluable in navigating the complexities of the
publishing process.
Last but not least, I want to express my gratitude to the
readers who have shown interest in my book.
Thank you to everyone who has played a part in making this
book a reality.
Preface
Mastering Python 3 Programming is a must for every
literate. Irrespective of whether you are a seasoned
programmer looking to expand your skill set or an absolute
beginner taking baby steps into the world of programming,
this book is designed to be your companion and
comprehensive guidebook to mastering Python.
Python has emerged as one of the most sought-after
programming languages due to its agility. Its simplicity,
readability, and versatility make it a preferred language for
a wide range of applications, from web development and
data analysis to artificial intelligence and machine learning.
In this book, we have described everything you need to
know to become proficient in Python 3. We will start with the
fundamentals, including basic syntax, data types, and
control structures, before moving on to more advanced
topics such as built-in containers like lists and dictionaries,
object-oriented programming, functional programming, and
advanced file and exception handling.
Throughout the book, you will find bountiful hands-on
examples and exercises to help reinforce your learning.
Whether you prefer to follow along with the code examples
or dive in and start coding on your own, you will have
abundant opportunities to practice and experiment with
Python.
One of the fascinating things about Python is its thriving
ecosystem of batteries included - libraries and frameworks.
In the later chapters, we will explore some of the most
popular Python libraries for tasks such as data structures
and data visualization, giving you the tools you need to start
building your own projects right away.
Whether your goal is to grab a job as a Python developer,
advance in your current career, or simply explore the
exciting world of programming, this book will provide you
with the knowledge and skills you need to succeed. So,
without further ado, let us dive in and start exploring the
wonderful world of Python 3 programming!
The contents of the book are given chapter-wise below:
Chapter 1: Introduction to Python 3 - Discusses the
motivation to learn Python and how to install the Python
development environment. We will be discussing
programming in the interactive mode and script mode and
give examples of both using the above. We will be using
IDLE, throughout the book owing to its merits. We will learn
that the Python frozen binaries bundle together the byte
code of our program files, along with the Python Virtual
Machine interpreter and any Python support files our
program needs, into a single package, a single binary
executable program like .exe file on Windows. By the end of
the chapter, students would have experimented with the
interactive mode as well as create frozen binaries in the
script mode.
Chapter 2: Algorithmic Problem Solving - In this
chapter, the student will learn to design computer based
solutions to problems using algorithms and flow charts. At
the end of the chapter, we describe some of the popular
algorithms in Python. This chapter aims to prepare freshers
for programming with algorithmic thinking. Furthermore, the
algorithms discussed here are used in the rest of the book.
Chapter 3: Numeric Computations and Console Input -
An overview of the major tokens of the Python language,
such as identifiers, keywords, constants or literals, and
operators, is given in this chapter. We will also discuss
expressions, operator precedence, and type conversion. In
this chapter, we also introduce console input using input
and eval functions. We will discuss operations on the bits
using bitwise operators.
Chapter 4: Unicode, Strings and Console Output - In
this chapter, we will discuss character coding, strings, and
slicing. String methods and methods to modify strings will
also be discussed. Then, the chapter teaches converting
ASCII characters to numbers and vice versa using ord () and
chr () functions. We will then move on to discuss console
output. Several methods of formatted printing are also
discussed in the chapter. Then we discuss the bytes ()
function, which returns an immutable bytes object. It can
convert strings into bytes objects.
Chapter 5: Selection and Loops - In this chapter, we will
discuss relational operators and logical operators. Then we
will describe the selection constructs of if, elif, and else and
give programs to illustrate their use. Next, we will give
examples of nested selection constructs and the use of a
ternary operator. Then we will move on to discuss iterations
using while and then for and give examples. We will
demonstrate the use of break and continue keywords in
programs.
Chapter 6: Functions and Recursion - In this chapter,
after discussing the features and benefits of structured
programming, we will give examples of calling a function
multiple times and calling more than one function in a
program. We will also discuss void functions. Then we
discuss fruitful functions, return values, runtime stack, and
Boolean functions. Then, we will discuss the local and global
scope of function parameters. This is followed by positional
arguments and default arguments.
Chapter 7: Lists - In this chapter, we carry out an in-depth
analysis of the Python container list. Then we will discuss list
concatenation, slicing, and nesting. Then we will highlight
the differences between functions and methods in Python
and give examples of methods and functions using lists. List
comprehension, aliasing list, and cloning lists are also
discussed. This chapter also includes several case studies.
Chapter 8: Tuples, Sets, and Dictionaries - In this
chapter, we will discuss 3 more containers – tuples, sets,
and dictionaries. We will discuss the methods and functions
used with all three containers. We will carry out
mathematical operations using sets and set comprehension.
The chapter gives some examples of dictionaries and
iterations over dictionaries, dictionary comprehension, and
nested dictionaries.
Chapter 9: Introduction to Object-Oriented
Programming - In this chapter, we give an overview of the
characteristics of Object-Oriented Programming (OOP).
Class as a blueprint for objects, access control, initializer,
and destruction of objects are discussed in this chapter.
After carrying out operations on objects, the distinction
between class variables and instance variables is brought
out. The overloading functions supported in Python are
illustrated with examples addressing overloading binary
operators - minus operator and the equality operator. At the
end of the chapter, we discuss documentation strings.
Chapter 10: Inheritance and Polymorphism - In this
chapter, we discuss single inheritance, multi-level
inheritance, and multiple inheritance. We will give a
comparison between containership and inheritance, and
implement various types of inheritances. Then we will
discuss the object class and diamond problem. It is followed
by method overriding, polymorphism, and abstract class.
This chapter ends with a discussion on iterators. iterable
and generators.
Chapter 11: File Handling - This is a comprehensive and
important chapter in the book in the context of Machine
Learning and big data analytics. We will discuss reading
from and writing to text and binary files. Implicit reading is
an important addition. It has an interesting case study on
counting the occurrence of each word and each alphabet in
a text file. Java Script Object Notation (JSON) and the
pickle solution are interesting and useful in many
applications. The CSV Files and Command line arguments
are also illustrated in this chapter.
Chapter 12: Exception Handling - We begin the chapter
with a listing of exception classes provided by the Python
standard library. The chapter describes all the five keywords
provided by Python for exception handling. The chapter has
two case studies, building an exception class and knowingw
the cause of the error in the custom exception class
Chapter 13: Gems of Python - This is one of the power-
packed chapters in the book, addressing various special
features of Python 3 such as lambda functions, modules,
date and time, functional programming, first class functions,
decorator function, namespaces and packages.
Chapter 14: Data Structures and Algorithms using
Python - This chapter gives several case studies after
explaining stack, queue, and exception handling. The
chapter briefly explains algorithm analysis - space
complexity, time complexity, and Big Oh notation. We
discuss four popular sorting algorithms in this chapter, such
as bubble sort, selection sort, insertion sort and merge sort.
Chapter 15: Data Visualization - In this chapter, we will
use Python libraries - pandas, Matplotlib and Seaborn to plot
various graphs, charts and diagrams using two datasets
publicly available on the Internet. The reader will be given
URLs to download the data and steps to install libraries.
Chapter 16 : Python Applications and Libraries - In
this chapter, we give an overview of applications of Python,
including libraries used therein as a ready reckoner to help
students to select their future areas of learning. This chapter
covers areas such as web development, data science and
machine learning, Natural Language Processing (NLP),
GUI applications, game development, scripting and
automation, web scraping, database applications, Internet
of Things (IoT) and education.
Code Bundle and Coloured
Images
Please follow the link to download the
Code Bundle and the Coloured Images of the book:
[Link]
The code bundle for the book is also hosted on GitHub at
[Link]
Python-3-Programming. 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 [Link]
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@[Link]
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
[Link] and as a print book customer, you are entitled to a
discount on the eBook copy. Get in touch with us at :
business@[Link] for more details.
At [Link], 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@[Link] 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 [Link]. 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 [Link].
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:
[Link]
Table of Contents
1. Introduction to Python 3
Introduction
Structure
Objectives
History of Python
Major users
Features of Python 3
Applications of Python 3
Advantages of Python 3
Interpreters and compilers
Python Virtual Machine
Interpretation process
Versions of Python
Python implementations
Installing Python
Interactive mode
Integrated Development Environment
What is an Integrated Development Environment?
Pythonʼs Integrated DeveLopment Environment
Script mode programming
Colour coding by IDLE
Execution of Python programs
Dynamically typed vs. statically typed language
Memory administration in Python
Python calculator
Addition
Subtraction
Multiplication
Division
Float division
Integer division
Modulus
Exponentiation
Special characters
Batteries included philosophy
Mathematical functions in Python
Sample program with built-in mathematical functions
Other built-in functions
Frozen binaries executables
Types of errors in programs
Syntax errors
Semantic errors
Conclusion
Points to remember
Questions
2. Algorithmic Problem Solving
Introduction
Structure
Objectives
Computer program development
Steps in computation
Defining the problem
Designing a solution to the problem
Algorithm
Flowchart
Graphical symbols used in flowcharts
Simple sequence
Selection pattern
Repetition pattern
Pseudocode
Flowchart versus pseudocode
Flowchart
Pseudocode
Testing algorithm
Simple rules governing algorithms
Good programming practices
Divide and conquer
Program design
Top-down and bottom-up design
Data organization and data structures
Construction of loops
Writing programs
Modular design
Choice of variable names
Documentation of programs
Program testing
Sample algorithms
Exchanging values of two variables
Decimal base to binary base conversion
Reversing digits of a natural number
Greatest Common Divisor
Prime numbers
Factorial of a given number
Finding the maximum and minimum numbers in a list
Inserting a card in a list of sorted cards
Guess an integer number in the given range
Recursion
Generation of the Fibonacci sequence
Towers of Hanoi
Conclusion
Points to remember
Questions
3. Numeric Computations and Console Input
Introduction
Structure
Objectives
Tokens
Identifiers
Keywords
Literals
Python literal types
Numeric data types
Integer operations
Real number operations
Scientific notation
Complex numbers
Type Boolean
Expressions and operator precedence
Augmented assignment operators
Type conversion
Console input
eval()
Random numbers
Bitwise operators
OR operation – a|b
AND operation a&b
Complement ~a
The left shift a<<4
Right shift a>>2
Exclusive OR of a^b
Conclusion
Points to remember
Questions
4. Unicode, Strings and Console Output
Introduction
Structure
Objectives
Character set
ASCII code
Unicode
String
String concatenation
Finding types
The str class
The str type
Multi-line strings
Method 1: Using triple quotes
Method 2: Enclosing the string within parentheses
Method 3: Using an escape character \
Escaping quotes within strings
Escape sequences
The index in a string
Substring: Slicing
Reversing a string
Immutable strings
Repetition
String methods
Methods for modifying strings
Replace substrings with replace()
ord() and chr() functions
Reversing a string
Console input of a string
Console output
Formatted printing
Using built-in format method
Floating point numbers
Formatting in scientific notation
Formatting as a percentage
Justification while printing
Formatting integers
Formatting strings
Use of %s as a place holder
Using [Link] method
Passing variables to the placeholder
Passing values to the placeholders
Positional arguments
Using Python string module and Template class
Using fstring
Checking whether a string is a palindrome or
anagram
String module constants
Sequence types
Converting string to bytes
Method 1: Using bytes(str, enc)
Method 2: Using encode
Conclusion
Points to remember
Questions
5. Selection and Loops
Introduction
Structure
Objectives
Structuring programs
Relational operators
Logical operators
and operator
or operator
not operator
Selection constructs
Finding whether a number is positive
Swap case
Finding the largest of three numbers
Nested selection constructs
Ternary operator
Iterations
While loop
Testing whether a number is prime using while
loop.
The range function
For loop
Variations in range function
The for loop using list
Finding maximum and minimum numbers in a list
Generation of mathematical tables
Keywords break and continue
Keywords learnt in this chapter
Conclusion
Points to remember
Questions
6. Functions and Recursion
Introduction
Structure
Objectives
Features of structured programming
Benefits of structured programming
Built-in functions
User-defined functions
General form of function
Function definition
Function header
Function body
Function call
Sum of two numbers
Calling functions multiple times
Calling more functions in a program
Reverse function
addDigits function:
The void function
Illustrative programs
Exchange the value of two variables
Distance between two points
Finding square root of a positive number
Finding square root without using math function
Fruitful functions
Return values
Another fruitful function
Runtime stack
Boolean functions
Divisibility of a number
Local and global scope of function parameters
More function concepts
Positional arguments
Default arguments
Variable length arguments
*args and *kwargs
Python *args
Python **kwargs
Recursion
Euclid GCD recursive program
Recursive factorial program
Tail recursion
Calculating the exponential value in Python
Case study: Towers of Hanoi
Conclusion
Points to remember
Questions
7. Lists
Introduction
Structure
Objectives
Containers
Array
List
Mutable sequence
Mutable
Slicing
Getting Python keywords online
List concatenation
Nesting of lists
Built-in functions
Difference between functions and methods
Console input
List methods
Use of keyword in
Loops in list
Method 1
Method 2
Method 3
Method 4
List comprehension
Creating Pythagorean triplets
Aliasing list
Cloning lists
Passing list and returning list
Transpose of a matrix
Arrays in Python
Sum of an array of numbers
Case study: Circulate the values of n variables
Caution about tabs
Case study: Linear search
Case study: Binary search
Conclusion
Points to remember
Questions
8. Tuples, Sets, and Dictionaries
Introduction
Structure
Objectives
Tuple
Built-in functions
Creating tuples from other container types
Built-in functions contd.
Additional operations on tuple
Tuple as a return value
List as a return value
Set
Type set
The set function
Built-in functions
Methods of set class
Mathematical operations
Checking a set in comparison with other sets
Set comprehension
Dictionary
Some examples of dictionaries
Iterations over dictionaries
Method 1
Method 2
Method 3
Method 4
Using built-in functions with dictionary
Dictionary methods
Dictionary comprehension
Nested dictionaries
Conclusion
Points to remember
Questions
9. Introduction to Object-Oriented Programming
Introduction
Structure
Objectives
Object-oriented programming
Encapsulation
Inheritance
Polymorphism
Operator overloading
Advantages of OOP
Class
A simple class
The self
Object
Access control
Object initializer
Destruction of object
The id function and type function
Carrying out operations on objects
Class variables versus instance variables
Operator overloading
Overloading functions supported in Python
Overloading binary operators
Overloaded minus operator
Overloading unary operator
Overloaded == operator
Documentation strings
Conclusion
Points to remember
Questions
10. Inheritance and Polymorphism
Introduction
Structure
Objectives
Reusability
Inheritance
Single inheritance
Multilevel inheritance
Multiple inheritance
Implementing reuse
Containership and inheritance
Containership
Inheritance
Single inheritance
Access types revisited
Multi-level inheritance
Multiple inheritance
The object class
Diamond problem
Method overriding
The isinstance function
Polymorphism
Dynamic binding
Abstract class
Iterators
Iterable
User-defined iterators
Generators
Generator expressions
Conclusion
Points to remember
Questions
11. File Handling
Introduction
Structure
Objectives
Files
Writing to a file
Checking existence of a file
Reading from a file
readline() method
readlines() method
Implicit reading
Text and binary files
Mode parameters
Copying files
Appending text
The with for file close
Case studies
Counting occurrence of each word in a text file
Counting occurrence of each alphabet in a text file
The seek method
Writing to binary file and then reading
Java Script Object Notation
Serialization and deserialization
Serializing JSON
Deserializing JSON
Serializing and de-serializing to and from strings
Pickle solution
Pickle versus JSON
Case study: CSV files
Command line arguments
File copy from source to destination
getopt module
shutil module
Conclusion
Points to remember
Questions
12. Exception Handling
Introduction
Structure
Objectives
Some standard exceptions
Handling exceptions
The syntax for exception handling
Reading file with exception handling
The finally keyword
Word count program with exception handling
Multiple except
Use of else
Value error
Raising exceptions
Case study: Custom exception
Knowing the cause of the error
Conclusion
Points to remember
Questions
13. Gems of Python
Introduction
Structure
Objectives
Lambda functions
Constituents of lambda functions
Syntax and examples
Using lambdas with Python built-ins
Immediately invoked function expression in lambda
Modules
Module [Link]
Module swap_case
Module tup_max.py
Module [Link]
Short names for modules
Import a function from a module
The main module
Importing multiple modules
Symbol table
vars() function
Date and time
Date and Time now
strftime function
Finding elapsed time
Perf_counter function
process_time function
Functional programming
Filtering elements in containers
map() function
Reduce() function
First class functions
Assigning functions to variables
Function passed as parameters to other functions
Define functions inside other functions
Decorators
A simple decorator
Function to be decorated
def decor(fun)
The nested wrap function
Assigning and calling
Decorator function with arguments
@decor1
Case study: Comparing methods by execution times
Built-in decorators
Namespace
Packages
Importing files from a package
Conclusion
Points to remember
Questions
14. Data Structures and Algorithms using Python
Introduction
Structure
Objectives
Data structures
Stack
Case study: Exception handling in a stack
Queue
Case study: Exception handling in queue
Algorithm analysis
Case study: Bubble sort
Time complexity of bubble sort
Case study: Selection sort
Time complexity of selection sort
Case study: Insertion sort
Time complexity of insertion sort
Case study: Merge sort
Time complexity of merge sort
Conclusion
Points to remember
Questions
15. Data Visualization
Introduction
Structure
Objectives
Importance of data
Python libraries for data visualization
Dataset
File formats
DataFrame
pandas
Installing pandas
Reading head() of csv file
Reading tail() of csv file
Matplotlib
Scatter diagram
Relationship between R&D spend and profit
pandas for visualization
Relationship between marketing spend and profit
Relationship between administration and profit
Line chart
Histogram
Second dataset
Getting the first five records of wines
Getting the last five records of the dataset
Getting column headers
Histogram for wines review
Bar chart
Seaborn
Installing seaborn
Scatter diagram using seaborn
Histogram using seaborn
Gaussian KDE inside the plot
Conclusion
Points to remember
Questions
16. Python Applications and Libraries
Introduction
Structure
Objectives
Overview of applications of Python
Libraries used in data structures and algorithms
Tasks in web development
Python libraries for web development
Machine learning
Types of machine learning
Machine learning algorithms
Model evaluation
Hyperparameter tuning
Machine learning applications
Python libraries for machine learning
pandas
NumPy
SciPy
Matplotlib
Seaborn
Scikit Learn
TensorFlow
Keras
Statsmodels
Plotly
SpaCy
Bokeh
Gensim
Natural Language Processing
Theano
PyTorch
Python libraries for data science
Graphical User Interface programming
Languages and frameworks for GUI programming
Python libraries for GUI programming
Game development
Scripting and automation
Web scraping
Database applications
Internet of Things
Education
Conclusion
Multiple choice questions
Questions
Appendix 1: Python Projects
Project 1: Text-to-speech conversion using Python library
Google Text To Speech
Google Text To Speech
Installation of gTTS
Languages supported
Program steps to convert text to speech
Text to speech conversion of string in English
Text to speech conversion of string in Tamil
Text to speech conversion of words in a text file in
English
Text to speech conversion of words in a text file in
Tamil language
Project 2: Offline text to speech conversion using Python
library pyttsx3
Playing from a text file
Appendix 2: List of Built-in Functions in Python
Appendix 3: Answers to Review Questions
Index
CHAPTER 1
Introduction to Python 3
Introduction
Python is one of the popular and widely used high-level
programming languages. It is both a procedure-oriented and
object-oriented programming language like C++. It is also a
web-scripting language like Javascript. The Python Virtual
machine, like Java virtual machine, is the key element of
Python, which facilitates the portability of Python programs
across platforms. Python’s batteries included philosophy is
a boon to the programmers to write compact and error-free
code.
In this chapter, we will be learning the history of Python, its
features, applications, and advantages. The Python 3
language system matching the operating system in our
computer system can be downloaded from
[Link]. After installation, if our computer runs
under Windows operating system, we will get the Python
command line interpreter and Integrated Development
Environment (IDLE) under the start menu in Windows in
the system. We use the statement prompts in the above, in
the interactive mode, to confirm our understanding of the
Python language syntax. The IDLE, in addition, can be used
for writing and executing the programs in script mode. We
get a glimpse of the use of mathematical and other functions
received along with the Python language system. We will
also write simple Python programs in this chapter.
Structure
The chapter covers the following topics:
History of Python
Major users
Features of the language
Applications of Python 3
Advantages of Python 3
Interpreters and compilers
Python Virtual Machine
Interpretation process
Versions of Python
Python implementations
Installing Python
Interactive mode
Integrated Development Environment
Execution of Python programs
Dynamically typed vs. statically typed language
Memory administration in Python
Python calculator
Special characters
Batteries included philosophy
Mathematical functions in Python
Other built-in functions
Frozen binaries executables
Types of errors in programs
Objectives
After studying this chapter, you will understand how to
invoke the Python command line interpreter, carry out a few
calculations, and display a few messages. You would have
invoked IDLE, created a new file, typed a program, saved it
in a directory, and executed the program. You would be able
to use mathematical and other functions and execute
programs in IDLE.
History of Python
Python is a high-level procedure-oriented programming
language like BASIC, COBOL, FORTRAN, and C. It is also an
object-oriented programming language like C++, C sharp,
and Java. It can thus be used for procedure-oriented
programming as well as object-oriented programming.
Python was released for use in the year 1991 by Guido Van
Rossum (b 1956) in Netherlands. Python was named after
the popular British comedy troupe, Monty Python’s Flying
Circus. It is freeware and not a proprietary product. We can
say that it is community owned. It is an open-source
programming language, and software professionals all over
the world contribute to the development of the language.
Python is managed officially by Python Software Foundation,
a not-for-profit organization with its headquarters in
Delaware, United States.
Major users
Many world-class organizations, such as those listed below,
use Python for the development of software products in their
organizations:
Google
Facebook
Instagram
YouTube
Spotify
Quora
Netflix
Dropbox
The National Aeronautics and Space Administration
(NASA), an independent agency of the U.S. Federal
Government responsible for the civilian space program, as
well as aeronautics and space research, uses Python to
develop their professional applications. It is a meritorious
programming language, and hence such big names are using
it extensively, and the user base is growing continually,
besides also being used by tens of thousands of small/mid to
large enterprises.
Python 3 is a popular and high-level computer programming
language known for its simplicity, readability, learnability,
and versatility. We will briefly peruse the features,
applications, and advantages of Python 3 language.
Features of Python 3
Python 3 has many special features, some of them are
unique. The special features of Python are listed below:
Simple and readable syntax: Python emphasizes
code readability and uses a clean and straightforward
syntax, which makes it easy for developers to write and
understand code.
Interpreted language: Python is an interpreted
language, which means code is executed line by line,
making it easy to test and debug.
High-level language: Python abstracts many low-
level details, allowing developers to focus on solving
problems rather than managing memory and other
system-level concerns.
Dynamically typed: Python is dynamically typed,
which means variable types are determined at runtime,
providing flexibility but requiring careful attention to
data types.
Multi-paradigm: Python supports multiple
programming paradigms, including procedural, object-
oriented, and functional programming.
Rich standard library: Python has a rich standard
library that provides modules and packages for a wide
range of tasks, reducing the need for reinventing the
wheel.
Cross-platform: Python is available on multiple
platforms, making it a portable choice for software
development.
Community and ecosystem: Python has a large and
active community of developers, which means a wealth
of third- party libraries, frameworks, and tools are
available.
Python 3 is a versatile language with a strong community
and ecosystem, making it a valuable choice for various
programming tasks and industries.
Applications of Python 3
Python is widely used in a variety of applications, both
scientific and commercial. Some applications of Python are
listed below:
Web development: Python is used for web
development with frameworks like Django and Flask,
making it easy to build web applications and APIs.
Data analysis and visualization: Python, along with
libraries like NumPy, pandas, and Matplotlib, is widely
used for data analysis, scientific computing, and data
visualization.
Machine learning and AI: Python has become the de
facto language for machine learning and artificial
intelligence with libraries such as TensorFlow,
PyTorch, and scikit-learn.
Scientific computing: Scientists and researchers use
Python for numerical and scientific computing tasks
due to its rich ecosystem of scientific libraries.
Automation and scripting: Python is often used for
automating repetitive tasks and writing system scripts.
Game development: Python has libraries like Pygame
for game development.
Desktop applications: Python can be used to build
desktop applications using frameworks like PyQt and
Tkinter.
Networking and cybersecurity: Python is used for
network programming, penetration testing, and
cybersecurity tasks.
Education: Python is a popular choice for teaching
programming due to its simplicity and readability.
Advantages of Python 3
The advantages of Python as a programming language are
plentiful. Some advantages are highlighted here:
Ease of learning: Python’s simple and readable syntax
makes it an ideal language for beginners and
experienced developers alike.
Productivity: Python’s high-level abstractions and rich
standard library allow developers to write code quickly
and efficiently.
Large community: The large and active Python
community means extensive documentation, support,
and a wealth of third-party libraries.
Cross-platform compatibility: Python code can run
on various platforms with minimal modifications,
making it highly portable. Availability of interpreters
for a host of operating systems such as Windows,
Linux, Ubuntu and Apple’s Mac OS.
Versatility: Python is suitable for a wide range of
applications, from web development to data science
and artificial intelligence.
Open source: Python is open source, which means it is
freely available and can be used and modified without
cost.
Interoperability: Python can easily integrate with
other languages like C/C++ and Java, making it
suitable for extending existing software.
Community-driven updates: Python’s development is
community-driven, with regular updates and
improvements.
Produces compact, portable, and readable code.
Needs little memory space for installation and use.
Structured coding to reduce errors.
Dynamic typing: No need to declare the data types of
variables.
Interpreter based language, which finds errors in
statements as soon as they are typed. When we make a
mistake while typing, we hear a beep.
It is both a programming language and a web scripting
language. Since it is interpreted like PHP, it can
perform support functions on the Internet, such as
taking input from HTML and transferring it to the web
server. It can translate source code to machine code
when the program is being executed.
There are no perceptible compiling, linking, and
loading steps before program execution. We simply
type and run the program without these time-
consuming steps visible to the programmer.
Interactive mode is useful for prototyping of the
program before actual coding.
Support for reusability.
No pointers as in language C/C++.
Automatic allocation of memory and garbage
collection.
It has four powerful containers as given below:
Lists
Tuples
Dictionaries
Sets
Can interact with popular frameworks such as .com,
.net.
Supports JavsScript Object Notation (JSON) for data
exchange with files and websites.
Libraries available for game development, database
access, scripting websites and Operating system
interfacing.
Built-in Graphics
Due to the availability of a rich collection of third-party
libraries used for building a host of applications
ranging from websites to scientific tools.
These are some of the power-packed features of the Python
language, and the reader will discover more advantages of
Python as they learn and start using the language for solving
problems in the real world.
Interpreters and compilers
Interpreters and compilers are designed to translate
programs written in high-level languages (source code
understandable by human beings) into machine code
(understandable by computing machines). They have a
similar purpose, that is, they both convert source code to
machine code. They also have differences. A compiler in
general, translates the entire source code into machine
code, which can, in turn, be executed (run) directly by the
operating system as an executable program. Interpreters
execute the code directly. They bypass the compilation
process, or the compilation process is carried out in the
background and not visible to the user, as is the case with
Python. Python is popularly known as an interpreted
language. The term interpreted means that the code is
translated into machine-readable form and executed by the
interpreter one statement at a time. Common interpreters
include BASIC, Perl, Python, and Ruby interpreters.
Python Virtual Machine
The programs we write in Python using its syntax or rules are
stored with .py extension and are called source code. Python,
like many interpreted languages, actually compiles source
code to a set of instructions for a virtual machine. The virtual
machine is software that emulates physical computer
hardware. Python code is translated into intermediate code
by the Python compiler, which has to be executed by a
virtual machine known as the Python Virtual Machine
(PVM). The concept is similar to Java. There is even a way of
translating Python programs into Java bytecode for the Java
Virtual Machine (JVM). The Python virtual machine is a
stack machine. It manipulates several stacks to perform its
operations. This is in contrast with register machines, which
write to and read from memory locations. The outcome of
compilation is neither a source code nor machine code. It is
an intermediate code called bytecode.
PVM is software/interpreter that converts the bytecode to
machine code for the given platform - operating system and
Central Processing Unit (CPU). PVM is also called Python
Interpreter, and this is the reason Python is called an
interpreted language. The user cannot see the bytecode of
the program because this happens internally in memory.
Before the interpreter takes over, Python performs three
other steps, which are lexing, parsing, and compiling, not
visible to the programmer. Together, these steps transform
the programmer’s source code from lines of text into
structured code objects containing instructions that the
interpreter can understand. The interpreter’s job is to take
these code objects and convert them to machine code
matching the CPU and the platform used for executing the
Python programs.
There is a relationship between the compiler and interpreter
when it comes to the Python language. The compiler
converts the Python code to bytecode. Bytecode is an
intermediate representation of Python code, which expresses
the source code that we write in a way the interpreter can
understand.
The bytecode is interpreted by the interpreter. The Python
interpreter is a bytecode interpreter. Its input is instruction
sets called bytecode. When we write a Python program, the
lexer, parser, and compiler generate code objects for the
interpreter to operate on. Each code object contains a set of
instructions to be executed. It is the bytecode and other
information that the interpreter will need.
The Python compiler converts the file with .py extension, the
source file into a .pyc bytecode for the Python virtual
machine. The .pyc file contains bytecode, which is a compiled
version of the Python file. Python automatically generates
this file to improve performance. The .pyc file has a bytecode
which is platform independent. It can be executed on any
operating system that supports a .pyc format. An interpreter
executes this bytecode on the virtual machine of the
computer.
It may be a surprise to hear that compiling is a step in
executing Python code at all. Python is often called an
interpreted language like Ruby or Perl, as opposed to a
compiled language like C or Java. However, this terminology
is not as precise as it may seem. Most interpreted languages,
including Python, do involve a compilation step. The reason
Python is called interpreted is that the compilation step does
relatively less work than in a compiled language and the
interpreter does relatively more.
While interpreters offer several advantages for running small
programs, interpreted languages also have some limitations.
Programs written for an interpreter may not be able to use
built-in system functions or access hardware resources like
compiled programs. The interpreters are slower than
compilers.
Interpretation process
When we write Python programs, the compiler converts
source code written by the developer into an intermediate
language which is again translated by the interpreter into
machine language that is executed. The Python program we
write is compiled into Python bytecode by the compiler,
which creates a file with the extension .pyc. The bytecode
compilation happens internally and is completely hidden
from the programmer. Compilation is simply a translation
step, and bytecode is a lower-level and platform-independent
representation of the source code. Each of the source
statements is translated into a group of bytecode
instructions. This bytecode translation is performed to
quicken the execution of source code statements.
The .pyc file, is created corresponding to each .py file in the
compilation step. The .pyc files are typically generated
automatically by the Python interpreter when you import or
run a Python script (.py file). They are stored in a directory
called __pycache__. The __pycache__ directory is located in the
same directory as the corresponding Python source file. The
.pyc is then executed by appropriate virtual machines. We
can see the contents of .pyc (Python Compiled) files, but they
are not meant to be human-readable. They contain
bytecode, which is a lower-level, platform-independent
representation of the original Python code.
The Virtual Machine iterates through the bytecode
instructions, one by one, to carry out their operations. The
Virtual Machine is the runtime engine of Python, and it is
always present as part of the Python system, and is the
component that truly runs the Python scripts.
Versions of Python
There are 2 versions of Python:
Python 2
Python 3
Python 2 is the legacy version. We will learn the latest
version, that is, Python 3, since Python 2 may eventually not
exist. The applications/programs developed in Python 2 may
cease to be used.
Python implementations
Python represents the specifications of the programming
language. It is implemented with compilers and interpreters.
They can be implemented in different ways. The various
Python implementations are discussed below:
CPython: This is the default and most widely used
implementation of Python and is written in C. This is an
interpreter and has a foreign function interface with
languages like C. When we download Python from
[Link] we get this implementation.
PyPy: written in a subset of Python language called
RPython. The programs execute fast in PyPy since
there is a Just-In-Time (JIT) compiler added to the
PVM.
Jython: It is written in Java language. It is designed to
run Python in the Java platform. Jython compiler
compiles Python programs, not as Python bytecode, but
as Java bytecode. Obviously, Java bytecode can be
executed in JVM and not PVM.
Iron Python: It is written in C# (C sharp).
Anaconda Python: It is meant for big data
applications.
Installing Python
The following are the web resources for downloading the
Python language system from Python Software Foundation:
[Link]/ to download Python version 3.x.x.
[Link]/doc for downloading official tutorial
and documentation.
We will be starting the Python learning journey along. You
can download Python language software for free. While
downloading, choose Python 3.x.x, matching the operating
system on your computer. Follow the steps, and choose the
default option for every question, and install Python for the
chosen operating system. Python will be installed in your
system.
Once Python is installed, we find new items under the Start
menu in Windows platform. Python installer has given us two
important tools, as given below:
Command-line Python Interpreter
A program called Integrated Development
Environment (IDLE)
Python provides a Python Shell (also known as Python
Interactive Shell) which is used to execute a single Python
command and get the result. Once you have installed Python
3, for instance for Windows 11, search for Python in the
command prompt in desktop, select it, and hit the Enter key.
By hitting the Enter key we are executing Python.
Immediately, we are presented with an interactive Python
shell known as Python Command-line Interpreter or Read
Evaluate Print Loop (REPL). The REPL, as shown in the
following figure will appear on your video monitor and will be
waiting for our command to be typed:
Figure 1.1: A view of the Command Line Interpreter
Interactive mode
On top of the screenshot, represented by Figure 1.1, you can
see that we have downloaded the latest Python version. On
the third line, you can see the symbol >>>. This is called the
Python statement prompt. At this stage, we should
understand console input and console output. Console input
means receiving input from the keyboard and console output
means displaying output to the monitor in your laptop.
Python is waiting for us to give our commands for execution.
Now type the following in the console input, that is, the
keyboard, after the statement prompt, and press the Enter
key in your keyboard. You will see the output immediately
following what you typed, in the console output that is, the
video monitor:
>>> print('Hello World')
Hello World
Congrats! You now have experience of running a Python
program.
The print is a built-in function of Python, and it is typed in
lowercase. It is used to print or display a word or string on
the console monitor. A string is one of the built-in datatypes
containing Unicode characters. The collection of characters
‘Hello World’ is enclosed within single quotation marks and
parentheses. The collection of characters is known as a
string in the programming world. We have carried this out in
the console. We received the input from the keyboard when
we typed the statement: print('Hello World'). The
statement we typed appears on the monitor, followed in the
next line by the output of the program. It would be
interesting to learn Python if the reader follows the author by
typing and executing the programs.
The string can also be enclosed within double quotes, and
you will get the same result. Let us repeat the same exercise
with double quotes:
>>> print("Python is easy to learn")
Python is easy to learn
We will notice two things:
Double quotes to enclose string works fine. So, strings
can be enclosed either between single quotes or double
quotes.
The output of the program statement, if it is correctly
entered, appears instantly. If not, we will get an error
message and cannot proceed with the execution of the
program.
The reader may be curious to know how Python gives an
error message. An erroneous statement captured is shown in
the following figure for you to observe:
Figure 1.2: An instance of syntax error
What do you notice? It says syntax error and gives some
ideas to correct the same. We will study syntax errors at the
end of the chapter. Let us correct the error and run the
program again. It is given in the following figure:
Figure 1.3: Display after the error was corrected
This type of program execution is called program execution
in the interactive mode.
In this mode, we typed only one statement at a time. The
prompt (three greater than signs: >>>) is also called the
primary prompt. Sometimes, we may need to execute a
multiline construct in the interactive mode. In such cases,
the interpreter provides a secondary prompt which is 3 dots
(…), as the following code illustrates:
>>> cond=True
>>> if cond==True:
... print('condition is ', cond)
...
condition is True
When the program statement continues to the next line, the
Python shell adds the three dots automatically, indicating
that it is a continuation line.
We carried out the above experiments in Python interactive
shell. It is also called Python Command-line Interpreter or
Read Evaluate Print Loop or simply Python interpreter.
Integrated Development Environment
Running a program in the interactive mode in the Python
interpreter is fine for prototyping or clearing our doubts. But,
in practice, we must create fruitful programs in the file and
not in the command line. What do we do then? We can use
an integrated program development environment.
What is an Integrated Development
Environment?
An Integrated Development Environment (IDE) includes
not just the standard code editor for managing the code but
also provides a comprehensive set of tools for its debugging,
execution, and testing, which is an absolute must for
software development. Some IDEs also come with built-in
compilers and interpreters. Some of the popular IDEs for
Python are given below:
PyCharm
Spyder
Eclipse+Pydev
Pythonʼs IDLE
Wing IDE
Cloud9 IDE
Visual Studio Code
Atom
Jupyter Notebook
Pythonʼs Integrated DeveLopment Environment
We will use Pythonʼs Integrated DeveLopment
Environment (IDLE) in this book, which is easy to use and
comparable in performance to the IDEs listed above.
Furthermore, IDLE is given to us by [Link] along
with the Python language system. When we download
Python on the Windows platform, an Integrated Development
Environment called IDLE will also be downloaded
automatically with the interpreter. On Windows, IDLE is
bundled with a Python interpreter. If you are using other
operating systems, you need to install them separately.
We can launch IDLE by searching and selecting IDLE on the
desktop. When we type IDLE and hit the Enter key, the
following figure is displayed:
Figure 1.4: A view of IDLE
As you will see, it is a Python 3.8.2 Shell. IDLE comprises of a
Python shell and Python editor. Note that we can also use the
IDLE shell in the interactive mode as an interpreter to run or
execute program statements as we had carried out with the
command line interpreter. Type the following in the
statement prompt in IDLE, and the output follows instantly:
>>> print('working with Python is simple')
working with Python is simple
Notice that IDLE also provides a statement prompt, and thus
we get two sources for Python shell when we download
Python for Windows. IDLE is an alternative to the command-
line interpreter.
The Python editor in IDLE provides the following facilities:
Create a new program file in the text editor of IDLE by
selecting file new in the menu on top of IDLE.
Open an existing file by selecting file open.
Save the file by selecting file save as.
Edit the file by selecting edit.
Run the file by selecting file run.
Script mode programming
In IDLE, open a new file and type the following:
# python [Link]
print('Python is an interpreted language')
print('python is also a scripting language')
Now save the file as [Link].
Now click Run in the task bar of IDLE or press the shortcut
key F5, and you will get the following output:
============================== RESTART: E:/[Link]
=============================
Python is an interpreted language
python is also a scripting language
The steps involved in creating a text file and executing in
IDLE are as follows:
1. Open a new file in the IDLE text editor.
2. Type the program in the text editor.
3. Save it.
4. Select Run in the Run menu or press F5.
The first line in the above program starts with a #. It
indicates that whatever is typed in that line following # is a
comment, and it will not be executed. The other two
statements following it are executable. The result indicates
the same.
A text file can be created in the built-in text editor of IDLE or
Notepad++.
Typing a statement in the statement prompt either in Python
interpreter or IDLE and executing it is called running Python
in interactive mode. Running a program from a script file is
called running Python in script mode.
Colour coding by IDLE
IDLE is a multi-window text editor. It provides syntax
highlighting and smart indenting. Indenting is a rule in
Python and if indenting is not appropriate, the interpreter will
throw a syntax error. A new Python programmer may have
trouble with indenting. IDLE groups statements by proper
indenting through its built-in smart indenting facility.
Notice that IDLE has its own color coding scheme to assist
the user. When we executed the above statements on the
computer, we would have noticed three different colors in
the program statements. IDLE uses a color scheme as given
below for the guidance of the programmer:
Dark red: Comments
Green: String
Purple: Built-in functions such as print. User-defined
functions will be coded in Blue.
Light red: Error messages like Syntax Errors
Blue: Program output and user defined functions
Orange: Keywords/commands
Black: Data and variables
We can type or write statements in any text editor, such as
Notepad. Do not use Microsoft Word or other documents to
write the code. When we open a new file in IDLE, we get a
text editor automatically in which we can write the program.
We can also open an existing file and modify it. The files we
create in this manner are known by the following names:
Source file
Script file
Module
Since Python files are stored with .py extension, they are
called dot py files.
Execution of Python programs
Let us get a clear picture of how a Python program is
executed:
1. We type the source code in Notepad and save it with .py
extension. For example, [Link].
2. Python compiler converts the above as a bytecode
understandable by the interpreter in PVM. It is stored
internally as [Link]. The size of each bytecode is 1
byte (or 8 bits), hence the name. The bytecode is
computer hardware and platform independent. It can
be executed in any PVM.
3. The PVM and the interpreter therein converts bytecode
to executable code for the system and platform in
which it will be executed.
4. The machine code is executed in the target machine or
CPU.
Dynamically typed vs. statically typed language
Typing refers to type-checking in programming languages.
The programming languages such as C, C++, Java, and
Golang are statically typed languages, but Python is a
dynamically typed language.
All programming languages classify objects into various
types such as int, float, byte, double, etc. to manage storage
space effectively. While programming in statically typed
languages, the programmer must specify the type of objects
before compilation; otherwise, it will lead to errors. Each
identifier holds an object of a specific type, which cannot be
altered later in statically typed languages. Correct usage of
types will be checked at the time of compilation.
Python being a dynamically typed language, treats all
variables and objects alike, and there is no need to specify
their type in advance. It understands the types and handles
them at the time of execution of the program dynamically
without compromising the quality of the programs. Suppose
var1 is assigned to a string. It can later be assigned to a list
in the same program. Hence it is called a dynamically typed
language. However, such reassignment will lead to errors in
statically typed programming languages such as C, C++,
and Java.
Statically typed programming languages like C, C++, Java,
C#, FORTRAN, BASIC, etc. do type checking (that is, the
process of verifying and enforcing the constraints of types)
at compile-time as opposed to run-time. Dynamically typed
programming languages such as Python do type checking at
run-time instead of compile-time.
A language is dynamically typed if the type of a variable is
checked during run-time. In dynamically typed languages,
variables are bound to objects at run-time through
assignment statements, and it is possible to bind the same
variables to objects of different types during the execution of
the program. Python is a dynamically typed language. It
does not determine the variable type until the code is run.
There is no type declaration in Python. What it does is to
store that value at some memory location and then bind that
variable name to that memory container. To summarize,
type-checking is carried out in two ways as summarized
below:
Static: Data types are checked during compilation.
Dynamic: Data types are checked during execution.
Python being an interpreted language, executes each
statement line by line and thus type-checking is done on the
fly, during execution. Hence, Python is a dynamically typed
language.
Memory administration in Python
In any computer system, the Central Processing Unit
(CPU) is the most important part to carry out various
operations such as arithmetic and logical operations. It is
supported by memory devices to store and retrieve values
temporarily and permanently. Temporary storage is provided
by the read and write memory, popularly called Random
Access Memory (RAM) which is a fast memory device.
Permanent storage is carried out in disc drives, compact
discs, and flash. We also know that the keyboard is the
standard input device, and the console monitor is the output
device.
In Python, everything – various data types such as strings,
containers, functions, and modules - is an object. They need
to be allocated storage or memory space when the program
is executing. When we execute Python programs, memory
allocation, and deallocation are carried out automatically.
Unlike some other languages like C, C++ and Java, users
need not allocate the memory either statically or
dynamically. The memory manager in PVM administers the
memory management for the objects and programs. The
memory manager in the PVM does this job efficiently. To take
care of the storage or memory space, the computer system
or the operating system, allocates memory space called
heap to the programming environment. The size of heap
may vary from machine to machine and depends on the size
of the available RAM in the machine and other workload in
the computer system at that time. The various objects are
allocated memory space in the heap, which is not
transparent to the programmer, but the job is done.
Python calculator
Python, in interactive mode, can be used like a pocket
calculator. It is easy, as the following sections will indicate.
We always wish to execute simple arithmetic operations to
check whether we are doing it right. Therefore, we will carry
out some common arithmetic operations in the Interactive
mode.
Python interpreter acts as a calculator to carry out simple
operations. Let us carry out the basic arithmetic operations
using IDLE in the interactive mode. It can also be carried out
in the command line interpreter.
Addition
Look at the following additions carried out in IDLE. When
both the numbers are integers, we get an integer as output;
otherwise, we get a floating-point number as output as the
listing below indicates:
>>> 5+4
9
>>> 6+3.6
9.6
>>> 3.9+7.1
11.0
We have been adding two numbers at a time. We can add
more numbers as the listing below indicates:
>>> 7+8+9
24
>>> 2.9+3+4+6
15.9
>>> 1+2+3.0+4+5
15.0
Note: When one of the numbers is a floating-point
number as 3.0 in the above example, the result is
displayed as a real number.
Subtraction
In Python, there is no need to specify the type of data.
Moreover, the types can be mixed. The listing of a few
subtractions carried out are shown below:
>>> 8-5
3
>>> 5-8
-3
>>> 10-7.5
2.5
>>> 7.5-10
-2.5
>>> 8.7-3.1
5.6
Multiplication
The addition and subtraction were carried out in interactive
mode in IDLE. Let us carry out multiplication in the
command-line interpreter. The output is listed below:
>>> 5*6
30
>>> 5.0*6
30.0
>>> 7.9*8.1
63.99
There is no difference in execution between Python
command-line interpreter and IDLE as far as executing
statements in the interactive mode. When the types are
mixed such as integer and Floating-point number, Python
recognizes it and deals with it correctly. Notice the comfort,
which is absent in other statically typed languages.
Division
Python supports two types of divisions as written:
Float division using operator /
Integer division using operator //
Float division
Float division means, the division operation continues till the
numbers after decimal point do not exceed the capacity of a
float number. The result, which is the quotient, contains
decimal part. When we carry out float division using /, we
always get the result (quotient) as a real number, even when
the number is evenly divisible by the divisor (that is,
remainder =0) as the listing below indicates. To perform float
division in Python, you can use the / operator:
8/4
2.0
>>> 8/12
0.6666666666666666
>>> 6.25/1.5
4.166666666666667
>>> 2.25/1.5
1.5
Integer division
Integer division means, the output of the division will be an
integer. The decimal part is ignored. In other words, you
would get only the quotient part. The integer division
operation is performed with a double slash//. The following
listing may be perused:
>>> 12//3
4
>>> 13//3
4
>>> 15//3
5
>>> 16.5//4
4.0
>>> 16.5//4.5
3.0
The remainder is ignored in integer division.
Modulus
The modulus (% operator) returns the remainder,
irrespective of whether the numbers are integers or real
numbers:
>>> 8%5
3
>>> 7%2
1
>>> 18%2
0
>>> 18.0%2
0.0
>>> 18.0%2.0
0.0
>>> 12.5%2
0.5
>>> 12.5%2.5
0.0
Exponentiation
The exponentiation operator is double *. Look at the
examples below:
>>> 2**3
8
>>> 2**0.5
1.4142135623730951
>>> 2**2.0
4.0
>>> 2.0**3.0
8.0
The results give no surprises.
Special characters
We use a few special characters in Python, some of which
are listed in Table 1.1:
Special Meaning
character
() Hold parameters passed to a function. For example: print()
# Precedes a comment line
““ Enclosing a string
‘‘ Enclosing a string
‘’’ ‘’’ Enclosing paragraph comment, used when the comments
exceed a line.
Table 1.1: Special characters
Batteries included philosophy
The Python language provides several built-in standard
library functions, which we get automatically when we
download Python. The Python source distribution has long
maintained the philosophy of batteries included - having a
rich and versatile standard library that is immediately
available, without making the user download separate
packages on a need basis. This gives the Python language a
head start in many projects. The Python Enhancement
Proposal (PEP) 206 describes the Python Advanced Library,
a collection of high-quality and frequently used third-party
extension modules. The batteries, that is, the
libraries/frameworks, are available for the following domains:
Web tasks
Scientific programming
Applications development
Education: Game development
Mathematical functions in Python
The math module is a built-in module in Python, which
provides mathematical functions for use in our programs. To
use mathematical functions grouped under this module, we
must import the module using import math. The list of
important functions and constants defined in the math
module is given in Table 1.2:
Function Explanation
ceil(x) Returns the smallest integer greater than or equal to x.
fabs(x) Returns the absolute value of x.
factorial(x) Returns the factorial of x.
floor(x) Returns the largest integer less than or equal to x.
fmod(x, y) Returns the remainder when x is divided by y.
frexp(x) Returns the mantissa and exponent of x as the pair (m, e).
isfinite(x) Returns True if x is neither an infinity nor a Not a Number
(NaN).
isinf(x) Returns True if x is a positive or negative infinity.
isnan(x) Returns True if x is a NaN.
modf(x) Returns the fractional and integer parts of x.
trunc(x) Returns the truncated integer value of x.
exp(x) Returns e**x.
log(x[, Returns the logarithm of x to the base (defaults to e).
base])
log2(x) Returns the base-2 logarithm of x.
log10(x) Returns the base-10 logarithm of x.
pow(x, y) Returns x raised to the power y.
sqrt(x) Returns the square root of x.
acos(x) Returns the arc cosine of x.
asin(x) Returns the arc sine of x.
atan(x) Returns the arc tangent of x.
cos(x) Returns the cosine of x.
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x.
tan(x) Returns the tangent of x.
degrees(x) Converts angle x from radians to degrees.
radians(x) converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
Function Explanation
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
pi Mathematical constant, the ratio of circumference of a
circle to it’s diameter (3.14159...)
e mathematical constant e (2.71828...)
Table 1.2: Important mathematical functions and constants
in Python
Sample program with built-in mathematical
functions
Let us write a program to understand the following three
mathematical functions:
[Link](x)
[Link](x)
[Link](x)
To use mathematical functions, we must import math on top
of the program. We must call the functions with math prefixes
as given below:
# Program [Link]
# Mathematical Functions
Import math
x= -4.51
print([Link](x)) # prints the smallest integer
>= x
print([Link](x)) # prints the absolute value of
x
print([Link](5))# prints the factorial of 5
The result of the program is given below:
======================== RESTART: E:/Py
programs/[Link] =======================
-4
4.51
120
Note that the smallest integer greater than -4.51 is -4. The
absolute value of -4.51 is 4.51 and factorial (5) is 120.
Other built-in functions
There are several other built-in functions in Python in
addition to mathematical functions and the list of some built-
in functions used often are given in Appendix 2. We do not
have to import math to use them. A few such functions are
given with their explanations in Table 1.3:
Function Meaning
abs(var) Absolute value of var
min(x1, x2,…) Smallest element in the collection
max(x1, x2,…) Largest element in the collection
bin(var) Binary equivalent of var
oct(var) Octal equivalent of var
hex(var) Hexadecimal equivalent of var
round(x[,d]) x rounded to d digits after decimal point
divmod(x,y) Returns a pair of (x//y, x%y)
Table 1.3: Other built-in functions in Python
We will use the built-in functions as needed. For the time
being, realize that we can make use of the built-in functions
when needed in our programs conveniently.
Let us understand the following three library functions:
bin(x)
oct(x)
hex(x)
There is no need to import math. The program is given below:
# Program [Link]
# library Functions
x= 27
print(bin(x)) # prints the binary value of x
print(oct(x)) # prints the octal value of x
print(hex(x)) #prints the hex value of x
The result of the program is as follows:
===================== RESTART: E:/Py
programs/[Link] =====================
0b11011
0o33
0x1b
We used the bin(x), oct(x) and hex(x) library functions. Note
the 0b prefix of binary numbers, 0o prefix of octal numbers
and 0x prefix of hexadecimal numbers. There is no prefix for
decimal numbers. This is an example of the clarity of Python.
Frozen binaries executables
Frozen binary executables are packages that combine a
program’s bytecode and the Python interpreter into a single
executable program. With these, programs can be launched
in the same way that we launch any other executable
program. While this option works well for delivery of
products, it is not really intended for use during program
development. We normally freeze just before shipping the
code after development is completed.
Types of errors in programs
Programming is a human activity and not a machine or robot
performed activity so far. It is therefore to err is human, but
the errors should not be repeated. The errors committed
during programming can be classified into the following
categories:
Syntax errors
Semantic errors
We will discuss them briefly now.
Syntax errors
We witnessed a syntax error in this chapter. The Python
language has a set of pre-defined rules for constructing a
program. For instance, the language requires that definition
of every class, method, if, elif, else, for, while, etc. shall end
with a colon. If any of the definitions does not end with a
colon, then it is a syntax error. This is analogous to a
grammatical error in simple English, where if a statement
does not have a verb, we say that there is a grammatical
error. We know that does is a valid verb. But it cannot be
used with we. If we do so, we commit a grammatical error.
Similarly, in Python, braces are a valid language construct
for a set, and the square bracket is used to hold elements of
a list in Python. But they cannot follow the main or any other
method respectively, as given below:
def main{}: # syntax error
def get_data[]: # syntax error
The above are syntax errors. We should use () followed by a
colon after the main and get_data. Thus, we commit syntax
errors when we do not adhere to the rules governing the
Python language. A program with syntax error will give errors
when it is run. What is the secret of eliminating syntax
errors? They are:
Understand the concepts governing the language
thoroughly.
Enter the code carefully.
Read the code, preferably with a checklist containing
commonly committed syntax errors.
Give the code to another person who is knowledgeable
to check independently.
Only after we are satisfied that there are no syntax errors
should we run the program. If any errors are left, the
program will not run, and the run-time system will list the
type of errors along with the statement number in the
program. Sometimes, we may be able to fix the error quickly
by knowing the statement number and the type of error,
such as missing colon or missing parentheses. However, the
interpreter may, at times, flag errors in the wrong place due
to errors in the previous statements. Therefore, one must
check the full program carefully again, find all errors, and
correct them.
Semantic errors
These are other types of errors we find after programming.
The interpreter will not catch these errors since the code
does not violate the language’s syntax. For instance, we
want to square a variable called var and store it to var1.
Therefore, we must write as given below:
var1 = var * var
Instead, we might have written as given below:
var1 = var + var
The computer does not know our true intention. Therefore, in
the above case, it will assume that we want to double the
value of var. Hence, it will not flag an error. Thus, the above
is a logical error or semantic error. A semantic error is an
error due to error in the meaning. This is like saying I am
going to school when actually, the person is going to market.
The above sentence is syntactically correct but semantically
wrong. Then, how to find semantic errors? This can be found
by testing the program. Suppose we want the program to
square a number, then try with a number greater than 2.
From the result obtained, we can conclude whether the
program is semantically correct or not. Even before
execution, the programmer can compute the actions taking
place in each statement and the value of variables in each
step. If we can manually capture the state of each variable in
the program, then it might help to identify the semantic
errors early. The ultimate verification is executing the
program and comparing the actual result with the expected
result.
Conclusion
In this chapter we looked at the history, users, features,
applications, and advantages of Python 3 language. Python
language system was downloaded from [Link],
and the following were installed in our computer system:
Command line Python Interpreter
Python’s Integrated Development Environment
We used both the above to execute python programs in
interactive mode. IDLE was used to write and execute Python
programs in the script mode. We use the “batteries included”
– built-in functions in Python- Mathematical library and other
Python libraries.
In the next chapter, we will study algorithmic problem
solving and learn a dozen widely used algorithms.
Points to remember
Python is a high-level programming language. It was
created in the year 1991 by Guido Van Rossum.
The Python interpreter is a virtual machine, meaning
that it is a program that emulates physical computer
hardware.
Before the interpreter takes over, Python performs
three other steps i.e. lexing, parsing, and compiling.
The compiler converts the Python code to intermediate
bytecode. The bytecode is interpreted by the
interpreter.
The Python interpreter is a bytecode interpreter.
The CPython is the default and most widely-used
implementation of Python and is written in C language.
We will use the new version, Python 3, since Python 2
will cease to be used.
Python installer gives us the following two tools as
given below.
Python command- line interpreter
A tool called IDLE
Notice that IDLE also provides a statement prompt.
A Python program can be created in the built-in text
editor of IDLE.
Typing a statement in the statement prompt either in
Python interpreter or IDLE and executing it is called
running Python in Interactive mode. Running a
program from a script file is called running Python in
script mode.
In Python, there is no need to specify the type of
variables, which is known as dynamic typing.
The Python language provides several built-in library
functions, which we get automatically when we
download Python. It is called batteries included
philosophy.
There are several other built-in functions in Python in
addition to Mathematical functions, which are listed in
Appendix 2.
The executable code in Python can be frozen along
with interpreter before delivery to customers, which is
known as frozen binaries executables.
Questions
Choose the most appropriate answer.
1. Python is:
a. High-level language
b. Object-oriented language
c. Freeware
d. All the above
e. None of the above
2. IDLE:
a. Does not provide interactive mode
b. Does not provide GUI
c. Integrated Development Environment
d. All the above
e. None of the above.
3. Python was created in the year:
a. 2001
b. 1991
c. 1956
d. None of the above
4. Major users of Python include:
a. Google
b. Facebook
c. NASA
d. All the above
e. None of the above
5. Python has:
a. An interpreter
b. Compiler
c. Virtual Machine
d. All the above
e. None of the above
6. A comment statement:
a. Starts with ‘’’
b. Ends with ‘’’
c. Ignored during execution
d. All the above
e. None of the above
7. The output of the following program is:
print([Link](5.6))
a. 5
b. 6
c. 5.6
d. None of the above
8. Print(‘largest number’) has:
a. Semantic error
b. Syntax error
c. No error
d. All the above
e. None of the above
9. Semantic error occurs when:
a. When run-time error occurs
b. When the interpreter flags an error
c. When it gives wrong result
d. All the above
e. None of the above
10. Math is:
a. Library
b. Method
c. All the above
d. None of the above
Write short notes on the following:
History of Python
Frozen binaries
Why is Python popular?
Interpretation process in Python
Virtual Machine
Syntax and semantic error
Interactive mode
Executing code in script mode
Color coding in text editor
Batteries included
Mathematical functions
Other built-in functions
Match the following:
A B
REPL
1. Single line comment
fabs()
2. Interpreter
CPython
3. Mathematical function
#
4. Multiline comment
‘’’ ‘’’
5. Default
Write programs for the following:
Print div and modulus for 500/6.
Find the smallest and largest number in a collection
of numbers.
Given 5 numbers, find their average.
Given the length of a square, print its perimeter and
area.
Convert degree in degree Fahrenheit to degree
Celsius.
Find the remainder when 567 is divided by 2, 3, 5,
and 7.
Given 3 float numbers, add them.
Calculate the volume of a sphere.
To convert foot to meters.
To convert time given in hours and minutes to
seconds.
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:
[Link]