Conceptualizing Python in Google COLAB
Conceptualizing Python in Google COLAB
net/publication/357929808
CITATIONS READS
0 3,558
3 authors:
Mr. M.B.Patil
Chh. Shahu Institute of Business Education & Research
15 PUBLICATIONS 10 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
Soft Computing Model for Secure Auto Program Evaluator View project
All content following this page was uploaded by Poornima Naik on 19 January 2022.
COLAB
By
ISBN: 978-93-93557-43-8
Price: 250.00
Publishing Year 2021
i
Acknowledgements
Many individuals share credit for this book’s preparation. We extend our sincere thanks to Late
Prof. A.D.Shinde, the Founder Director and Managing Trustee who has been a constant source of
inspiration for us throughout our career. His support is really a driving force for us. Also, we would like to
thank Dr.R.A.Shinde, Hon’ble Secretary, CSIBER, Kolhapur for his whole hearted support and continuous
encouragement. We are grateful to Dr. C.S.Dalvi, Director CSIBER, Kolhapur for his invaluable guidance.
We take this opportunity to thank Dr.V.M.Hilage, Former Director and Trustee Member, CSIBER,
Kolhapur, Mr. Bharat Patil, Chairman, Mr. Sunil Kulkarni, Vice Chairman, and Deepak Chougule,
Secretary, KIT, Kolhapur for showing a keen interest in the matter of this book and extending all support
facilities for the in-timely completion of this book. Last but not the least we thank all faculty members and
non-teaching staff of department of computer studies, CSIBER, Kolhapur and Production Engineering
department, KIT’s College of Engineering, Kolhapur who have made contribution to this book either
directly or indirectly.
ii
Preface
It gives us an immense pleasure to bring out a book entitled ‘Conceptualizing Python in Google COLAB’.
The goal of this book is to introduce you to the topic and get you started on your journey to application
development using Python. There are many books, websites, online courses, tutorials etc. on Python. The
current book is different in that it does not provide a lengthy tutorial introduction to a particular aspect
Python, but gives the practical inputs for learning Python in a simple and effective way. The book offers
first hand acquaintance with the Python language and the new constructs added to the language in order to
render it safe, clean and robust. It aims to provide comprehensive material on Python
How is this Book Organized:
This book can serve as textbook for post graduates and reference for any computer graduate. It will also
provide easy reference for Computer Professionals who wants to begin their career in Machine Learning
using Python. This book is precisely organized into twelve chapters. Each chapter has been carefully
developed with the help of several implemented concepts. Dedicated efforts have been put in to ensure that
every concept of Python discussed in this book is explained with help of relevant commands and
screenshots of the outputs have been included. Chapter 1 focuses on development environment offered by
Google COLAB. Chapters 2 through 4 cover the Python language fundamentals focusing on control and
iterative statements, operators along with their applications in basic programs. Python employs blended
programming paradigm in which it is procedural, object-oriented and functional. The best part of all
programming languages reside in a single platform. Chapter 5 focuses on functions in Python with a special
emphasis on Lambda functions. Advanced Python programming concepts such as iterators, closures,
decorators, generators are covered at depth in Chapter 6 and 7. A good and in-depth knowledge of
exception handling enables in writing a reliable and robust code. To cater to this need Chapter 8 unleashes
the salient features of exception handling in Python. Data persistence through file handling is covered in
Chapter 9. Due to the wide application of Regular expressions in pattern matching, Chapter 10 is fully
devoted to understanding of regular expression in Python. Different types of common errors that might
creep in during the execution of a Python program are summarized in Chapter 11. Final Chapter 12 is
devoted to implementation of object oriented concepts in Python. The case study based on object oriented
concept is discussed at depth and implemented in Appendix A.
The part of the content of this book is derived from different sources which are listed at the end in a
‘references’ section.
iii
Contents
iv
v
Conceptualizing Python in Google COLAB
Chapter 1
Introduction to Google COLAB
Colaboratory, or ‘Colab’ for short, is a product from Google Research. Colab allows anybody to
write and execute arbitrary python code through the browser, and is especially well suited to
machine learning, data analysis and education.
If you are exploring Machine Learning but struggling to conduct simulations on enormous
datasets, or an expert playing with ML desperate for extra computational power, Google Colab is
the perfect solution for you. Google Colab or ‘the Colaboratory’ is a free cloud service hosted by
Google to encourage Machine Learning and Artificial Intelligence research, where often the barrier
to learning and success is the requirement of tremendous computational power.
If you want to create a machine learning model but you don’t have a computer that can take the
workload, Google Colab is the platform for you. Even if you have a GPU or a good computer
creating a local environment with anaconda and installing packages and resolving installation
issues are a hassle.
Colaboratory is a free Jupyter notebook environment provided by Google where you can use free
GPUs and TPUs which can solve all these issues. It contains almost all the modules you need for
data science analysis. These tools include but are not limited to Numpy, Scipy, Pandas, etc. Even
deep learning frameworks, such as Tensorflow, Keras and Pytorch are also included.
Benefits of COLAB
Colab is a free Jupyter notebook environment that runs entirely in the cloud.
Besides being easy to use, the Colab is fairly flexible in its configuration and does much of the
heavy lifting for you. It does not require a setup.
• Python 2.7 and Python 3.6 support
1
Conceptualizing Python in Google COLAB
• Free GPU acceleration
• Pre-installed libraries: All major Python libraries like TensorFlow, Scikit-learn, Matplotlib
among many others are pre-installed and ready to be imported.
• Built on top of Jupyter Notebook
• Collaboration feature (works with a team just like Google Docs): Google Colab allows
developers to use and share Jupyter notebook among each other without having to
download, install, or run anything other than a browser. Notebooks can be shared among
team members.
• Supports bash commands
• Google Colab notebooks are stored on the drive
2
Conceptualizing Python in Google COLAB
3
Conceptualizing Python in Google COLAB
On opening the website you will see a pop-up containing following tabs –
On opening the website you will see a pop-up containing following tabs –
Else you can create a new Jupyter notebook by clicking New Python3 Notebook or New Python2
Notebook at the bottom right corner.
On creating a new notebook, it will create a Jupyter notebook with Untitled0.ipynb and save it to
your Google drive in a folder named ‘Colab Notebooks’.
You can click in the file name and change it as shown below. The extension of the file is .ipynb.
4
Conceptualizing Python in Google COLAB
Entering Code
You will now enter a trivial Python code in the code window and execute it.
Enter the following two Python statements in the code window −
import time
print(time.ctime())
Executing Code
To execute the code, click on the arrow on the left side of the code window.
Clearing Output
You can clear the output anytime by clicking the icon on the left side of the output display.
5
Conceptualizing Python in Google COLAB
Insert / Code Cell
Alternatively, just hover the mouse at the bottom center of the Code cell. When
the ‘Code’ and ‘Text’ buttons appear, click on the ‘Code’ to add a new cell. This is shown in the
screenshot below –
6
Conceptualizing Python in Google COLAB
What is GPU?
Graphics processing unit, a specialized processor originally designed to accelerate graphics
rendering. GPUs can process many pieces of data simultaneously, making them useful for
machine learning, video editing, and gaming applications. Select ‘Change runtime type’. Colab
provides the Tesla K80 GPU.
Verifying GPU
Enter the following code in the cell and execute.
import tensorflow as tf
tf.test.gpu_device_name()
7
Conceptualizing Python in Google COLAB
What is TPU?
TPUs are tensor processing units developed by Google to accelerate operations on a Tensorflow
Graph. Each TPU packs up to 180 teraflops of floating-point performance and 64 GB of high-
bandwidth memory onto a single board.
Verifying TPU
Enter the following code in the cell and execute.
import os
if 'COLAB_TPU_ADDR' not in os.environ:
print('Not connected to TPU')
else:
print("Connected to TPU")
Verifying TPU
Select the option Runtime → Change Runtime Type and select ‘TPU’ from the ‘Hardware
Selector’ dropdown list and re-execute the program.
8
Conceptualizing Python in Google COLAB
Verifying TPU
The following output is displayed.
9
Conceptualizing Python in Google COLAB
The following output is displayed:
On selecting the file, the file is uploaded on the drive and the following output is generated:
Mounting Drive
• Unix systems have a single directory tree. All accessible storage must have an associated
location in this single directory tree. This is unlike Windows where (in the most common
syntax for file paths) there is one directory tree per storage component (drive).
• Mounting is the act of associating a storage device to a particular location in the directory
tree. For example, when the system boots, a particular storage device (commonly called
10
Conceptualizing Python in Google COLAB
the root partition) is associated with the root of the directory tree, i.e., that storage device
is mounted on / (the root directory).
• Let's say you now want to access files on a CD-ROM. You must mount the CD-ROM on
a location in the directory tree (this may be done automatically when you insert the CD).
Let's say the CD-ROM device is /dev/cdrom and the chosen mount point is /media/cdrom.
The corresponding command is
Uploading a File:
The uploaded file can be saved in a data frame as shown below:
import io
df2 = pd.read_csv(io.BytesIO(uploaded['file_name.csv']))
11
Conceptualizing Python in Google COLAB
Uploading a File:
Then you’ll see a link, click on link, then allow access, copy the code that pops up, paste it at
“Enter your authorization code:”.
Now to see all data in your Google drive you need to execute following:
! ls "/mntDrive/My Drive“
Mounting Drive Visually
Running a Cell
Make sure the runtime is connected. The notebook shows a green check and ‘Connected’ on the
top right corner.
There are various runtime options in ‘Runtime’.
OR
12
Conceptualizing Python in Google COLAB
To run the current cell, press SHIFT + ENTER.
Running a Cell
!cat /proc/cpuinfo
!cat /proc/meminfo
13
Conceptualizing Python in Google COLAB
File / Save a copy in Drive…
You will see the following screen −
The action will create a copy of your notebook and save it to your drive. Later on you may rename
the copy to your choice of name.
You may also save your work to your GitHub repository by selecting the following menu options
−
File / Save a copy in GitHub...
The menu selection is shown in the following screenshot for your quick reference −
14
Conceptualizing Python in Google COLAB
You will have to wait until you see the login screen to GitHub. Now, enter your credentials. If
you do not have a repository, create a new one and save your project
15
Conceptualizing Python in Google COLAB
Text Cells are formatted using markdown - a simple markup language. Let us now see you how
to add text cells to your notebook and add to it some text containing mathematical equations.
Markdown Examples
Let us look into few examples of markup language syntax to demonstrate its capabilities.
Type in the following text in the Text cell.
This is **bold**.
This is *italic*.
This is ~strikethrough~.
Mathematical Equations
Add a Text Cell to your notebook and enter the following markdown syntax in the text window −
$\sqrt{3x-1}+(1+x)^2$
You will see the immediate rendering of the markdown code in the right hand side panel of the
text cell. This is shown in the screenshot below −
Hit Enter and the markdown code disappears from the text cell and only the rendered output is
shown
16
Conceptualizing Python in Google COLAB
Let us try another more complicated equation as shown here −
$e^x = \sum_{i = 0}^\infty \frac{1}{i!}x^i$
Constraints are
- $3x_1 + 6x_2 + x_3 =< 28$
- $7x_1 + 3x_2 + 2x_3 =< 37$
- $4x_1 + 5x_2 + 2x_3 =< 19$
- $x_1,x_2,x_3 >=0 $
17
Conceptualizing Python in Google COLAB
What is LaTex?
LaTeX is a document preparation system and document markup language. LaTeX is not the name
of a particular editing program, but refers to the encoding or tagging conventions that are used in
LaTeX documents.
18
Conceptualizing Python in Google COLAB
You may enter the email IDs of people with whom you would like to share the current document.
You can set the kind of access by selecting from the three options shown in the above screen.
Click on the Get shareable link option to get the URL of your notebook. You will find options for
whom to share as follows −
• Specified group of people
• Colleagues in your organization
• Anyone with the link
• All public on the web
Now. you know how to create/execute/save/share a notebook. In the Code cell, we used Python so
far.
What is Git?
Git is a free and open source distributed version control system designed to handle everything from
small to very large projects with speed and efficiency.
19
Conceptualizing Python in Google COLAB
import numpy as np
from matplotlib import pyplot as plt
y = np.random.randn(100)
x = [x for x in range(len(y))]
plt.plot(x, y, '-')
plt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6)
plt.title("Sample Plot")
plt.show()
20
Conceptualizing Python in Google COLAB
Step 1 − Open a new notebook and type in the following code in the Code cell −
import numpy
Step 2 − Run the code by clicking on the Run icon in the left panel of the Code cell. Add another
Code cell and type in the following code −
numpy.
Note: If you do not run the cell containing import, the context help is not displayed.
Function Documentation
Colab gives you the documentation on any function or class as a context-sensitive help.
21
Conceptualizing Python in Google COLAB
Line Magics
Type the following code in your code cell −
%ldir
22
Conceptualizing Python in Google COLAB
%history
This presents the complete history of commands that you have previously executed.
Cell Magics
Type in the following code in your code cell −
%%html
<marquee style='width: 50%; color: Green;'>Welcome to CSIBER!</marquee>
Now, if you run the code and you will see the scrolling welcome message on the screen as shown
here −
23
Conceptualizing Python in Google COLAB
Adding Form
For accepting input from user.
Now, select ‘Add a form’ option. It will add the form to your Code cell with a Default title as seen
in the screenshot here −
To change the title of the form, click on the ‘Settings’ button (pencil icon on the right). It will pop
up a settings screen as shown here:
24
Conceptualizing Python in Google COLAB
Select ‘Add a form field’ menu option. A dialog pops up as seen here −
25
Conceptualizing Python in Google COLAB
Leave the Form field type to ‘input’. Change the ‘Variable name’ to ‘num’ and set the ‘Variable
type’ to ‘number’. Save the changes by clicking the Save button.
Your screen will now look like the following with the ‘num’ variable added into the code.
Your screen will now look like the following with the ‘num’ variable added into the code.
26
Conceptualizing Python in Google COLAB
Testing Form
Add a new Code cell underneath the form cell. Use the code given below −
import time
print(time.ctime())
time.sleep(num)
print (time.ctime())
27
Conceptualizing Python in Google COLAB
Edit the form code as shown:
print("Hello",name)
• If the checkbox ‘Allow Input’ is selected, then the user will be able to enter the new item,
if the corresponding item does not exist in the list.
28
Conceptualizing Python in Google COLAB
Since the option ‘Allow-execute cell when fields change‘ is checked when new item is selected
from the drop-down list, the code in the cell is auto executed and the output is refreshed.
29
Conceptualizing Python in Google COLAB
Date Input
Colab Form allows you to accept dates in your code with validations.
Colab Form allows you to accept dates in your code with validations. Use the following code to
input date in your code.
30
Conceptualizing Python in Google COLAB
#@title Default title text
print(start_date)
Installing ML Libraries
Colab supports most of machine learning libraries available in the market. Let us take a quick
overview of how to install these libraries in your Colab notebook.
To install a library, you can use either of these options −
!pip install
or
!apt-get install
Keras
Keras, written in Python, runs on top of TensorFlow, CNTK, or Theano. It enables easy and fast
prototyping of neural network applications. It supports both convolutional networks (CNN) and
recurrent networks, and also their combinations. It seamlessly supports GPU.
To install Keras, use the following command −
!pip install -q keras
PyTorch
PyTorch is ideal for developing deep learning applications. It is an optimized tensor library and is
GPU enabled. To install PyTorch, use the following command −
!pip3 install torch torchvision
31
Conceptualizing Python in Google COLAB
MxNet
Apache MxNet is another flexible and efficient library for deep learning. To install MxNet execute
the following commands −
!apt install libnvrtc8.0
!pip install mxnet-cu80
OpenCV
OpenCV is an open source computer vision library for developing machine learning applications.
It has more than 2500 optimized algorithms which support several applications such as recognizing
faces, identifying objects, tracking moving objects, stitching images, and so on. Giants like
Google, Yahoo, Microsoft, Intel, IBM, Sony, Honda, Toyota use this library. This is highly suited
for developing real-time vision applications. To install OpenCV use the following command −
!apt-get -qq install -y libsm6 libxext6 && pip install -q -U opencv-python
XGBoost
XGBoost is a distributed gradient boosting library that runs on major distributed environments
such as Hadoop. It is highly efficient, flexible and portable. It implements ML algorithms under
the Gradient Boosting framework. To install XGBoost, use the following command −
!pip install -q xgboost==0.4a30
GraphViz
Graphviz is an open source software for graph visualizations. It is used for visualization in
networking, bioinformatics, database design, and for that matter in many domains where a visual
interface of the data is desired. To install GraphViz, use the following command −
!apt-get -qq install -y graphviz && pip install -q pydot
Developing machine learning models requires high processing power. Colab provides free GPU
for your notebooks.
32
Conceptualizing Python in Google COLAB
Chapter 2
Lab Assignments on Python Language Fundamentals
Level – Basic
Python Variables
Python variables are case-sensitive. In the following program, ‘course’ and ‘Course’ are treated
as two distinct variables as demonstrated in the following program:
33
Conceptualizing Python in Google COLAB
Size of Identifier in Python
The maximum possible length of an identifier is not defined in the python language. It can be of
any number.
As shown in the following figure, the size of ‘int’ data type is augmented by 4 bytes for every 230
times increment in the value which accounts for large value that can be stored in ‘int’ data type.
34
Conceptualizing Python in Google COLAB
How bool value is stored in Python.
Similar to programming languages such as C and C++, Python employs the numeric values 0 and
1 for storing the boolean values ‘False’ and ‘True’, respectively.
Hence ‘True’ and ‘False’ values are stored in Python using numeric 1 and 0, respectively.
35
Conceptualizing Python in Google COLAB
In the above program, ‘i’ is an instance of type ‘int’. Hence the first print statement displays ‘True’
and the second print statement displays ‘False’.
36
Conceptualizing Python in Google COLAB
In the following program, the variables ‘a’, ‘b’ and ‘c’ are initialized to a string constant ‘CSIBER’
in a single statement.
37
Conceptualizing Python in Google COLAB
Deleting a variable in Python (NameError)
A reference to the variable can be deleted using ‘del’ operator. The syntax for using ‘del’ operator
is shown below:
Attempting to access a deleted variable later in the program generates ‘NameError’ as shown in
the following program:
In the above program, the variables ‘a’ and ‘b’ are deleted. An attempt to access the deleted
variable will generate ‘NameError’ as shown above:
38
Conceptualizing Python in Google COLAB
Raw String
Raw string can be displayed by prepending the character ‘r’ to the string. Raw string displays the
escape characters without any interpretation as shown in the following programs:
String Indexing
Python enables traversing the string in both directions using positive and negative index,
respectively. For the string of length ‘n’ the indexing in both the directions are depicted in the
following table:
39
Conceptualizing Python in Google COLAB
0 1 2 3 4 5 6 .. n
-n 1-n 2-n 3-n 4-n 5-n 6-n .. -1
In the above example, the different characters of the string ‘CSIBER’ are traversed in both the
directions using the forward and backward indexing mechanisms.
40
Conceptualizing Python in Google COLAB
If the value of the variable is not known at the time of declaration, then it can be initialized with
‘None’ keyword. ‘None’ is not same as zero, False, or empty string. ‘None’ is an instance of
‘NoneType’ class as shown in the following program:
41
Conceptualizing Python in Google COLAB
Note: If a function does not return any value, then it returns ‘None’. In the following program, f is
a function which does not return any value. The last statement in the program, prints the value
returned by the function f() which is ‘None’.
List in Python
A list is data structure which contains comma separated heterogeneous elements enclosed within
a pair of square brackets ([]).
42
Conceptualizing Python in Google COLAB
Features of List:
• List is mutable.
• List maintains insertion order.
• List is iterable.
• List is ordered.
Operations on List
Slicing Operator
A slicing operator is employed for selecting multiple contiguous elements from the list. For
retrieving the elements from the index position ‘i’ to ‘j’ in a list ‘list1’ use the following syntax:
list1[ i : j+1]
Negative Indexing
For retrieving the m elements from the right in a list ‘list1’ use the following syntax:
43
Conceptualizing Python in Google COLAB
Example:
For retrieving last two elements from the ‘l’ shown below,
m=2
-m-1 = -2-1 = -3
list1[-3, -1]
For retrieving the last four elements from the list use the following statement:
l[-5 : -1]
0 1 2 3 4 5 6 7 8 9
44
Conceptualizing Python in Google COLAB
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
The relationship between the positive and negative indexing is given by:
l[n]=l[n-s]
For retrieving the elements from the index position ‘i’ to ‘j’ in a list ‘list1’ using positive indexing,
use the following syntax:
list1[ i : j+1]
For retrieving the elements from the index position ‘i’ to ‘j’ in a list ‘list1’ using negative indexing,
use the following syntax:
list1[ i - s : j + 1 - s]
where, s is the size of the list.
Example:
For retrieving the elements from the index positions 1 to 3 using the positive indexing use the
following statement:
l[1:4]
For retrieving the elements from the index positions 1 to 3 using the negative indexing use the
following statement:
l[-4:-1]
45
Conceptualizing Python in Google COLAB
String Slicing Operator
The slicing operator can also be employed for stripping substrings of a given string employing the
same syntax depicted above.
List is Mutable
List is mutable implies the elements of the list can be modified after creating the list.
List is Iterable
The different elements of the list can be traversed using for loop as shown in the following
program:
46
Conceptualizing Python in Google COLAB
List is Ordered
Two lists are considered to be equal if and only if they contain same elements also in the same
order. In the following program, list1, list2 and list3 contain the same elements. However, list1
and list3 contain the elements in the same order while list1 and list2 contain the same elements in
different order. Hence list1 and list3 are considered to be equal while list1 and list2 are not equal
as demonstrated in the following example:
List Concatenation
The two lists can be concatenated using ‘+’ operator as demonstrated in the following program:
47
Conceptualizing Python in Google COLAB
Rule 2: A single element cannot be added to a list, since ‘int’ type is not iterable. Doing so will
generate ‘TypeError’ as shown in the following figure:
48
Conceptualizing Python in Google COLAB
In the following program, the elective subject is accepted from the end user and is then tested for
the availability in ‘electives’ list.
49
Conceptualizing Python in Google COLAB
50
Conceptualizing Python in Google COLAB
extend() Method
For appending more than one element n a single go, instead use extend() method which accepts a
list as its argument, iterates through the list and appends each element to the list on which extend()
is invoked.
Invoking extend() method on a list by passing a parameter which is not iterable generates
‘TypeError’ as shown in the following program:
51
Conceptualizing Python in Google COLAB
Difference Between append() and extend() Methods
The append() method is used for appending a single element to the list and accepts a single
parameter, the element to be appended to the list. On the contrary, the extend() method accepts a
list as its only argument and appends all the elements to the list by iterating through it.
When an append() method is invoked on a list by passing another list as a parameter, the list passed
in the parameter is appended as an element to the list creating a nested list as demonstrated in the
following program:
On modifying the above program by passing a string to append() method, the string is appended
to the list as shown below:
On passing a string argument to extend() method, the individual characters of a string are
appended to the list as shown in the following figure:
To append a string to the list, modify the above program as shown below.
52
Conceptualizing Python in Google COLAB
Cloning a List
Assigning a list to another list simply copies a reference and will not generate a new list. A single
list is referenced by two distinct references. The list can be modified employing any of the two
references. In the following program, the references ‘numbers’ and ‘numbers1’ refer to the same
list [10, 20, 30, 40]. The elements at the index position 0 and 3 are modified employing reference
‘numbers1’.
53
Conceptualizing Python in Google COLAB
modifying the object referenced by ‘numbers1’ does not modify the object referenced by
‘numbers’.
In the above program, ‘list1’ and ‘list2’ are two different references referencing the same List
object. On the contrary, ‘list2’ and ‘list3’ are two different references referencing the distinct List
objects.
54
Conceptualizing Python in Google COLAB
Shallow Copying Vs. Deep Copying
Shallow Copying
Shallow copying only copies the outer structure i.e. the elements of the outer list and references to
inner lists, if any. As a result, on shallow copying a nested list, the elements of the outer list can
be manipulated independently of each other while the inner lists are shared. In the following
program, ‘numbers’ is a nested list which is cloned using copy() method in a new reference
‘numbers1’. The inner list is manipulated using a reference ‘numbers1’. Since the copying is
shallow, ‘numbers’ list reflects the changes carried out by ‘numbers1’ as shown in the following
program:
Deep Copying
For deep copying a nested list Python supports a deepcopy() method which creates an exact copy
of complete nested structure as demonstrated in the following program. In the following example,
the above program is re-written for deep copying a list. Hence manipulating the inner list using
the reference ‘numbers1’ does not modify the list referenced by ‘numbers’.
55
Conceptualizing Python in Google COLAB
Sorting a List
Python supports sort() method for sorting a list. The sort() method returns ‘None’. The list on
which the method is invoked is sorted and no new list is created as shown in the following program.
56
Conceptualizing Python in Google COLAB
As seen by the output generated above, the ‘id’ of list ’numbers’ before and after sorting is same.
Hence no new list is created. The original list is re-organized.
The following program sorts the list containing the elective subjects in ascending order using sort()
method.
57
Conceptualizing Python in Google COLAB
As seen by the output generated above, the ‘id’ of original list and sorted list are different. Hence
a new list is created after sorting. The following program sorts the list containing the elective
subjects in both ascending and descending order using sorted() method.
58
Conceptualizing Python in Google COLAB
Deleting the Elements of a List – del Method
The del method can be used for one of the following:
• for deleting a single element from the list.
• for deleting range of elements
• for deleting the entire list along with the reference.
del[n:m+1]
The following program deletes the elements at the index position 2 to 4 using del method using
positive indexing.
The syntax for deleting the elements in the index position n-m using negative indexing is
59
Conceptualizing Python in Google COLAB
del[n-s:m-s+1]
In the following example, the above program is re-written using negative indexing.
[1, 2, 3, 4, 5]
Hence n – s = 2 – 5 = -3 and
m-s+1 = 4-5+1 = 0
Deleting All Elements from the list with Reference Intact - clear() Method
clear() method is used for deleting all the elements from the list while keeping the reference intact.
The list reference is not deleted but points to an empty list on invoking clear() method as
demonstrated in the following program:
60
Conceptualizing Python in Google COLAB
61
Conceptualizing Python in Google COLAB
pop() method also accepts an index of the element to be deleted which is a default parameter.
When invoked without any parameter pop() method deletes an element at highest index position.
62
Conceptualizing Python in Google COLAB
Deleting an Element of a List Using remove() Method
remove() method accepts the name of the element to be deleted. If the element is found, then it is
deleted and the remaining elements are re-indexed. If the specified element does not exist in the
list, then ‘ValueError’ is generated as shown below:
If the list contains multiple elements with the name passed to remove() method, only the first
occurrence of the element is deleted. In the following program, the element 1 occurs three times
at index positions 0, 2 and 4, respectively. The remove() method only deletes the element at index
position 0.
63
Conceptualizing Python in Google COLAB
For removing all the occurrences of a given element use the following logic: The code iterates
through the list and deletes all elements with value 1.
64
Conceptualizing Python in Google COLAB
Reversing the List Using reverse() Method
Python supports reverse() method for reversing the elements of a list. The reverse() method does
not create a new list but returns the same list with the elements in reverse order.
As seen by the output generated on execution of the program, the ‘id’ of the list before and after
reversing is the same. Hence no new list is created.
65
Conceptualizing Python in Google COLAB
Nested Lists
A list can be nested inside another list to any level creating a nested list structure. Consider the
following list which is nested upto level 3:
The following program accesses the different elements of list1 and displays the same:
66
Conceptualizing Python in Google COLAB
Tuple in Python
A tuple is data structure which contains comma separated heterogeneous elements enclosed within
a pair of parentheses ().
Features of Tuple:
• Tuple is immutable.
• Tuple maintains insertion order.
• Tuple is iterable.
• Tuple is ordered.
Operations on Tuple
For extracting the elements of a tuple, the slicing operator, positive and negative indexing
mechanism discussed above for a list are also applicable to a tuple. The following program
employs slicing operator for extracting different elements of a tuple.
67
Conceptualizing Python in Google COLAB
Tuple is immutable
Tuple is immutable implies that the elements of a tuple cannot be modified once the tuple is
created. An attempt to modify an element of a tuple generates ‘TypeError’ as shown in the
following figure:
However, tuple concatenation is well defined and concatenation of two tuples generates a new
tuple as demonstrated in the following program. In the following program, the tuple ‘t’ is
concatenated with the tuple (6, 7) which generates a new tuple as confirmed from its ‘id’.
68
Conceptualizing Python in Google COLAB
Tuple Packing and Unpacking
Tuple Packing
Tuple packing refers to assigning values to different elements of a tuple in a single statement. The
syntax of tuple packing is shown below:
Syntax:
var = (ele1, ele2, . . . . , eleN)
After the execution of the above statement, the elements of the tuple are assigned to ‘var’ which
can be accessed using indices as shown below:
var[0]=ele1
var[1]=ele2
var[n-1]=eleN
One-to-one correspondence exists between variables and values. In the above syntax, var1, var2,
etc. are initialized with value1, value2, ….etc., respectively.
For tuple packing to work properly, the no of values specified on the right side of the expression
should exactly be equal to the no. of values on the left hand side of the expression.
69
Conceptualizing Python in Google COLAB
Tuple Unpacking
Tuple unpacking is exact opposite of tuple packing where the list of variables are initialized using
the elements of a tuple.
If the no. of variables is less than the no. of values, ‘ValueError’ is generated with the message
‘too many values to unpack’ as shown in the following figure:
If the no. of values is less than the no. of variables, ‘ValueError’ is generated with the message
‘not enough values to unpack’ as shown in the following figure:
70
Conceptualizing Python in Google COLAB
In the following program ‘stud_info’ is a tuple containing student information pertaining to rollno,
name and division. The tuple is unpacked for extracting rollno, name and division in three distinct
variables.
Tuple is Iterable
The different elements of the tuple can be traversed using for loop as shown in the following
program:
71
Conceptualizing Python in Google COLAB
Tuple is Ordered
Two tuples are considered to be equal if and only if they contain same elements also in the same
order. In the following program, t1, t2 and t3 contain the same elements. However, t1 and t2
contain the elements in the same order while t1 and t3 contain the same elements in different order.
Hence t1 and t2 are considered to be equal while t1 and t3 are not equal as demonstrated in the
following example:
Tuple is Hashable
Since the tuple is immutable it can be used as keys of dictionary. Since list is mutable it cannot be
used as keys of dictionary. An attempt to use list as a key of a dictionary generates ‘TypeError’ as
shown in the following figure:
72
Conceptualizing Python in Google COLAB
73
Conceptualizing Python in Google COLAB
obj1 is obj2 is equivalent to
id(obj1) == id(obj2).
This is demonstrated in the following program:
The value refers to the object content compared by == operator. If the class overrides __eq__()
method, then __eq__() method is invoked when == operator is used. If the class does not override
__eq__() method then the method inherited from object class is invoked where the instances will
be solely compared using their identities.
74
Conceptualizing Python in Google COLAB
Some objects are characterized by the hash value which means they can be used as keys in
the dictionary. Such objects are characterized by the fact that their value remains same for the
life time of the object and as such the objects must be immutable.
Note: If you write an __eq__ method in a custom class, Python will disable this default hash
implementation, since your __eq__ function will define a new meaning of value for its
instances. You'll need to write a __hash__ method as well, if you want your class to still be
hashable. If you inherit from a hashable class but don't want to be hashable yourself, you can
set __hash__ = None in the class body.
__hash__() function, value() function and equality operator (==) return True, if the two objects
have the same content, else return False.
On the contrary, id() function and ‘is’ operator return True, if the two objects are same, else return
False.
Deleting a Tuple
Tuple does not support deleting a single element. Doing so will generate a ‘TypeError’ as shown
in the following program.
However, ‘del’ function can be used for deleting an entire tuple as shown below:
75
Conceptualizing Python in Google COLAB
76
Conceptualizing Python in Google COLAB
77
Conceptualizing Python in Google COLAB
Dictionary in Python
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). They are similar to the hash tables containing key/value pairs. A dictionary key
can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can
be any arbitrary Python object.
Operations on Dictionary
Accessing Keys of a Dictionary
‘dict’ class supports the methods keys() and values() which return a tuple containing list of keys
and a tuple containing list of values in a dictionary as shown in the following program:
78
Conceptualizing Python in Google COLAB
fromkeys() Method of dict class
fromkeys() method of ‘dict’ class can be used for creating the elements of a dictionary as
demonstrated in the following program. The fromkeys() method accepts two parameters, the first
parameter is the list containing keys and the second parameter is a value.
Method 1:
Using the keys() method of a ‘dict’ class.
Method 2:
Using the values()method of a ‘dict’ class.
79
Conceptualizing Python in Google COLAB
Method 3:
Using the items()method of a ‘dict’ class. The items() method of ‘dict’ class returns key/value pair
of each element in the dictionary.
Dictionary is Mutable
In a dictionary the key is unique. The values of the keys can be altered after the dictionary is
created.
80
Conceptualizing Python in Google COLAB
Concatenation of Two Dictionaries
The concatenation operation on two dictionaries is not defined. An attempt to add two dictionaries
generates ‘TypeError’ as shown in the following program:
update() Method
The update() method can be used for updating a dictionary based on the contents of another
dictionary passed to it as an argument.
If the key is already present in the dictionary, the corresponding value is updated, otherwise a new
key/value pair is added to the dictionary as shown below:
81
Conceptualizing Python in Google COLAB
Membership Testing in Dictionary
The ‘in’ operator is used for testing the existence of a key n a dictionary as demonstrated in the
following program:
82
Conceptualizing Python in Google COLAB
Set in Python
Similar to dictionary, {} characters are used for enclosing the elements of a set. A set can contain
only immutable elements. Adding mutable elements to a set generates ‘TypeError’ as
demonstrated in the following programs:
83
Conceptualizing Python in Google COLAB
Features of Set:
• Set is immutable.
• Set elements are unique
• Set elements are not indexed.
• Set does not maintain insertion order.
• Set is iterable.
• Set is not ordered.
Set is Immutable
Set is immutable implies that the elements of a set cannot be modified once the set is created. An
attempt to modify an element of a tuple generates ‘TypeError’ as shown in the following figure:
84
Conceptualizing Python in Google COLAB
Set Elements are Unique
Addition of any duplicate element to the set is discarded by the set as shown in the following
example:
Set Elements are not Indexed – Set Does not Maintain Insertion Order
Displaying the unsorted set multiple times displays the elements in a different order each time. If
the set is sorted the order is maintained as shown below:
Set elements are not indexed. An attempt to access the elements of a set using indexing generates
‘TypeError’ as shown in the following program:
85
Conceptualizing Python in Google COLAB
Set is Iterable
The different elements of the set can be traversed using for loop as shown in the following
program:
86
Conceptualizing Python in Google COLAB
Since the concatenation operation is defined on two lists, for concatenating two sets performs the
following operations:
• Convert the two sets into lists using list() method
• Concatenate the two lists
• Convert the list back into a set
Sorting a Set
Since the order of the elements in a set is insignificant, sorting and reversing the elements of a set
do not create new sets. However, sorted() methods is supported while reversed() method is not
supported on a set, sorted() method returns list as demonstrated in the following program:
87
Conceptualizing Python in Google COLAB
88
Conceptualizing Python in Google COLAB
If the set is unsorted, then add() method inserts the element at random position as shown below:
89
Conceptualizing Python in Google COLAB
90
Conceptualizing Python in Google COLAB
Using set to insert elements in a set
In the following example, the set containing five elements is passed to update() element which
inserts all the elements of a target set to a source set.
If the element does not exist in a set, then remove() method generates ‘KeyError’ as demonstrated
in the following program:
91
Conceptualizing Python in Google COLAB
Deleting an Element from a Set – discard() Method
If the element does not exist in a set, then unlike remove() method discard() method does not
generate any error as demonstrated in the following program:
92
Conceptualizing Python in Google COLAB
93
Conceptualizing Python in Google COLAB
Deleting a set Using del Method
Since set is not indexed, del method cannot be used for deleting the elements of a set. Doing so
generates ‘TypeError’ as shown in the following program:
‘del’ method can however be used for deleting the entire set as shown in the following program:
94
Conceptualizing Python in Google COLAB
Cloning Set
95
Conceptualizing Python in Google COLAB
Set Operations
Different set operations such as union, intersection, set difference, set symmetric difference, etc.
are defined on two sets.
96
Conceptualizing Python in Google COLAB
Set Difference
Difference of two sets is a set containing elements from the first set which are not present in second
set as shown in the following program. Set supports difference() method for the purpose. The same
result can be achieved using ‘-’ operator as well.
97
Conceptualizing Python in Google COLAB
isdisjoint() Method
The two sets are considered to be disjoint, if they have no elements in common. set class supports
a boolean method isdisjoint() to check whether the two sets are disjoint or not.
98
Conceptualizing Python in Google COLAB
difference_update() Method
difference_update() method on the contrary computes the set difference and updates the invoking
set.
intersection_update() Method
intersetion_update() method computes the set intersection and updates the invoking set with the
result of set intersection.
99
Conceptualizing Python in Google COLAB
Symmetric_difference_update() Method
Symmetric_difference_update() method computes the symmetric difference between two sets and
updates the invoking set with the result of set difference.
Frozen Set
Set is immutable. Frozen set is a mutable version of a set. Since the set is mutable, it is not hashable
and hence cannot be used as a key of a dictionary whereas a frozen set can be.
100
Conceptualizing Python in Google COLAB
Application of Set
To find difference between two lists.
The List class does not support ‘-‘ operator for finding the difference between two lists, however
Set class does.
Hence using Set class the difference between the elements of ‘list1’ and ‘list2’ can be computed
as demonstrated in the following program:
101
Conceptualizing Python in Google COLAB
Chapter 3
Lab Assignment on Python Operators and Control Statements
Level – Basic
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
102
Conceptualizing Python in Google COLAB
103
Conceptualizing Python in Google COLAB
Python Assignment Operators
The different assignment operators supported by Python language are depicted in the following
table:
Assume variable a holds 10 and variable b holds 20, then –
104
Conceptualizing Python in Google COLAB
105
Conceptualizing Python in Google COLAB
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following
table lists out the bitwise operators supported by Python language with an example each in those,
we use the above two variables (a and b) as operands –
128 64 32 16 8 4 2 1
60 0 0 1 1 1 1 0 0
13 0 0 0 0 1 1 0 1
60 & 13 0 0 0 0 1 1 0 0
=12
60 | 13 0 0 1 1 1 1 0 1
=61
60 ^ 13 0 0 1 1 0 0 0 1
=49
a = 0011 1100
b = 0000 1101
~a = 1100 0011
The different bitwise operations on operands 60 and 13 are demonstrated in the following program:
106
Conceptualizing Python in Google COLAB
107
Conceptualizing Python in Google COLAB
Short-Circuit Evaluation
In Evaluation of ‘and’ Condition
The following program demonstrates short-circuit evaluation of ‘and’ condition in Python. In the
following program, in the ‘if’ condition, the first condition evaluates to true, hence the second
condition is evaluated which invokes display() method which prints ‘Inside display’ as shown in
the following program:
When the value of ‘x’ is changed to 2, the first condition in the ‘if’ statement evaluates to false
and hence the second condition is not evaluated owing to short-circuit evaluation adopted by
Python.
108
Conceptualizing Python in Google COLAB
When the value of ‘x’ is changed to 20, the first condition in the ‘if’ statement evaluates to true
and hence the second condition is not evaluated owing to short-circuit evaluation adopted by
Python.
109
Conceptualizing Python in Google COLAB
110
Conceptualizing Python in Google COLAB
In the following program, ‘x’ and ‘y’ are two distinct list objects while ‘x’ and ‘z’ are two distinct
references pointing to the same list object. Hence all the three x, y and z have the same content
and == operator used on them evaluates to ‘True’. While the ‘is’ operator used with the operands
‘x’ and ‘y’ evaluates to ‘False’. Hence == operator checks the content of the two operands passed
to it while ‘is’ operator checks the objects referenced by the object variables.
111
Conceptualizing Python in Google COLAB
Note: is compares object references where as == compares object content.
112
Conceptualizing Python in Google COLAB
113
Conceptualizing Python in Google COLAB
For converting the input to the required data type, use one of the type conversion functions, int(),
float()bool() etc. In the following program, ‘age’ is accepted from the user and is converted into
‘int’.
114
Conceptualizing Python in Google COLAB
The different format codes supported by Python are enumerated in the following table:
115
Conceptualizing Python in Google COLAB
To produce the output on the same line, use second named parameter in print() function specifying
the line terminator which by default is new line character, ‘\n’.
The above program is re-written to produce the output in the same line.
116
Conceptualizing Python in Google COLAB
Chapter 4
Lab Assignment on Basic Programs
Level – Basic
Program 1: To Check Whether the Given No is Positive, Negative or Zero
117
Conceptualizing Python in Google COLAB
Using Nested if
118
Conceptualizing Python in Google COLAB
119
Conceptualizing Python in Google COLAB
Program 3: To Find Largest Among Two No.s
120
Conceptualizing Python in Google COLAB
121
Conceptualizing Python in Google COLAB
Using Nested if
122
Conceptualizing Python in Google COLAB
123
Conceptualizing Python in Google COLAB
124
Conceptualizing Python in Google COLAB
125
Conceptualizing Python in Google COLAB
Program 7: Python Program to Print Fibonacci Sequence
126
Conceptualizing Python in Google COLAB
127
Conceptualizing Python in Google COLAB
Program 10:
z = "xyz"
j = "j"
if j in z:
print(j, end=" ")
What will be the output of this statement?
Program 11
What is output on execution of the following program in Python?
x = 'pqrs'
for i in range(len(x)):
x[i].upper()
print (x)
128
Conceptualizing Python in Google COLAB
Program 12
What happens when '2' == 2 is executed?
129
Conceptualizing Python in Google COLAB
Chapter 5
Lab Assignment on Python Functions
Level – Basic
A function is a block of organized, reusable code which can be used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusability.
Defining a Function
The rules for defining a function in Python are enumerated below:
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax:
def <function_name>(<parameter-list>):
“function_docstring”
function_suite
return <expression>
130
Conceptualizing Python in Google COLAB
Example:
In the following example, printme() is a function which accepts a single string parameter and prints
the same.
131
Conceptualizing Python in Google COLAB
Call By Value
In the following program, ‘list’ is a variable local to change() method which is initialized and
printed within the change() method. The list passed to change() method is not used in the function.
Function Arguments
A function can be invoked by using the following types as formal arguments −
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
132
Conceptualizing Python in Google COLAB
133
Conceptualizing Python in Google COLAB
Named Arguments
The following program demonstrates the use of named arguments in Python. When the function is
invoked with different required and named parameters, the values of ‘a’, ‘b’ and ‘c’ are displayed
in the output.
134
Conceptualizing Python in Google COLAB
135
Conceptualizing Python in Google COLAB
Syntax:
lambda <argument_list>:expression
136
Conceptualizing Python in Google COLAB
• Lambda functions have their own local namespace and cannot access variables other than
those in their parameter list and those in the global namespace.
The following examples demonstrate lambda functions for computing the sum of two no.s,
doubling the no. and finding the maximum of two no.s passed to a function, respectively.
Examples:
Write a lambda function to increment the value by 10.
137
Conceptualizing Python in Google COLAB
Write a lambda function to print a string
filter() Function
The filter() function in Python takes in a function and a list as arguments.
The function is called with all the items in the list and a new list is returned which contains items
for which the function evaluates to True. Here is an example use of filter() function to filter out
only even numbers from a list.
138
Conceptualizing Python in Google COLAB
In the following example, filter() function is employed to filter out all even and odd no.s from a
list, list1.
map() Function
The map() function in Python takes in a function and a list. The function is called with all the items
in the list and a new list is returned which contains items returned by that function for each item.
Here is an example use of map() function to double all the items in a list.
139
Conceptualizing Python in Google COLAB
Example:
In the following example, arithmetic() function takes three parameters. The first parameter is a
function which accepts exactly two arguments. The next two parameters are the parameters to the
function passed as a first argument to arithmetic() function. add(), subtract(), multiply() and
divide() are the functions which take exactly two parameters and hence can be passed as first
parameter to arithmetic() function for performing different arithmetic operations on two no.s.
140
Conceptualizing Python in Google COLAB
141
Conceptualizing Python in Google COLAB
Chapter 6
Lab Assignment on Advanced Concepts in Python - I
(Covers Iterators, Closures, Decorators and Generators)
Level – Intermediate
Using Iterator
Iterators are elegantly implemented within for loops, comprehensions, generators etc. Iterator in
Python is an object which can be iterated upon and returns data, one element at a time. An iterator
object implements two special methods __iter__() and __next__() which are collectively referred
to as ‘Iterator Protocol’.
Iterables
An object is said to be iterator, if it supports __iter__() method which returns an iterator. Most of
the in-built classes in Python such as list, tuple, set, string are all iterables.
An iterator supports __next__() method to manually iterator through the items of an iterator. The
__next__() method throws ‘StopIteration’ exception when end of the iteration is reached and no
more data is found as shown in the following programs:
142
Conceptualizing Python in Google COLAB
143
Conceptualizing Python in Google COLAB
to break from the loop when ‘StopIteration’ exception is thrown and no more elements exist in
the iterator.
This technique by which some data (‘Student’ or ‘MSc’ in this case) gets attached to the code is
called closure in Python. This value in the enclosing scope is remembered even when the variable
goes out of scope or the function itself is removed from the current namespace.
144
Conceptualizing Python in Google COLAB
Also, the nested function can modify the non-local variables as demonstrated in the following
program:
As seen in the above program, the nested printer() function was able to access the non-local ‘nm’
variable of the enclosing function.
Closure Functions
We have a closure in Python when a nested function references a value in its enclosing scope
In the case of a closure function, a function is nested within the scope of outer function and is
returned by the outer function as shown in the following program. In the following program, the
greetings() function is publicly visible which returns a nested ‘greet’ function.
145
Conceptualizing Python in Google COLAB
In the above program, the greetings() function was called with the string ‘Student’ and the returned
function was bound to the variable ‘func’. On calling func(), the ‘nm’ was still remembered
although we had already finished executing the greetings() function.
In Python everything is an object, including a function. Hence the function reference can be stored
in a variable which can then be invoked any no. of times as demonstrated in the following program:
In the above program, ‘greeting2’ and ‘greeting3’ both refer to the same function object.
In the following program, the ‘greet’ function reference returned by ‘greetings’ function is stored
in a variable ‘func’ before deleting the ‘greetings’ function.
Here, the returned function still works even when the original function was deleted.
146
Conceptualizing Python in Google COLAB
147
Conceptualizing Python in Google COLAB
Applications of Closures
Closures can avoid the use of global values and provides some form of data hiding. It can also
provide an object oriented solution to the problem.
148
Conceptualizing Python in Google COLAB
The above program is re-written below where inc() and dec() functions now accept two parameters,
the original no and the value by which the number should be incremented or decremented.
149
Conceptualizing Python in Google COLAB
In the following example, C_called() is a higher order function which creates and returns a function
Python_returned().
The function C_called() can be directly invoked without assigning it to a variable as shown in he
following program:
Decorators in Python
A decorator in Python is a function which takes a function as its argument adds some functionality
and returns it. This is also called ‘Meta Programming’ because a part of the program tries to
modify another part of the program at compile time. In the following program,
decorated_geetings() is a decorator which displays a decorated start line before and after invoking
the function passed to is as an argument.
150
Conceptualizing Python in Google COLAB
151
Conceptualizing Python in Google COLAB
Callable
Functions and methods are called callable as they can be called.
In fact, any object which implements the special __call__() method is termed callable. So, in the
most basic sense, a decorator is a callable that returns a callable.
Using Annotation
This is a common construct and for this reason, Python has a syntax to simplify this. The function
to be decorated can be modified with the header which contains ‘@’ symbol along with the name
of the decorator function to which it is to be passed.
@decorator_func
def ordinary_func():
//function suit
is equivalent to
decorator_func(ordinary_func)
152
Conceptualizing Python in Google COLAB
Decorators also employ closures. In the following example, outer_func() is a function which is a
decorator to test() function accepting two arguments. outer_func() defines a nested function,
inner_func() which accepts two arguments and prints them. Since the nested function has access
to the parameters of outer function, the parameters passed to a function func() are accessed by
inner_func() and the same are printed.
153
Conceptualizing Python in Google COLAB
The no. of parameters passed to the function to be decorated should exactly match parameters of
nested function.
Application to Division
In the following example, divide() is a function which accepts two parameters, divides the first
parameter by the second and returns the same.
When the divide() function is invoked by passing 0 as second parameter, the exception
‘ZeroDivisionError’ is thrown as shown in the following figure:
154
Conceptualizing Python in Google COLAB
The problem can be addressed using a decorator. In the following program, smart_divide() is a
decorator to a divide() function which examines the second parameter before dividing the first
parameter by the second. If the second parameter is zero, the message ‘Cannot Divide a by 0’ is
printed and the function returns. If the second parameter is not zero, divide() function is invoked
by passing the two parameters as demonstrated in the following programs:
155
Conceptualizing Python in Google COLAB
Note: Parameters of the nested inner() function inside the decorator is the same as the parameters
of functions it decorates.
Chapter 7
Lab Assignment on Advanced Concepts in Python - II
Level – Intermediate
List Comprehension
List comprehension offers a shorter syntax for creating a new list from the values of an existing
list based on the condition. The element from the specified list is selected if the condition evaluates
to ‘True’, otherwise the element is discarded. The syntax for list comprehension is shown below:
Syntax:
156
Conceptualizing Python in Google COLAB
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Example
Set all values in the new list to ‘mango':
157
Conceptualizing Python in Google COLAB
newlist = [‘mango' for x in fruits]
The expression can also contain conditions, not like a filter, but as a way to manipulate the
outcome:
Example
Return "orange" instead of "banana": (Replaces banana with orange)
newlist = [x if x != "banana" else "orange" for x in fruits]
Without if statement:
The above code creates a new list by copying all elements of list ‘fruits’.
Example:
The following programs demonstrate list comprehension for selecting the elements in the given
range employing a range() function and a condition for filtering the elements from the list.
158
Conceptualizing Python in Google COLAB
Modifying Output
The elements of the original list can be modified while generating a new list. The following
program generates a new list which contains the square root of all elements in original list using
list comprehension.
In the following program, a new list ‘result1’ is generated based on the contents of ‘result’ list
which maps the elements ‘p’ and ‘f’ to ‘Pass’ and ‘Fail’, respectively.
Generator Function
A generator-function is defined like a normal function, but whenever it needs to generate a value,
it does so with the yield keyword rather than return. If the body of a def contains yield, the function
automatically becomes a generator function. In the following example, gen_fun() is a generator
function which yields four values 1, 2, 3 and 4. Similar to iterables such as list, tuple, set etc., a
generator function can be used in for loop for retrieving its elements which invokes __next__()
method on generator function object in each iteration. Similar to iterables, the StopIteration
159
Conceptualizing Python in Google COLAB
exception is throws when __next__() method is invoked on a generator function and value is not
yielded.
Generator Object
Generator function returns a generator object which is iterable. The value yielded by generator
function can be accessed using one of the following approaches:
Method 1:
Using the generator object in ‘for in’ loop.
160
Conceptualizing Python in Google COLAB
Method 2:
Invoking __next__() method on generator object as demonstrated in the following program:
An attempt to invoke __next__() method on generator object past yielded elements throws
‘StopIteration’ exception as demonstrated in the following program:
161
Conceptualizing Python in Google COLAB
162
Conceptualizing Python in Google COLAB
Python generator expression
Generator expression is similar to a list comprehension. The difference is that a generator
expression returns a generator, not a list.
A generator expression is created with round brackets. Creating a list comprehension in this case
would be very inefficient because the example would occupy a lot of memory unnecessarily.
Instead of this, we create a generator expression, which generates values lazily on demand.
Example:
for e in n:
print(e)
Generator Expression
# Demonstrate Python Generator Expression
for e in out:
print(e)
163
Conceptualizing Python in Google COLAB
164
Conceptualizing Python in Google COLAB
Closure Functions
The following program demonstrates a closure function where the ‘outer’ function returns an
‘inner’ function.
In closures, the outer function does not have an access to the parameters of inner function. At
attempt to access the parameters of inner function inside outer function generates ‘NameError’.
165
Conceptualizing Python in Google COLAB
However, the inner function can access the parameters of the outer function as demonstrated in the
following program:
The following program demonstrates generator function yielding the elements of a list.
The following program demonstrates reversing the string using a generator function.
166
Conceptualizing Python in Google COLAB
The following program creates a tuple which contains the square of the elements in the range 0 to
9. The aggregate function sum() is used for computing the sum of square of natural no.s in the
range 0 to 9.
Generator Pipeline
The different generator functions with distinct functionality can be pipelined together to generate
a cumulative effect. In the following example, three generator functions are defined:
even_filter → It accepts a list and yields only even no.s from the list.
multily_by_three → It accepts a list, multiplies each element of the list by 3 and yields.
convert_to_string → It accepts a list and yields the string representation of each element in the list.
167
Conceptualizing Python in Google COLAB
In the main program, the list is defined which is passed as a parameter to a generator function,
even_filter to extract all even no.s from the list. The output of even_filter generator function
becomes input to multily_by_three generator function, which multiplies each element by 3 and
passed as input to third generator function which displays each no. with the string ‘The Number: ‘
prepended to it. The entire generator pipeline is depicted in the following figure:
[1 , 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_filter
[2, 4, 6, 8, 10]
multiply_by_three
convert_to_string
The Number : 6
The Number : 12
The Number : 18
The Number : 24
The Number : 30
The following example demonstrates yet another instance of generator pipeline. The generator
function pass_filter() accepts a list of marks and yields only those values for which marks is greater
than equal to 40. The output of pass_filter() generator is passed as input to add_bonus() generator
function which adds 10 bonus marks to each passed student. Next, ‘for’ loop iterates through the
list and prints the elements.
168
Conceptualizing Python in Google COLAB
pass_filter
add_bonus
50
65
70
169
Conceptualizing Python in Google COLAB
Chapter 8
Lab Assignment on Exception Handling in Python
Level – Intermediate
Exception
A typical program can contain one of the following types of errors:
• Logical Error
• Compiler Error
• Linker Error
• Runtime Error
Logical error can be trapped through exhaustive test cases. Compiler error is tracked by the
compiler and can be fixed, so is the linker error. If the program contains the runtime error, then it
will compile successfully. However, during the execution will generate an error. Such a runtime
error is referred to as ‘Exception’.
An exception can be defined as an unusual condition in a program which the program cannot cope
up with, resulting in the interruption in the flow of the program.
• anticipate and handle the exception in the program and take the corrective measures
• leave it to the system for processing
170
Conceptualizing Python in Google COLAB
171
Conceptualizing Python in Google COLAB
172
Conceptualizing Python in Google COLAB
173
Conceptualizing Python in Google COLAB
Unhandled Exception
When the exception is raised in the program and the program does not handle it, it will be sent to
the system for processing which will result in abnormal termination of the program. The program
ceases to continue its execution as demonstrated in the following program. In the following
example, ‘ZeroDivisionError’ is thrown in statement 3 when attempting to divide a no. by zero
which the system will not handle and is ultimately processed by the runtime system.
Exception Handling
The following program is re-written version of above program for exception handling. All the
statements to be monitored for exception and enclosed within ‘try’ block which is succeeded by
‘except’ block. If the exception is raised in ‘try’ then it will be handled in the succeeding except
block and the program execution continues normally. If the exception is not raised in ‘try’ block
then ‘except’ block is skipped and the program execution continues normally. In either case
program execution continues normally as demonstrated in the following programs. The structure
of exception handling block is shown below:
174
Conceptualizing Python in Google COLAB
try:
.
.
except ExceptionI:
.
.
except ExceptinII:
.
.
except ExceptionN:
.
.
else:
.
.
else Block
The program also can contain ‘else’ block which is executed if the exception is not raised in the
‘try’ block as shown in the following program:
175
Conceptualizing Python in Google COLAB
176
Conceptualizing Python in Google COLAB
Here are few important points about the above-mentioned syntax −
• A single try statement can have multiple except statements. This is useful when the try
block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception (catch all
block).
• After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's protection.
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a variable
follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the exception. The
variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.
The exception instance can be employed for displaying descriptive error messages as shown in the
following program:
177
Conceptualizing Python in Google COLAB
178
Conceptualizing Python in Google COLAB
Note: If the generic except block, ‘Exception’ is placed at the beginning, all exceptions get
processed there and the succeeding exception blocks become unreachable.
Default except
When the ‘except’ is used without specifying the name of the Exception class. It is referred to as
‘default except’. Default ‘except:’ block, if present must be the last except block, otherwise the
compiler error is generated as shown in the following program:
179
Conceptualizing Python in Google COLAB
Python provides another syntax for handling multiple exceptions which is shown below:
Syntax:
except(exception_name1, exception_name2, . . . . , exception_nameN)
All the anticipated exceptions can be enclosed in a pair of parentheses using comma delimiter.
180
Conceptualizing Python in Google COLAB
finally Demo
‘try’ or ‘except’ blocks can be immediately preceded by ‘finally’ block which is guaranteed to be
executed under all circumstances and includes a must execute code. finally block is executed under
the following conditions:
181
Conceptualizing Python in Google COLAB
Case 1: No Exception is Raised
182
Conceptualizing Python in Google COLAB
Case 3: ‘NameError’ Exception is thrown in ‘try’ Block.
183
Conceptualizing Python in Google COLAB
The following table different cases summarized above:
Note: If the exception is raised in outer ‘try’ block and matching inner ‘except’ block is present,
then the exception is not processed there.
In the following program, ‘ArithmeticError’ is raised in the outer ‘try’ block which is handled in
outer ‘except’ block.
184
Conceptualizing Python in Google COLAB
In the following program, ‘StopIteration’ exception is raised in the outer ‘try’ block, but there is
no matching outer ‘except’ block. Hence is handled by the runtime system.
Note: Even if the inner except block is in place for handling ‘StopIteration’ exception, it is not
processed there.
185
Conceptualizing Python in Google COLAB
In the following program, ‘ArithmeticError’ is raised in inner ‘try’ block which is processed in
xception
Both inner and outer except blocks are in place for handling ‘ArithmeticError’ . In such a case the
following rule is employed. ‘If the ArithmeticError exception is raised in the inner ‘try’ block,
then it will be handled in inner ‘except’ block, and if the ArithmeticError exception is raised in the
outer ‘try’ block, then it will be handled in outer ‘except’ block’
In the following program, ‘FileNotFoundError’ exception is raised in the inner ‘try’ block. There
is not inner or outer except block for handling the exception. Hence it will be handled by the
runtime system.
186
Conceptualizing Python in Google COLAB
In the following program ‘ValueError’ exception is raised in the inner ‘try’ block which is
processed in the inner ‘except’ block.
In the following program, ‘NameError’ is raised in the inner ‘try’ block and there is no inner
‘except’ bock for handling it. However, there is outer ‘except’ block present for handling
‘NameError’. Hence the error is processed in outer ‘except’ block.
187
Conceptualizing Python in Google COLAB
188
Conceptualizing Python in Google COLAB
On execution the following output is generated:
189
Conceptualizing Python in Google COLAB
Case 2: ZeroDivisionError Exception is raised in Outer try Block
Modify outer try block as shown below:
190
Conceptualizing Python in Google COLAB
Case 3: ZeroDivisionError Exception is raised in Inner try Block
Modify outer and inner try blocks as shown below:
191
Conceptualizing Python in Google COLAB
192
Conceptualizing Python in Google COLAB
193
Conceptualizing Python in Google COLAB
194
Conceptualizing Python in Google COLAB
On execution the following output is generated:
195
Conceptualizing Python in Google COLAB
Case 6: IOError Exception Raised in Inner try Block
Modify outer and inner try blocks as shown below:
196
Conceptualizing Python in Google COLAB
197
Conceptualizing Python in Google COLAB
198
Conceptualizing Python in Google COLAB
199
Conceptualizing Python in Google COLAB
Valid Exception Handling Structures
Rule 1: ‘try’ block must be followed by either ‘except’ or ‘finally’ block.
200
Conceptualizing Python in Google COLAB
Rule 3: The default except block, if present, should be the last ‘except’ block.
Find Output:
201
Conceptualizing Python in Google COLAB
Rule 4: When more than one exception is specified in a single ‘except’ block, all exceptions
must be enclosed within a pair of parentheses.
def foo():
try:
return 1
finally:
return 2
k = foo()
202
Conceptualizing Python in Google COLAB
print(k)
The finally block is executed even there is a return statement in the try block.
def foo():
try:
print(1)
finally:
print(2)
foo()
No error occurs in the try block so 1 is printed. Then the finally block is executed and 2 is printed.
203
Conceptualizing Python in Google COLAB
Chapter 9
Lab Assignment on File Handling in Python
Level – Intermediate
Uploading the File in Colab
For uploading the file in Colab, click on the ‘Upload File’ icon, browse to the local file system
and select the file to be uploaded as shown in the following figure:
204
Conceptualizing Python in Google COLAB
file_object = open(file_name,[,access_mode],[,buffering])
205
Conceptualizing Python in Google COLAB
Parameter Meaning
file_name A string value containing the name of the file to be accessed.
access_mode It determines the mode in which the file needs to be opened which depends on
the type of operation to be performed on a file. This is optional parameter and
the default file access mode is read (r).
buffering It can take positive, negative or zero values. The default is negative which refers
to the system default. If the buffering value is set to 0, no buffering takes place.
If the buffering value is 1, line buffering is performed while accessing a file. If
you specify the buffering value as an integer greater than 1, then buffering action
is performed with the indicated buffer size.
206
Conceptualizing Python in Google COLAB
207
Conceptualizing Python in Google COLAB
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that
file.
The following program demonstrates different file attributes of a file opened using open() function.
208
Conceptualizing Python in Google COLAB
Closing the File
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file.
It is a good practice to use the close() method to close a file. The syntax for closing the file is
shown below:
Syntax
<file_object>.close()
Python supports a tell() function for querying the position of file pointer. The following program
displays the position of the file pointer when the file is opened in different modes specified above
for writing to the file and reading the file contents.
209
Conceptualizing Python in Google COLAB
FileNotFoundError Exception
FileNotFoundError exception is raised when the file is opened in ‘r’ mode and the file does not
exist at the specified location. If the file is opened in ‘w’ mode and the file does not exist, then the
new file is created.
210
Conceptualizing Python in Google COLAB
Syntax:
<file_object>.write(<string>)
The following program creates a new file with the name ‘foo.txt’, if the file with that name does
not already exist or erases the contents if the file exists and writes the content passed to the write()
method. The file is closed after the write operation is complete.
211
Conceptualizing Python in Google COLAB
In the following program, the file ‘test.txt’ is opened in ‘w’ mode and the string ‘MCA’ is written
to the file.
Refresh Files
To view the changes in the ‘Files’ tab of Colab, click on ‘Refresh’ button at the top.
212
Conceptualizing Python in Google COLAB
Reading Content of the File
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can
have binary data apart from text data. The syntax of read() method is shown below:
Syntax:
<file_object>.read([<bytes>])
Here, the parameter passed to read method specifies the number of bytes to be read from the opened
file. This method starts reading from the beginning of the file and if count is missing, then it tries
to read as much as possible, until the end of file.
In the following program, the file ‘test.txt’ is opened in ‘r’ mode and the entire contents of the file
are read in a string variable, ‘data’.
213
Conceptualizing Python in Google COLAB
The seek(offset[, from]) method changes the current file position. The offset argument indicates
the number of bytes to be moved. The from argument specifies the reference position from where
the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use
the current position as the reference position and if it is set to 2 then the end of the file would be
taken as the reference position.
214
Conceptualizing Python in Google COLAB
Relocating File Pointer
In the following program seek() method is used for positioning the file pointer at the location 10
bytes from the beginning of the file and then the next 15 bytes from the file are read.
As shown in the following program, when the file is opened in ‘r’ mode negative values cannot be
specified for end-relative seeks. While it works fine when the file is opened in ‘rb’ mode as
demonstrated in the following programs:
215
Conceptualizing Python in Google COLAB
In the following program, the file ‘test.txt’ is opened in ‘w+’ mode for performing read and write
operations. After writing ‘MCA’ to the file, the file pointer is positioned at the end of the file. The
seek() method is used for relocating the pointer at the beginning of the file and the entire content
of the file is read in a variable ‘data’ and the same is printed.
Next, file pointer is moved by one byte and the character ‘C’ in ‘MCA’ is replaced with the
character ‘B’.
The file is closed and re-opened in ‘r’ mode and the the entire content of the file is read in a variable
‘data’ and the same is printed.
216
Conceptualizing Python in Google COLAB
217
Conceptualizing Python in Google COLAB
To fix the bug use encode() method of ‘str’ class as shown in the following program:
On reading a binary file using read() method, the text written to the file is enclosed within b’’. To
read the text, use decode() method as shown in the following program:
218
Conceptualizing Python in Google COLAB
219
Conceptualizing Python in Google COLAB
• the file pointer is positioned at the beginning of the file using seek() method and the
contents are read and displayed.
220
Conceptualizing Python in Google COLAB
Append Mode
The append mode enables appending content to the existing content of the file leaving the original
content of the file is intact. In the following program,
• the string ‘MCA in SIBER’ is written to the file ‘test.txt’ by opening it in ‘w’ mode.
• the file is closed and re-opened in ‘a+’ mode for appending the content ‘MBA in SIBER’.
• the file pointer is re-positioned at the beginning of the file using seek() method and the
entire contents of the file are read into a variable ‘data’ and the same is printed.
In text files (those opened without a b in the mode string), only seeks relative to the beginning of
the file are allowed (the exception being seeking to the very file end with seek(0, 2)).
This is because text files do not have a 1-to-1 correspondence between encoded bytes and the
characters they represent, so seek can't tell where to jump to in the file to move by a certain number
of characters.
If your program is okay with working in terms of raw bytes, you can change your program to read:
221
Conceptualizing Python in Google COLAB
Refresh Files
To use this module you need to import it first and then you can call any related functions.
222
Conceptualizing Python in Google COLAB
Renaming a File
The rename() Method
The rename() method takes two arguments, the current filename and the new filename. The syntax
of rename() function is shown below:
Syntax
os.rename(<old_filename>,<new-filename>)
Deleting a File
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted as
the argument. The syntax of remove() method is shown below:
Syntax
os.remove(<file_name>)
223
Conceptualizing Python in Google COLAB
Refresh Files
Directories in Python
All files are contained within various directories, and Python has no problem handling these too.
The os module has several methods that help you create, remove, and change directories.
Syntax:
os.mkdir(<dir_name>)
224
Conceptualizing Python in Google COLAB
Creating Directories
Syntax:
os.chdir(<dir_name>)
Refresh Files
225
Conceptualizing Python in Google COLAB
Printing Current Working Directory
The getcwd() Method
The getcwd() method displays the current working directory. The syntax of the method is shown
below:
Syntax:
os.getcwd()
Removing a Directory
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed. The syntax of the method is
shown below:
Syntax:
os.rmdir(<dir_name>)
226
Conceptualizing Python in Google COLAB
Refresh Files
227
Conceptualizing Python in Google COLAB
Chapter 10
Lab Assignment on Regular Expressions in Python
Level – Intermediate
Regular Expression
A regular expression is a sequence of characters and meta characters that define a search pattern,
mainly for use in pattern matching with strings.
Python has a module named ‘re’ to work with RegEx. Some important functions available in ‘re’
module are listed below:
re.match() Function
re.match() function is used to search pattern within the test_string. It accepts two parameters:
The method returns a match object if the search is successful. If not, it returns None.
re.findall()
228
Conceptualizing Python in Google COLAB
Example 1: re.findall()
re.split()
The re.split method splits the string where there is a match and returns a list of strings where the
splits have occurred.
If the pattern is not found, re.split() returns a list containing the original string.
re.sub()
229
Conceptualizing Python in Google COLAB
The method returns a string where matched occurrences are replaced with the content of replace
variable.
re.subn()
The re.subn() is similar to re.sub() expect it returns a tuple of 2 items containing the new string
and the number of substitutions made.
In the above program, if the statement re.sub() is replaced with re.subn(), a tuple containing the
result string and the no. of occurrences is returned as shown in the following program:
230
Conceptualizing Python in Google COLAB
You can pass count as a fourth parameter to the re.sub() method. If omitted, it results to 0. This
will replace all occurrences. The following program replaces only the first occurrence of the
multiple white spaces within the string with a single space.
231
Conceptualizing Python in Google COLAB
re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the first
location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)
Example:
Here, the variable ‘found’ contains a match object. In the following program, the string ‘SIBER’
is searched in a given string. Since the search is successful, re.Match object is returned as depicted
in the following figure:
Since the string ‘CSIBER’ is not found in the given string, re.search() method returns ‘NoneType’
as demonstrated in the following program:
232
Conceptualizing Python in Google COLAB
Match object
You can get methods and attributes of a match object using dir() function as shown in the following
program:
Some of the commonly used methods and attributes of match objects are:
match.group()
The group() method returns the part of the string where there is a match.
Our pattern (\d{3}) (\d{2}) has two subgroups (\d{3}) and (\d{2}). You can get the part of the
string of these parenthesized subgroups. Here's how:
233
Conceptualizing Python in Google COLAB
The span() function returns a tuple containing start and end index of the matched part.
234
Conceptualizing Python in Google COLAB
Using r prefix before RegEx
When r or R prefix is used before a regular expression, it means raw string. For example, '\n' is a
new line whereas r'\n' means two characters: a backslash \ followed by n.
Backlash \ is used to escape various characters including all metacharacters. However, using r
prefix makes \ treat as a normal character.
Example:
The re attribute of a matched object returns a regular expression object. Similarly, string attribute
returns the passed string.
235
Conceptualizing Python in Google COLAB
MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a list
of commonly used metacharacters:
[] . ^ $ * + ? {} () \ |
Searching a Pattern
Met character . (Single Character)
pattern=':\d+'
236
Conceptualizing Python in Google COLAB
Character Repetitions
The following characters are employed to specify the repetition of characters in a string:
237
Conceptualizing Python in Google COLAB
The search pattern ‘docx?’ (x is optional) matches one of the patterns ‘doc’ or ‘docx’.
238
Conceptualizing Python in Google COLAB
The relationship between the meta characters ‘*’ and ‘+’ is that:
{*} = {} U {+}
The regular expression ab+c will give abc, abbc, abbbc, … and so on.
239
Conceptualizing Python in Google COLAB
240
Conceptualizing Python in Google COLAB
Example :
{2} means that the preceding character is to be repeated 2 times, {min,} means the preceding
character is matches min or more times. {min, max} means that the preceding character is repeated
at least min & at most max times.
Character Classes
A character class matches any one of a set of characters. It is used to match the most basic element
of a language like a letter, a digit, space, a symbol etc. The following table depicts different
character classes which can be used in a regular expression:
Character Class Meaning
/s matches any whitespace characters such as space and tab
/S matches any non-whitespace characters
/d matches any digit character
/D matches any non-digit characters
/w matches any word character (basically alpha-numeric)
/W matches any non-word character
/b matches any word boundary (this would include spaces, dashes,
commas, semi-colons, etc.)
241
Conceptualizing Python in Google COLAB
242
Conceptualizing Python in Google COLAB
Example :
[abc] will match characters a, b and c in any string.
Example :
[^abc] will match any character except a, b, c .
243
Conceptualizing Python in Google COLAB
[first-last] – Character range: Matches any single character in the range from first to last.
Example :
[a-zA-z] will match any character from a to z or A to Z.
You can also specify a range of characters using - inside square brackets.
[a-e] is the same as [abcde].
[1-4] is the same as [1234].
[0-39] is the same as [01239].
244
Conceptualizing Python in Google COLAB
Grouping Characters
A set of different symbols of a regular expression can be grouped together to act as a single unit
and behave as a block, for this, you need to wrap the regular expression in the parenthesis( ).
Example :
([A-Z]\w?) contains two different elements of the regular expression combined together. This
expression will match any pattern containing uppercase letter followed by any optional character.
(w stands for word character, alphanumeric)
[A-Z]\w?
stands for
‘Any one character in the range A to Z followed by an optional white space character’
The pattern a(bc)* matches the strings, a, abc, abcbc, abcbcbc, . . . . while the patter abc* matches
the strings ab, abc, abcc, abccc, . . . .etc.
Alternation ( | ) :
Matches any one element separated by the vertical bar (|) character.
245
Conceptualizing Python in Google COLAB
Example :
246
Conceptualizing Python in Google COLAB
\number :
Backreference:
It allows a previously matched sub-expression(expression captured or enclosed within circular
brackets ) to be identified subsequently in the same regular expression. \n means that group
enclosed within the nth bracket will be repeated at current position.
Example :
([a-z])\1 will match “ee” in Seek because the character at second position is same as character at
position 1 of the match.
Examples:
Regular Expression Meaning
abc* matches a string that has ab followed by zero or more c
abc+ matches a string that has ab followed by one or more c
abc? matches a string that has ab followed by zero or one c
abc{2} matches a string that has ab followed by 2 c
abc{2,} matches a string that has ab followed by 2 or more c
abc{2,5} matches a string that has ab followed by 2 up to 5 c
a(bc)* matches a string that has a followed by zero or more copies of the
sequence bc
a(bc){2,5} matches a string that has a followed by 2 up to 5 copies of the sequence
bc
Bracket expressions — []
Regular Expression Meaning
[abc] matches a string that has either a or b or c and is the same as a|b|c
[a-c] matches a string that has either a or b or c
[a-fA-F0-9] a string that represents a single hexadecimal digit, case insensitively
[0-9]% a string that has a character from 0 to 9 before a % sign
[^a-zA-Z] a string that has not a letter from a to z or from A to Z. In this case the
^ is used as negation of the expression
247
Conceptualizing Python in Google COLAB
Look-ahead and Look-behind — (?=) and (?<=)
d(?=r) matches a d only if is followed by r, but r will not be part of the overall regex match
(?<=r)d matches a d only if is preceded by an r, but r will not be part of the overall regex match
d(?!r) matches a d only if is not followed by r, but r will not be part of the overall regex match
(?<!r)d matches a d only if is not preceded by an r, but r will not be part of the overall regex
match
248
Conceptualizing Python in Google COLAB
Character Validation
249
Conceptualizing Python in Google COLAB
Give the meaning of following patterns:
^a…b$
A string containing exactly five characters starting with ‘a’, ending with ‘b’ and any three
characters between ‘a’ and ‘b’.
[0-9]{2, 4}
^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$
250
Conceptualizing Python in Google COLAB
Chapter 11
Lab Assignment on Language Basics and Error Handling in Python
Level – Intermediate
Program 1: Scope of Variables
Local Scope
A variable declared within a function is local to the function in which it is declared. In the
following program ‘x’ is used in different scopes:
• Global scope
• Local function scope
• Parameter to a function
Even if variable name is ‘x’ its scope is different. In the following program, x is declared as a
global variable which is initialized to 50. The variable with the same name is declared inside a
function func(). However, its scope if limited to a function in which it is declared. When the
function returns the variable goes out of scope.
251
Conceptualizing Python in Google COLAB
Global Scope
The variable declared outside any function attains a global scope and is shared between all
functions in the same program. When a function has a local variable with the same name as global
variable, the local variable takes preference. To access a global variable within a function, use
‘global’ keyword as demonstrated in the following program:
Exercise 1:
What error will occur when you execute the following code?
MANGO = APPLE
On execution of the above program, ‘NameError’ with the message ‘name APPLE is not defined’
is displayed as shown in the following program since in Python a variable cannot be used without
initializing it.
252
Conceptualizing Python in Google COLAB
Exercise 2:
What will be the output of the following Python code?
lst = [1, 2, 3]
lst[3]
On execution of the above code ‘IndexError’ with the message ‘list index out of range’ is
displayed as shown in the following figure. Python performs bounds checking on data structures
such as list, tuple etc.
Exercise 3:
What will be the output of the following Python code?
t[5]
253
Conceptualizing Python in Google COLAB
On declaring a list with the name ‘t’ containing three elements, ‘IndexError’ exception is raised
with the message ‘list index out of range’ as shown in the following figure:
The program executes successfully, on adding three more elements to the list as shown below:
Exercise 4:
What will be the output of the following Python code, if the time module has already been
imported?
4 + '3'
On execution of the above statement, ‘TypeError’ is generated with the message ‘unsupported
operand types’ as shown in the following figure:
254
Conceptualizing Python in Google COLAB
Exercise 5:
What will be the output of the following Python code?
int('65.43')
On execution of the above program ‘ValueError’ is generated with the message ‘Invalid literal
for int()’ as shown in the following figure:
Exercise 6:
What will be the output of the following Python code?
student={“rollno”:1,”name”:”Maya”}
print(student[“division”])
On execution of the above program, ‘KeyError: division’ error is generated since in the ‘student’
dictionary there is no key with the name ‘division’.
KeyError
255
Conceptualizing Python in Google COLAB
IndentationError
Python uses indentation for defining a block of code referred to as ‘Suite’. The indentation error
occurs when the spaces or tabs are not placed properly.
256
Conceptualizing Python in Google COLAB
Chapter 12
Lab Assignment on Object Oriented Programming in Python
Level – Intermediate
Python is an object oriented programming language. Almost everything in Python is an object,
with its properties and methods.
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data attributes
and functions.
257
Conceptualizing Python in Google COLAB
Displaying Document String
Every Python class has a member __doc__() which can be used for accessing the document string
of a class as shown in the following program:
258
Conceptualizing Python in Google COLAB
Constructors
__init__() method is used for defining a constructor in Python which takes ‘self’ as its first
argument. Python rebinds the name __init__ to the __new__ method. This means in the following
program, the first declaration of this method is inaccessible now.
Class Instantiation
To create instances of a class, you call the class using class name and pass in whatever arguments
its __init__ method accepts. The syntax for instantiating an object of the class is shown below:
Syntax:
<instance_name> = <class_name>(<parameter_list>)
259
Conceptualizing Python in Google COLAB
‘
In the above program, the data member with the name ‘name’ is not defined. The bug is fixed in
the following program. The ‘name’ parameter passed to the class constructor is used for
initializing the data member ‘name’ of the class.
260
Conceptualizing Python in Google COLAB
In the following program, ‘empCount’ is a static variable which is shared by all instances of
‘empoyee’ class. However, ‘name’ and ‘salary’ are data members or instance members of the
class. The class has a two argument constructor __init__() for initializing the data members of a
class. The class has two member functions displayCount() and displayEmployee() for displaying
the total count of employees and employee information.
Note: Within the class local variable is referenced directly while class variable is referenced using
the following syntax (using class name):
<class_name>.<class_variable_name> and
There can be only one __init__() method in a class. If the class contains multiple __init__()
methods, then the last __init__() method takes effect by overwriting earlier __init__() methods, if
any as demonstrated in the following program. In the following program, the ‘Person’ class
261
Conceptualizing Python in Google COLAB
contains three __init__() methods of which the last __init__() method will be considered for object
creation. An attempt to create a ‘Person’ object with a single ‘name’ parameter generates
‘TypeError’ with the message ‘__init__() missing one required positional parameter ‘age’’ as
shown below:
Default Arguments
The constructor can accept default parameters. The constructor overloading can be simulated using
default arguments in a constructor as shown in the following program. In the following example,
the ‘Person’ class has two parameter constructor for initializing ‘name’ and ‘age’ data members
which offers three different ways of creating the object of ‘Person’ class as described below:
262
Conceptualizing Python in Google COLAB
Method 2: Using one argument constructor
p1 = Person(name=”Jack”)
The above statement creates a ‘Person’ object with name=’Jack’ and age=20.
p1 = Person(age=30)
The above statement creates a ‘Person’ object with name=’xyz’ and age=30.
263
Conceptualizing Python in Google COLAB
Python employs reference counting mechanism to figure out unneeded objects. Python's garbage
collector runs during program execution and is triggered when an object's reference count reaches
zero. An object's reference count changes as the number of aliases that point to it changes. An
unreferenced object is referred to as ‘garbage’.
An object's reference count increases when it is assigned a new name or placed in a container (list,
tuple, or dictionary). The object's reference count decreases when it's deleted with del, its reference
is reassigned, or its reference goes out of scope. When an object's reference count reaches zero,
Python collects it automatically.
You normally will not notice when the garbage collector destroys an orphaned instance and
reclaims its space. But a class can implement the special method __del__(), called a destructor,
that is invoked when the instance is about to be destroyed. This method might be used to clean up
any non memory resources used by an instance.
In the following program, the ‘Point’ object is referenced by three references, ‘pt1’, ‘pt2’ and
‘pt3’. getrefcount() method of ‘sys’ class is employed for displaying reference count which accepts
a single parameter the name of the reference. Every time a new reference is created to the existing
264
Conceptualizing Python in Google COLAB
‘Point’ class object, the reference count is incremented by 1 till it reaches 3. In the subsequent
statements, the references ‘pt1’, ‘pt2’ and ‘pt3’ are deleted in that order. When no more references
exist for ‘Point’ object it is garbage collected and prior to that __del__() method is invoked which
displays the message ‘Point Destroyed’.
Class IDs
The id() function returns a unique id for the specified object. All objects in Python has its own
unique id. The id is assigned to the object when it is created. In the following example, the ‘Point’
class has a constructor __init__() with two default arguments for initializing the x and y
coordinates and a destructor __del__(). pt1, pt2 and pt3 are three references to the same ‘Point’
object. Hence the ‘id’ is same for all references as shown in the output generated on execution of
the above program:
265
Conceptualizing Python in Google COLAB
When ‘del’ function is used for deleting the object, the destructor __del__() is invoked.
266
Conceptualizing Python in Google COLAB
Function Name Description
getattr(obj, name[, default]) to access the attribute of object.
Example:
getattr(emp1, 'age')
Returns value of 'age' attribute of ‘emp1’ instance.
hasattr(obj,name) to check if an attribute exists or not.
Example:
hasattr(emp1, 'age')
Returns true if 'age' attribute exists in class of which ‘emp1’ is
an instance.
setattr(obj,name,value) to set an attribute. If attribute does not exist, then it would be
created.
Example:
setattr(emp1, 'age', 8)
Sets attribute 'age' of ‘emp’ instance to 8
delattr(obj, name) to delete an attribute.
Example:
delattr(empl, 'age')
Delete attribute 'age' of class of which ‘emp1’ s an instance.
267
Conceptualizing Python in Google COLAB
__module__ Module name in which the class is defined. This attribute is "__main__"
in interactive mode.
__bases__ A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.
The above attribute are accessed for the ‘Employee’ class as shown in the following figure:
Class Inheritance
Inheritance aids in code reusability. If two classes have common traits, then instead of creating the
class from scratch, it can simply be inherited from another class. The class from which a new class
is inherited is referred to as ‘Base’ class or ‘Super’ class and the new class created is referred to
as ‘Derived’ or ‘Sub’ class. The ‘Sub’ class can do one of the following:
• Inherit the members of base class
• Override the members of base class
• Add new data members of functionality to the class
Syntax
Derived classes are declared much like their parent class; however, a list of base classes to inherit
from is given after the class name −
268
Conceptualizing Python in Google COLAB
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
More than one base class can be listed in the parentheses since Python supports multiple
inheritance.
In the following example, ‘Child’ is the derived class of ‘Parent’ which inherits the members of
‘Parent’ class and adds a new member function with the name childMethod()
269
Conceptualizing Python in Google COLAB
Method Overriding
The child class can override the functionality of the parent class to define a different functionality
in a derived class. In the following example, the my Method() method inherited from ‘Parent’
class is overridden in ‘Child’ class.
Modify the above program to initialize the variable ‘c’ with the reference of ‘Parent’ class and re-
execute the program as shown below:
270
Conceptualizing Python in Google COLAB
Access Modifiers in Python : Public, Private and Protected
Various object-oriented languages like C++, Java, Python controls access modifications which are
used to restrict access to the variables and methods of the class. Most programming languages has
three forms of access modifiers, which are Public, Protected and Private in a class. Python uses
‘_’ symbol to determine the access control for a specific data member or a member function of a
class. Access specifiers in Python have an important role to play in securing data from
unauthorized access and in preventing it from being exploited.
271
Conceptualizing Python in Google COLAB
In the above program, ‘name’ and ‘rollno’ are public data members and displayRollno() method
is a public member function of the class ‘Student’. These data members of the class ‘Student’ can
be accessed from anywhere in the program.
272
Conceptualizing Python in Google COLAB
273
Conceptualizing Python in Google COLAB
In the following program, _name, _roll and _elective are private members, __displayDetails()
method is a private member function (these can only be accessed within the class) and
accessPrivateFunction() method is a public member function of the class ‘Student’ which can be
accessed from anywhere within the program. The accessPrivateFunction() method accesses the
private members of the class ‘Student’.
The following program illustrates the use of all the above three access modifiers (public, protected
and private) of a class in Python:
In the following program, x, _y and __z are public, protected and private data members of ‘Super’
class. The class has three argument constructor for initializing these data members. Also the class
has the following member functions:
274
Conceptualizing Python in Google COLAB
display_protected() → for displaying a public data member, _y
display_private() → for displaying a public data member, __z.
access_private() → for accessing private data member of the class outside the class.
The ‘Derived’ class has a three argument constructor which invokes the super class constructor for
initializing the data members of the class. The super class constructor can be invoked in one of the
following ways:
<superclass_name>.__init__(self,x,y,z)
Super.__init__(self,x,y,z)
‘self’ parameter should be the first parameter while using class name.
super().__init__(x,y,z)
When using super(), ‘self’ is not used as a first parameter to the method call.
275
Conceptualizing Python in Google COLAB
The above program can be re-written using super() function to access the super class functionality
as shown below:
276
Conceptualizing Python in Google COLAB
The ‘Derived’ class has direct access to the members x and _y.
277
Conceptualizing Python in Google COLAB
An attempt to access the private data member outside the class generates ‘AttributeError’ as
shown in the following program. The protected members are still accessible in Python.
278
Conceptualizing Python in Google COLAB
279
Conceptualizing Python in Google COLAB
280
Conceptualizing Python in Google COLAB
However, the __str__() method can be overridden in the class which will be invoked when an
object is passed to print() method for displaying the object in the required string format. In the
following example, the __str__() method is overridden in ‘Vector’ class to display the x and y
coordinates of the vector in parentheses.
281
Conceptualizing Python in Google COLAB
In the following example, the __str__() method is overridden in ‘Rational’ class to display the
numerator and denominator of the rational no. in required format.
In the following example, the __str__() method is overridden in ‘Complex’ class to display the
real and imaginary parts of rational no. in required format.
282
Conceptualizing Python in Google COLAB
Object Comparison
When == operator is used for comparing the two reference variables in Python, the addresses of
the two objects are compared and not the content. In the following example, ‘n1’ and ‘n2’ are
references of ‘Number’ class. Even if their content is same their comparison fails as shown in the
following figure:
For comparing the contents of two objects, __eq__() method must e overridden in the class. The
following program presents the re-written version of above program which overrides __eq__()
method for comparing the content of two ‘Number’ class objects. When __eq__() method is
overridden in the class, == operator is mapped to the method for object comparison.
283
Conceptualizing Python in Google COLAB
In the above program, the statement
n1.__eq__(n2)
Operator Overloading
Operator Overloading means giving extended meaning beyond their predefined operational
meaning. For example operator + is used to add two integers as well as join two strings and merge
two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. The same
built-in operator or function shows different behavior for objects of different classes, this is
referred to as Operator Overloading.
The following table depicts the operators that can be overloaded along with magic methods.
284
Conceptualizing Python in Google COLAB
285
Conceptualizing Python in Google COLAB
286
Conceptualizing Python in Google COLAB
287
Conceptualizing Python in Google COLAB
In the following program, binary + operator is overloaded in ‘Complex’ class to define addition
operation on two objects of ‘Complex’ class.
288
Conceptualizing Python in Google COLAB
Python program to overload equality and less than operators
The following program demonstrates the overloading of equality and ‘less than’ operator in class
‘A’.
Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to name
attributes with a double underscore prefix, and those attributes then are not be directly visible to
outsiders.
In the following example, the attribute ‘secretCount’ is prefixed with two underscores and hence
is not visible outside the class. An attempt to access it outside the class generates ‘AttributeError’
as shown in the following program:
289
Conceptualizing Python in Google COLAB
However, the variable ‘secretCount’ can be accessed outside the class using _JustCounter as
demonstrated in the following program:
290
Conceptualizing Python in Google COLAB
Polymorphism in Python
Polymorphic functions in an object oriented programming language enable same method call
responding differently based on the context and how the reference is initialized. The same method
call attains different forms.
The basic form of polymorphism is achieved through function overloading. In Python function
overloading can be simulated through default parameters. In the following example, the add()
method accepts three parameters. The first two parameters are the required parameters and the last
parameter is a default parameter. The add() function can thus be invoked with two and three
parameters as demonstrated in the following program:
291
Conceptualizing Python in Google COLAB
Polymorphism with Class Methods: Adhoc Polymorphism
Class methods can be employed for implementing polymorphism in Python. Depending on the
type of the object variable appropriate version of the method is invoked at runtime.
In the following example, each of the classes, ‘India’ and ‘USA’ have three member functions,
capital(), language() and type(). Both the classes are instantiated and the for loop iterates through
the tuple containing these instances. Depending on the type of object on which the method is
invoked, the appropriate version of the method is invoked as demonstrated in the following
program:
292
Conceptualizing Python in Google COLAB
Polymorphism with Inheritance: Classical Polymorphism
In Python, Polymorphism lets us define methods in the child class that have the same name as the
methods in the parent class. In inheritance, the child class inherits the methods from the parent
class. However, it is possible to modify a method in a child class that it has inherited from the
parent class. This is particularly useful in cases where the method inherited from the parent class
doesn’t quite fit the child class. In such cases, we re-implement the method in the child class. This
process of re-implementing a method in the child class is known as Method Overriding.
In the following program, Bird is a base class for ‘sparrow’ and ‘ostrich’ classes which override
the ‘flight’ method. When the object variable is initialized with instances of ‘sparrow’ and ‘ostrich’
classes the overridden methods are invoked as demonstrated in the following program:
293
Conceptualizing Python in Google COLAB
In the following program, func() is a function which accepts a single parameter, a valid instance
of a class implementing capital(), language() and type() methods. Depending on the type of object
passed to func() method, the capital(), language() and type() methods of the appropriate class are
invoked as demonstrated in the following program:
294
Conceptualizing Python in Google COLAB
On execution of the above program, the following output is generated:
Using super
Python super() function provides us the facility to refer to the parent class explicitly. It is basically
useful where we have to call superclass functions. It returns the proxy object that allows us to refer
parent class by ‘super’.
Example:
In the following example, class ‘A’ has a single data member ‘x’ and a display() method to display
the value of ‘x’. ‘B’ is a derived class of ‘A’ with the new data member ‘y’. Hence, the class ‘B’
has access to two data members:
The class ‘B’ has display() method to display the values of ‘x’ and ‘y’ which uses ‘super’ keyword
for invoking the display() method of parent class ‘A’ and then displays the value of ‘y’.
‘C’ is a derived class of ‘B’ with the new data member ‘z’. Hence, the class ‘C’ has access to three
data members:
The class ‘C’ has display() method to display the values of ‘x’, ‘y’ and ‘z’ which uses ‘super’
keyword for invoking the display() method of parent class ‘B’ for displaying the values of ‘x’ and
‘y’ and then displays the value of ‘z’.
295
Conceptualizing Python in Google COLAB
Hence each class is responsible for performing the responsibility assigned to it. The complete
source code of the program is shown below:
296
Conceptualizing Python in Google COLAB
297
Conceptualizing Python in Google COLAB
Case Study:
Comparison of Rational No.s –
For comparing the two rational no.s the following cases need to be considered. The rational no.s
may have different signs in their numerator and denominator. So both the rational no.s to be
compared need to be standardized. The denominators of two rational no.s to be compared may not
be same, so they need to be normalized. The different cases to be dealt with are depicted below:
Case 1: If signs are not equal, then +ve is greater than –ve
Case 2: Signs are equal and both +ve, denominators are equal.
Case 3: Signs are equal and both +ve, denominators are not equal.
Case 4: Signs are equal and both –ve, denominators are equal.
Case 5: Signs are equal and both –ve, denominators are not equal.
Case 6: If signs are not equal and denominators are equal
Case 7: If signs are not equal and denominators are not equal
Test Case 1:
Test Case 2:
Test Case 3:
Test Case 4:
Test Case 5:
Test Case 6:
Test Case 7:
298
Conceptualizing Python in Google COLAB
2/3 and -4/5
299
Conceptualizing Python in Google COLAB
and the second rational no is
𝑛𝑟2 ∗ 𝑑𝑟1
𝑑𝑟2 ∗ 𝑑𝑟1
Now, the denominators of both the rational no.s are equal and they can now be compared directly
by comparing their respective numerators.
The complete source code for the implementation of the above case study is shown below along
with the execution of individual cases.
300
Conceptualizing Python in Google COLAB
Test Case 1:
Test Case 2:
301
Conceptualizing Python in Google COLAB
Test Case 3:
Test Case 4:
Test Case 5:
Test Case 6:
Test Case 7:
302
Conceptualizing Python in Google COLAB
References:
1. https://docs.python.org/3/tutorial/
2. https://www.tutorialspoint.com/python/index.htm
3. https://www.w3schools.com/python/
4. https://www.javatpoint.com/python-tutorial
5. https://www.programiz.com/python-programming
6. https://www.learnpython.org/
7. https://www.geeksforgeeks.org/python-programming-language/learn-python-tutorial/
8. https://realpython.com/tutorials/python/
9. https://colab.research.google.com/?utm_source=scs-index
303
Conceptualizing Python in Google COLAB
Appendix A
Case Study on Object Oriented Programming
Level – Intermediate
Implementation of Custom Signed Number Class
Problem Definition:
Define a class with the name ‘Number’ with the following data members –
• value
• sign
Overload constructors for creating both signed and unsigned objects of ‘Number’ class, as shown
below –
• 0 (No Sign)
• +10
• -20
304
Conceptualizing Python in Google COLAB
Addition operation on objects of ‘Number’ class
Case 1 –
If ‘sign’ attribute of both ‘Number’ objects is +ve, then result is addition of two values and sign is
+ve.
Case 2 –
If ‘sign’ attribute of both ‘Number’ objects is -ve, then result is addition of two values and sign is
-ve.
Case 3 –
If ‘sign’ attribute of ‘Number’ objects are different, then result is absolute difference of two values
and sign equal to the ‘sign’ attribute of ‘Number’ object whose ‘value’ attribute is greater. If the
value is zero, then sign is blank.
Case 2 –
If ‘sign’ attribute of ‘Number’ object is -ve, then result is
subtraction of one from value attribute and sign is –ve if ‘value’ attribute is non-zero else sign is
blank .
Case 3 –
If value attribute of a ‘Number’ object is zero, then result is a Number object with value attribute
equal to 1 and sign attribute equal to +ve.
305
Conceptualizing Python in Google COLAB
Test Cases –
+1 +2
-1 0
-2 -1
0 +1
Case 2 –
If ‘sign’ attribute of ‘Number’ object is -ve, then result is
subtraction of one from value attribute and sign is –ve if ‘value’ attribute is non-zero else sign is
blank .
Maximum operation on objects of ‘Number’ class
Test Cases –
+1 +2
-1 0
+1 0
-2 -1
+2 -1
-2 +1
0 +1
0 -1
Note – Return maximum ‘Number’ class object
Solution:
Solution – Number Class
306
Conceptualizing Python in Google COLAB
class Number:
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def __str__(self):
return self.sign+str(self.value);
obj=Number()
print(obj)
obj1=Number(10,"+")
print(obj1)
obj2=Number(20,"-")
print(obj2)
307
Conceptualizing Python in Google COLAB
Implementation of Addition Operation
class Number:
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def __str__(self):
return self.sign+str(self.value);
def __add__(self,other):
return Number(self.value+other.value,"+")
return Number(self.value+other.value,"-")
else:
value=abs(self.value-other.value)
if (self.value>other.value):
sign=self.sign
else:
sign=other.sign
return Number(value,sign)
obj1=Number(10,"+")
obj2=Number(20,"+")
obj3=obj1+obj2
print(obj3)
308
Conceptualizing Python in Google COLAB
obj4=Number(10,"-")
obj5=Number(20,"-")
obj6=obj4+obj5
print(obj6)
obj7=Number(10,"-")
obj8=Number(20,"+")
obj9=obj7+obj8
print(obj9)
obj10=Number(10,"+")
obj11=Number(20,"-")
obj12=obj10+obj11
print(obj12)
309
Conceptualizing Python in Google COLAB
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def __str__(self):
return self.sign+str(self.value)
310
Conceptualizing Python in Google COLAB
def increment(self):
if(self.sign=="+"):
self.value=self.value+1
self.sign=""
self.value=0
elif (self.sign=="-"):
self.sign="-"
self.value=self.value-1
elif (self.value==0):
self.sign="+"
self.value=1
obj=Number(10,"+")
obj.increment()
print(obj)
obj1=Number(1,"-")
obj1.increment()
print(obj1)
obj2=Number(2,"-")
obj2.increment()
print(obj2)
obj3=Number(0,"")
obj3.increment()
print(obj3)
311
Conceptualizing Python in Google COLAB
312
Conceptualizing Python in Google COLAB
Implementation of Max Operation
class Number:
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def __str__(self):
return self.sign+str(self.value)
def max(self,other):
return self
value=self.value
else:
value=other.value
sign="+"
return Number(value,sign)
elif(self.value==0):
return other
return self
elif(other.value==0):
313
Conceptualizing Python in Google COLAB
if(self.value>0 and self.sign=="+"):
return self
return other
return self
else:
return other
if(self.sign == "+"):
return self
else:
return other
obj1=Number(10,"+")
obj2=Number(20,"+")
obj3=obj1.max(obj2)
print(obj3)
obj4=Number(0,"")
obj5=Number(10,"+")
obj6=obj4.max(obj5)
print(obj6)
obj7=Number(0,"")
obj8=Number(10,"-")
314
Conceptualizing Python in Google COLAB
obj9=obj7.max(obj8)
print(obj9)
obj10=Number(10,"+")
obj11=Number(0,"")
obj12=obj10.max(obj11)
print(obj12)
obj13=Number(10,"-")
obj14=Number(0,"")
obj15=obj13.max(obj14)
print(obj15)
obj16=Number(0,"")
obj17=Number(0,"")
obj18=obj16.max(obj17)
print(obj18)
obj19=Number(10,"-")
obj20=Number(20,"-")
obj21=obj19.max(obj20)
print(obj21)
obj22=Number(10,"+")
obj23=Number(20,"-")
obj24=obj22.max(obj23)
print(obj24)
315
Conceptualizing Python in Google COLAB
obj25=Number(10,"-")
obj26=Number(20,"+")
obj27=obj25.max(obj26)
print(obj27)
316
Conceptualizing Python in Google COLAB
317
Conceptualizing Python in Google COLAB
Inheritance
Delegation?
Delegation
Number nr
318
Conceptualizing Python in Google COLAB
Number dr
2/3 4/5
r1.nr/ r1.dr
r2.nr/r2.dr
class Number:
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def display(self):
print(self.sign+str(self.value),end="")
class Rational:
def __init__(self,nr,nr_sign,dr,dr_sign):
self.nr=Number(nr,nr_sign)
self.dr=Number(dr,dr_sign)
def display(self):
self.nr.display()
print("/",end="")
self.dr.display()
r1=Rational(10,"+",20,"-")
r1.display()
319
Conceptualizing Python in Google COLAB
class Number:
def __init__(self,value=0,sign=""):
self.value=value
self.sign=sign
def __str__(self):
return self.sign+str(self.value)
class Rational:
def __init__(self,nr,nr_sign,dr,dr_sign):
self.nr=Number(nr,nr_sign)
self.dr=Number(dr,dr_sign)
def __str__(self):
320
Conceptualizing Python in Google COLAB
print(self.nr,end="")
print("/",end="")
print(self.dr)
return ""
r1=Rational(10,"+",20,"-")
print(r1)
321
ACADEMIC
ISBN 978-93-93557-43-8
9 789393 557438