0% found this document useful (0 votes)
149 views

Conceptualizing Python in Google COLAB

Python para Google Colab en inglés

Uploaded by

jimena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views

Conceptualizing Python in Google COLAB

Python para Google Colab en inglés

Uploaded by

jimena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 330

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/357929808

Conceptualizing Python in Google COLAB

Book · January 2022

CITATIONS READS
0 3,558

3 authors:

Poornima Naik Girish Naik


CHHATRAPATI SHAHU INSTITUTE OF BUSINESS EDUCATION AND RESEARCH KITs College of Engineering
141 PUBLICATIONS   139 CITATIONS    91 PUBLICATIONS   187 CITATIONS   

SEE PROFILE SEE PROFILE

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:

On-line Generic Elective Selection System for CSIBER View project

Soft Computing Model for Secure Auto Program Evaluator View project

All content following this page was uploaded by Poornima Naik on 19 January 2022.

The user has requested enhancement of the downloaded file.


Conceptualizing Python in Google

COLAB

By

Dr. Poornima G. Naik


Dr. Girish R. Naik
Mr. M.B.Patil
© Copyright 2021 Authors
All rights are reserved. No part of this book may be reproduced or transmitted in any form by any means;
electronic or mechanical including photocopy, recording, or any information storage or retrieval system;
without the prior written consent of its author.
The opinions /contents expressed in this book are solely of the authors and do not represent the opinions /
standings / thoughts of Shashwat Publication. No responsibility or liability is assumed by the publisher for
any injury, damage or financial loss sustained to a person or property by the use of any information in this
book, personal or otherwise, directly or indirectly. While every effort has been made to ensure reliability
and accuracy of the information within, all liability, negligence or otherwise, by any use , misuse or abuse
of the operation of any method, strategy, instruction or idea contained in the material herein is the sole
responsibility of the reader. Any copyright not held by the publisher are owned by their respective authors.
All information in this book is generalized and presented only for the informational purpose “as it is”
without warranty or guarantee of any kind.
All trademarks and brands referred to in this book are only for illustrative purpose are the property of their
respective owners and not affiliated with this publication in any way. The trademarks being used without
permission don’t authorize their association or sponsorship with this book.

ISBN: 978-93-93557-43-8
Price: 250.00
Publishing Year 2021

Published and Printed by:


Shashwat Publication
Office Address: Ram das Nagar,
Bilaspur, Chhattisgarh – 495001
Phones: +91 9993608164 +91 9993603865
Email: [email protected]
Website: www.shashwatpublication.com
Printed in India

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.

Dr. Poornima G. Naik


Dr. Girish R. Naik
Mr. M.B.Patil

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.

Dr. Poornima G. Naik


Dr. Girish R. Naik
Mr. M.B.Patil

iii
Contents

Chapter Page No.

1. Introduction to Google COLAB 1


2. Lab Assignments on Python Language Fundamentals 33
3. Lab Assignment on Python Operators and Control Statements 102
4. Lab Assignment on Basic Programs 117
5. Lab Assignment on Python Functions 130
6. Lab Assignment on Advanced Concepts in Python - I 142
(Covers Iterators, Closures, Decorators and Generators)
7. Lab Assignment on Advanced Concepts in Python - II 157
8. Lab Assignment on Exception Handling in Python 170
9. Lab Assignment on File Handling in Python 204
10. Lab Assignment on Regular Expressions in Python 228
11. Lab Assignment on Language Basics and Error Handling in Python 251
12. Lab Assignment on Object Oriented Programming in Python 257
References 303
Appendix A - Case Study on Object Oriented Programming 304

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

What COLAB Offers You?


As a programmer, you can perform the following using Google Colab.
• Write and execute code in Python
• Document your code that supports mathematical equations
• Create/Upload/Share notebooks
• Import/Save notebooks from/to Google Drive
• Import/Publish notebooks from GitHub
• Import external datasets e.g. from Kaggle
• Integrate PyTorch, TensorFlow, Keras, OpenCV
• Free Cloud service with free GPU

Getting Started with COLAB


To start working with Colab you first need to log in to your Google account, then go to this link
https://colab.research.google.com.
Since Colab implicitly uses Google Drive for storing your notebooks, ensure that you are logged
in to your Google Drive account before proceeding further.

2
Conceptualizing Python in Google COLAB

What is Jupyter Notebook


The Jupyter Notebook is an open-source web application that allows you to create and share
documents that contain live code, equations, visualizations and narrative text. Uses include: data
cleaning and transformation, numerical simulation, statistical modeling, data visualization,
machine learning, and much more.

Opening Jupyter Notebook:


On opening the website you will see a pop-up containing following tabs –

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.

Adding New Cells


To add more code to your notebook, select the following menu options −

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 –

Changing Runtime Environment:


Click the ‘Runtime’ dropdown menu. Select ‘Change runtime type’. Select python2 or 3
from ‘Runtime type’ dropdown menu.

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()

• If gpu is connected it will output following –

• Otherwise, it will output following

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.

Installing Python packages –


Use can use ‘pip’ to install any package. For example:
For installing a package ‘pandas’ enter the following command:
pip install pandas

9
Conceptualizing Python in Google COLAB
The following output is displayed:

Uploading a File in COLAB


For uploading a file, enter the following code:
from google.colab import files
uploaded = files.upload()
‘Choose Files’ button appears as shown below:

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

mount /dev/cdrom /media/cdrom


• After that command is run, a file whose location on the CD-ROM is /dir/file is now
accessible on your system as /media/cdrom/dir/file. When you've finished using the CD,
you run the command

umount /dev/cdrom or umount /media/cdrom


(both will work; typical desktop environments will do this when you click on the ‘eject’ or ‘safely
remove’ button).
• Mounting applies to anything that is made accessible as files, not just actual storage
devices. For example, all Linux systems have a special file system mounted under /proc.
That file system (called proc) does not have underlying storage: the files in it give
information about running processes and various other system information; the information
is provided directly by the kernel from its in-memory data structures.

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']))

Upload File By Mounting Google Drive:


To mount your drive inside ‘mntDrive’ folder execute following –
from google.colab import drive
drive.mount('/mntDrive')

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

Saving to Google Drive


Colab allows you to save your work to your Google Drive. To save your notebook, select the
following menu options −

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

Documenting Your Code


• As the code cell supports full Python syntax, you may use Python comments in the code
window to describe your code. However, many a time you need more than a simple text
based comments to illustrate the ML algorithms. ML heavily uses mathematics and to
explain those terms and equations to your readers you need an editor that supports LaTex
- a language for mathematical representations. Colab provides Text Cells for this
purpose.
• A text cell containing few mathematical equations typically used in ML is shown in the
screenshot below −

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$

The rendered output is shown here for your quick reference.

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.

Google Colab - Sharing Notebook


• To share the notebook that you have created with other co-developers, you may share the
copy that you have made in your Google Drive.
• To publish the notebook to general audience, you may share it from your GitHub
repository.
There is one more way to share your work and that is by clicking on the SHARE link at the top
right hand corner of your Colab notebook. This will open the share box as shown here

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.

Getting Remote Data


Let us look into another example that loads the dataset from a remote server.
Type in the following command in your Code cell −
!wget http://mlr.cs.umass.edu/ml/machine-learning-databases/adult/adult.data -P
"/content/drive/My Drive/app"

Cloning Git Repository


You can clone the entire GitHub repository into Colab using the git command. For example, to
clone the keras tutorial, type the following command in the Code cell −
!git clone https://github.com/wxs/keras-mnist-tutorial.git

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.

Google Colab - Graphical Outputs


Colab also supports rich outputs such as charts. Type in the following code in the Code cell.

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()

Code Editing Help


The present day developers rely heavily on context-sensitive help to the language and library
syntaxes. That is why the IDEs are widely used. The Colab notebook editor provides this facility.

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.

Type the following code in your code window −


import numpy as np
in one cell, run it and enter the following code in another cell.
np.add(
Now, hit TAB and you will see the documentation on cos in the popup window as shown in the
screenshot here. Note that you need to type in open parenthesis before hitting TAB.

21
Conceptualizing Python in Google COLAB

Google Colab – Magics


Magics is a set of system commands that provide a mini extensive command language.
Magics are of two types −
• Line magics
• Cell magics
The line magics as the name indicates that it consists of a single line of command, while the cell
magic covers the entire body of the code cell.
In case of line magics, the command is prepended with a single % character and in the case of
cell magics, it is prepended with two % characters (%%).
Let us look into some examples of both to illustrate these.

Line Magics
Type the following code in your code cell −

%ldir

The above command displays the content of current working directory.

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 −

To get a complete list of supported magics, execute the following command −


%lsmagic

23
Conceptualizing Python in Google COLAB
Adding Form
For accepting input from user.

Click on vertically dotted ‘Options’ menu in the right-top corner.

The following menu is displayed:

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:

‘Edit form attributes’ dialog appears as shown below:

24
Conceptualizing Python in Google COLAB

Adding Form Fields


To add a form field, click the ‘Options’ menu in the Code cell, click on the ‘Form’ to reveal the
submenus. The screen will look as shown below −

Select ‘Add a form field’ menu option. A dialog pops up as seen here −

Adding Form Fields −

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())

The output is displayed below the form control.

Edit the form as shown below:

Change the variable type to ‘string’ and variable name to ‘name’.

27
Conceptualizing Python in Google COLAB
Edit the form code as shown:

print("Hello",name)

Following output is displayed:

Using Dropdown List


• Click on ‘Form Field Type’ dropdown and select ‘dropdown’ from the list displayed.

• Enter the variable type as ‘string’ and variable name as ‘course’

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

Adding Item to the Dropdown List


• For adding new item to the list, click in ‘+’ icon next to item and enter the name of the item
in the textbox that appears.

28
Conceptualizing Python in Google COLAB

Edit the form code as shown below:

print("You Selected - ",course)

Following output is displayed:

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

start_date = "2021-05-29" #@param {type:"date"}

print(start_date)

The Form screen looks like the following.

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:

Checking Variable Type


Python is dynamically typed language. The type of the variable is decided at runtime based on the
type of the value assigned to it. In the following program, the variable ‘x’ is initialized with the
value 10, and hence ‘x’ is of type ‘int’. In the subsequent statement, the value of ‘x’ is changed to
‘CSIBER’ which changes the type of ‘x’ from ‘int’ to ‘str’ 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.

Determining the size of Variable in Python


In Python ‘int’ is a full-fledged object which involves an extra overhead which stores reference
count, object type among others. In the following figure, size of int class and instance of int class
is displayed.

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.

Variable Initialization Issues


Python does not automatically initialize the variables to the default values. Attempting to use the
variable without initializing will generate ‘NameError’ as demonstrated in the following program:

Data Type of Variables – type() Function


Python support type() function for determining runtime instance of a variable. type() function
accepts a single parameter the variable whose type is to be determined as demonstrated in the
following program:

35
Conceptualizing Python in Google COLAB

Checking the Type of the Variable – isinstance()


Python supports a function isinstance() for checking the instance of the variable at runtime as
demonstrated in the following figure. The isinstance() function accepts two parameters:
• first parameter is the name of the variable and
• second parameter is the class

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

Implicit Type Casting


Python automatically converts smaller data type to larger data type i.e. the result of adding ‘int’
and ‘float’ values is ‘float’ as demonstrated in the following program:

36
Conceptualizing Python in Google COLAB

Multiple Assignments in a Single Statement


Python enables initialization of multiple values in a single statement employing ‘=’ operator. The
‘=’ operator is right associative i.e. it evaluates the expression from right to left. In the following
program, the constant ‘1’ is assigned to a variable ‘c’ which is then assigned to ‘a’ and ‘b’
subsequently.

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:

del <var_1>[, <var,2>, . . . . <var_N>]

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:

Using Escape Characters in Strings


The escape character is used for performing a specific action on a string. For example, ‘\n’
characters are used for appending new line character at the end of a string. ‘\t’ is used for using tab
space between the words as demonstrated in the following programs:

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 Repetition Operator


* operator is used for repeating the string the specified no. of times. In the following example, the
string ‘CSIBER’ is repeated 5 times.

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.

Bounds Checking for Strings


Python performs strict bounds checking on arrays and strings. Attempting to access an element
beyond limits generates an ‘IndexError’ as shown in the following program:

40
Conceptualizing Python in Google COLAB

A Special Data Type – None


‘None’ is used for defining a null value. In Python a variable cannot be used without initializing
it. Using an uninitialized variable generates ‘NameError’ as shown in the following figure:

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:

list1[ -m-1 : -1]

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]

Retrieving the elements Using Positive and Negative Indexing


The positive and negative index positions for a list of length 10 is shown in the following figure:

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]

where s is the size of the list.

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 1: A list and a tuple cannot be concatenated.

Attempting to concatenate a tuple with the list generates ‘TypeError’.

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

However, the following program compiles successfully.

Checking the Existence of an Element in a List


The membership operator ‘in’ can b used for testing the existence of an element in a list as
demonstrated in the following program:

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

Determining the Size of the List – len() Function


len() function can be used for determining the size of the list which returns the no. of elements
available in the list.

Appending an Element to a List –append() Method


append() method can be used for appending a single element to the list as shown in the following
program:

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

Object Cloning – copy() Method


Python supports copy() method for cloning the object by duplicating the contents. copy() method
creates an exact copy of the object by duplicating the contents and returns a reference to the newly
created object. This enables two copies to be manipulated independently of each other. In the
following program, the variables ‘numbers’ and ‘numbers1’ refer to two distinct objects. Hence

53
Conceptualizing Python in Google COLAB
modifying the object referenced by ‘numbers1’ does not modify the object referenced by
‘numbers’.

Testing Object Equivalence Using ‘is’ Operator


‘is' operator accepts two operands and returns ‘True’ if the two references point to the same object,
otherwise returns ‘False’.

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.

Sorting in Ascending and Descending Order – sorted() Method


Python supports a sorted() method for bi-directional sorting of elements. It can be used for sorting
the elements either in ascending or descending order. Unlike sort() method of List class sorted()
method accepts a list reference as a parameter, creates a new sorted list and returns the same.

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.

Deleting a Single Element from the List Using del Method


del method is used for deleting a single or a range of elements from a list. An attempt to access the
deleted element generates ‘NameError’.

Deleting a Range of Elements from the List Using del Method


The syntax for deleting the elements in the index position n-m using positive indexing is

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]

where s is the size of the list.

In the following example, the above program is re-written using negative indexing.

For the following list

[1, 2, 3, 4, 5]

s=5 n=2 and m=4

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

Deleting All Elements from the list Along with Reference


del method can be used for deleting the entire list along with the reference. An attempt to access
the deleted list generates ‘NameError’ as demonstrated in the following program:

Deleting the Element of a List Using pop() Method


pop() method can be used for deleting an element at the highest index position.

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.

Difference Between del list1[:] and del list1


list1[:] deletes all elements from the list1 while keeping he reference intact while del list1 deletes
the list itself, all elements of list1 along with the reference as demonstrated in the following
program:

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.

The above program is re-written using lambda function as shown below:

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.

Finding the index of an Element Using index() Method


Python supports index() function which returns the index of the element passed to it. In the
following program, the index of the elements ‘PHP’ and ‘Python’ is retrieved using index()
method.

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:

list1 = [[[1, 2], [3, 4], 5], [6, 7]]

The nesting of list1 to different levels is depicted in the following figure:

[[[1, 2], [3, 4], 5], [6, 7]]

list1[0] = [[1, 2], [3, 4], 5] list1[1] = [6, 7]

list1[0][0] = [1, 2] list1[0][1] = [3, 4] list1[0][2] = 5 list[1][0]=6 list[1][1]=7

list1[0][0][0]=1 list1[0][0][1]=2 list1[0][1][0]=3 list1[0] [1][1]=4

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

var1, var2, var3, . . . .,varN = value1, value2, value3, . . . .,valueN.

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

Difference Between id, value and hash


Object id
If the same object is referenced by two distinct references, then their ‘id’ is same. The ‘is’ operator
compares the ‘id’ of the two operands. Hence,

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

Operation Not Applicable to Tuple


Since tuple is immutable, the following operations cannot be performed on a tuple:
• append()
• insert()
• clear()
• pop()
• remove()
• copy()
• sort()
• reverse()

Tuple Nested Inside List


A tuple can be nested inside list. Tuple being immutable cannot be changed, however, the list can
be manipulated. An attempt to change the tuple element of a list element generates ‘TypeError’ as
shown in the following figure:

76
Conceptualizing Python in Google COLAB

However, the list element can be directly manipulated as shown below:

List Nested Inside Tuple


A list can be nested inside a tuple. Tuple being immutable cannot be changed, however, the list
can be manipulated. An attempt to change the tuple element generates ‘TypeError’ as shown in
the following figure:

However, the list element can be directly manipulated as shown below:

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.

Iterating Over the Elements of Dictionary


There are three approaches for iterating over the elements of a dictionary.

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:

Deleting Elements of Dictionary


Method 1: Using pop() method
pop() method of a dict class accepts the key of the dictionary element to be deleted as demonstrated
in the following program:

Method 2: Using del Method


del method can also be used for deleting the element of a dictionary as shown below:

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:

The order of elements in a set is unpredictable.

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:

Concatenating Two Sets


The concatenation operation on two sets is not defined. An attempt to add two sets generates
‘TypeError’ as shown in the following program:
Since

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

as demonstrated in the following program:

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:

Set is Not Reversible


Since the set is immutable, the elements of a set cannot be reversed. Doing so generates
‘TypeError’ as demonstrated in the following program:

87
Conceptualizing Python in Google COLAB

Checking Set Equality Using == Operator


The equality operator == can be used for comparing the content of two sets. == returns ‘True’ if
the two sets have same content, otherwise ‘False’.

Checking Set Equivalence Using ‘is’ Operator


‘is’ operator returns ‘True’ if the two references reference the same set object, otherwise returns
‘False’.

88
Conceptualizing Python in Google COLAB

Inserting a Single Element in a List – add() Method


If the list is sorted, then the add() method inserts the element at the appropriate position as
demonstrated in the following figures:

If the set is unsorted, then add() method inserts the element at random position as shown below:

89
Conceptualizing Python in Google COLAB

Inserting a Multiple Elements in a List – update() Method


For inserting multiple elements in the set update() method can be employed which accepts an
iterable (list, tuple or set) as its single argument as demonstrated in the following programs:

Using list to insert elements in a set


The update() method accepts an iterable, iterates through all the elements are adds each element
to the set. In the following example, the list containing five elements is passed to update() element
which inserts all the elements of a list to a set.

Using tuple to insert elements in a set


In the following example, the tuple containing five elements is passed to update() element which
inserts all the elements of a tuple to a set.

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.

Deleting an Element from a Set – remove() Method

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:

Deleting an Element from a Set – pop() Method


pop() method does not accept any arguments and deletes the first element from the list and returns

the deleted element as shown in the following program:

remove() and discard() methods do not return any value.

92
Conceptualizing Python in Google COLAB

Deleting all the Elements from a Set – clear() Method

clear() method does not return any value.

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

Set Aggregate Functions –max(), min(), sum()


The aggregate functions max(), min(), sum() can be used for finding the maximum, minimum and
sum of all elements of a set as demonstrated in the following program:

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.

Union of Two Sets


Union of two sets is a set containing elements from both the sets eliminating duplicates, if any as
shown in the following program. Set supports union() method for the purpose. The same result can
be achieved using ‘|’ operator as well.

Intersection of Two Sets


Intersection of two sets is a set containing elements common to both the sets as shown in the
following program. Set supports intersection() method for the purpose. The same result can be
achieved using ‘&’ operator as well.

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.

Set Symmetric Difference


Symmetric difference of two sets is a set containing elements from both the sets obtained by
computing their respective differences as shown in the following program. Set supports
symmetric_difference() method for the purpose. The same result can be achieved using the
following operation:

s1 ~ s2 = s1 – s2) U (s2 – s1)

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.

Checking Set Relationship – issubset(), issuperset()


Set A is considered to be a subset of set B, if it at least contains all elements of set B. B is considered
to be a superset of A. set class supports two boolean methods issubset() and issuperset() to check
whether the invoking set is a subset/superset of a set passed as an argument.

Set Difference Revisited- difference() Method


Set difference contains all the elements from first set which re not present in second set, but it does
not update the first set as shown below:

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.

Converting a Set into Frozen Set


A set can be converted into a frozen set using frozenset() method as demonstrated in the following
program. The program confirms that set is not hashable while frozen set is. After converting a set
into a frozen set, the methods which modify the elements of a set such as add(), clear(), update()
etc. case to be applicable to a frozen set.

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

Python Arithmetic Operators


The different arithmetic operators supported by Python language are depicted in the following
table:
Assume variable a holds 10 and variable b holds 20, then –

102
Conceptualizing Python in Google COLAB

Floor Division Operator


Python supports floor division operator which performs an integer division as shown in the
following program:

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 –

Python Comparison Operators


The comparison or relational operators compare the values of two operands. The different
relational 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

Python Bitwise Operators


The different bitwise operators supported by Python language are depicted in the following table:

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The different bitwise operations on operands 60 and 13 are demonstrated in the following program:

106
Conceptualizing Python in Google COLAB

Left Shift and Right Shift Operators

Python Logical Operators


The different logical operators supported by Python language are depicted in the following table:

Assume variable a holds 10 and variable b holds 20 then

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.

In Evaluation of ‘or’ Condition


The following program demonstrates short-circuit evaluation of ‘or’ condition in Python. In the
following program, in the ‘if’ condition, the first condition evaluates to false, hence the second
condition is evaluated which invokes display() method which prints ‘Inside display’ as shown in
the following program:

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

Python Membership Operators


Python’s membership operators are employed to test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below –

The following programs demonstrate the use of membership operators in Python:

110
Conceptualizing Python in Google COLAB

Python Identity Operator (is)


Identity operators compare the memory locations of two objects. There are two Identity operators
explained below –

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.

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

112
Conceptualizing Python in Google COLAB

Accepting Input from User


input() function is used for accepting input from the keyboard which returns a string value
corresponding to the input entered by the user as demonstrated in the following figure:

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

String formatting (Format String %)


The ‘%’ operator is employed for formatting a set of variables enclosed in a ‘tuple’ together with
a format string, which contains normal text together with ‘argument specifiers’ or ‘argument place
holders’ corresponding to special symbols such as ‘%s’ and ‘%d’ as demonstrated in the following
programs:

114
Conceptualizing Python in Google COLAB
The different format codes supported by Python are enumerated in the following table:

‘d’ for integers


‘f’ for floating-point numbers
‘b’ for binary numbers
‘o’ for octal numbers
‘x’ for octal hexadecimal numbers
‘s’ for string
‘e’ for floating-point in an exponent format

Formatting Output Using format()


The format() method was introduced in Python3 and contains the place holders enclosed in a pair
of curly braces. There is one-to-one correspondence between place holders and parameters passed
to format() method as demonstrated in the following program:

String Templates – Using F-Strings


F-strings provide a concise and convenient way to embed python expressions inside string literals
for formatting. It is also referred to as ‘Literal String Interpolation’. To create an F-String prefix
the string with character ‘F’. The variables are part of the string and are enclosed in a pair of curly
braces as demonstrated in the following programs:

115
Conceptualizing Python in Google COLAB

Generating Output in the Same Line


By default print() function generates output in a separate line as shown in the following program:

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

Program 2: To Check Whether the Given no. is Even or Odd

119
Conceptualizing Python in Google COLAB
Program 3: To Find Largest Among Two No.s

To Find Largest of Three No.s

120
Conceptualizing Python in Google COLAB

121
Conceptualizing Python in Google COLAB
Using Nested if

122
Conceptualizing Python in Google COLAB

Program 4: To Check Whether the Given No. is Prime or Not.

123
Conceptualizing Python in Google COLAB

Program 5: To Compute the Factorial of a Given No.

124
Conceptualizing Python in Google COLAB

Program 6: Python Program to display Multiplication Table

125
Conceptualizing Python in Google COLAB
Program 7: Python Program to Print Fibonacci Sequence

Program 8: Python Program to Check Whether the Given No. is


Armstrong No. or Not

126
Conceptualizing Python in Google COLAB

Program 9: Python Program to Reverse the Given No.

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.

The syntax for defining a function in Python is shown below:

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.

Call By Value Vs. Call By Reference


Since everything in python is an object, the parameters passed to a function are object references
which can be manipulated within the function body as demonstrated in the following program. In
the following program, the list ‘l’ is passed to change() method which appends another list to the
list passed as the argument.

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

Function with Required Arguments


Required arguments must be passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition. In the following
program, the add() function takes two required arguments, num1 and num2. All the required
arguments must be passed to the function in correct order as shown in the following program:

132
Conceptualizing Python in Google COLAB

Function with Keyword Arguments or Named Arguments


In contrast to the required arguments, the keyword or named arguments need not maintain their
position or order in the function call which enables to skip certain arguments containing default
values in the function invocation. When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name. The above program is re-written below using
named arguments. In the function definition, the parameter ‘num1’ occurs before the parameter
‘num2’. On the other hand, in the function invocation the parameter ‘num2’ occurs before the
parameter ‘num1’ as shown in the following program:

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.

Function with Default Arguments


During the function definition certain default values can be assigned to the function parameters
which can be employed if the corresponding parameter is not specified in the function invocation.
In the following example, the above program is re-written where the add() function assigns the
default values 10 and 20 to its parameters ‘num1’ and ‘num2’, respectively. If the add() function
is invoked without one or both the parameters, then the default values will be utilized as
demonstrated in the following program:

134
Conceptualizing Python in Google COLAB

Function with Variable No. of Arguments


Python supports variable no. of arguments which can be utilized if the no. of parameters to be
passed to the function are not known at design time. An asterisk (*) is placed before the variable
name that holds the values of all non keyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. In the following example, terms is a
variable no. of argument. The add() function must be invoked with minimum two required
arguments.

135
Conceptualizing Python in Google COLAB

Anonymous or Lambda Functions


In Python, an anonymous function is a function that is defined without a name. While normal
functions are defined using the ‘def’ keyword in Python, anonymous functions are defined using
the lambda keyword. A lambda function can take any number of arguments, but can only have one
expression. The syntax for defining a lambda function is shown below:

Syntax:
lambda <argument_list>:expression

Rules in Defining Lambda Functions :


The following rules are observed in designing lambda functions:
• ‘lambda’ keyword is used in place of ‘def’ keyword for defining lambda functions.
• ‘lambda’ functions are anonymous which means the functions are defined without name.
• Lambda forms can take any number of arguments but return just one value in the form of
an expression. They cannot contain commands or multiple expressions.

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.

Write a lambda function to multiply two numbers.

137
Conceptualizing Python in Google COLAB
Write a lambda function to print a string

Lambda with Default Arguments


A lambda function can take default arguments. In the following example, a lambda function is
defined with three parameters x, y and z which are assigned default values 10, 20 and 30,
respectively.

Applications of Lambda Functions


lambda function can be used anywhere where a nameless function is required for a short period of
time. In Python, we generally use it as an argument to a higher-order function (a function that takes
in other functions as arguments). Lambda functions are used along with built-in functions like
filter(), map() etc.

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.

Map each element of a list o its square using lambda function

139
Conceptualizing Python in Google COLAB

Higher Order Functions


In Python, a function can return a function and a function can take functions as augments such
functions are referred to as ‘Higher Order Functions’. In the following example, myfun() is a
higher order function which takes a single parameter and returns a lambda function taking one
parameter. Thus, myfun() can be invoked with different values for creating different functions for
doubling, tripling no.s etc. as demonstrated in the following program:

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

Higher Order Function with Variable No. of Arguments


The following program demonstrates a higher order function, arithmetic() which accepts two
parameters, the first parameter is a function which accepts variable no. of argument as its only
parameter and the second parameter is a variable no. of arguments to a function. The arithmetic
function is invoked by passing add() function as its first parameter and variable no. of arguments
as shown below:

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.

__next__() Method of Iterator

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

Iterating through the list Using for Loop


The most elegant way to iterate through the iterator is using for loop which successively invokes
__next__() method on the iterator to traverse through the elements and processes ‘StopIteration’
exception when all the elements of the iterator are exhausted. The following program demonstrates
iterating through the list using for loop.

Implementation of for loop - Handling StopIteration Exception


The following program demonstrates the actual implementation of the for loop for iterating
through the list. The infinite while loop is employed for iterating through the elements which
encapsulates try..except block for exception handling. ‘break’ statement is used in ‘except’ block

143
Conceptualizing Python in Google COLAB
to break from the loop when ‘StopIteration’ exception is thrown and no more elements exist in
the iterator.

Nested Functions in Python


In Python a function can be nested inside another function to create a nested function structure as
shown below. As shown in the program, nested functions can access variables of the enclosing
scope which are non-local members of the function. In the following program, greet() is a function
which is nested inside greetings() function and exists within the scope of greetings() function. The
greet() function has access to the parameter ‘nm’ of enclosing function as shown:

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

Criteria for Closures


The criteria that must be met to create closure in Python are enumerated below:

• We must have a nested function (function inside a function).


• The nested function must refer to a value defined in the enclosing function.
• The enclosing function must return the nested function.

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

Example of Closure Function:


In the following example, make_multiplier_of() is a function accepting argument ‘n’ which creates
a multipler() function with argument ‘m’ and multiplies the parameter passed to it with ‘n’.

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.

Higher Order Functions


A function in Python can take other functions as arguments and return a function. Such functions
are referred to as higher order functions. In the following program, change() function accepts two
parameters, the first parameter is a name of the function to be invoked which accepts exactly one
parameter and the second argument is the parameter to be passed to a function. inc() and dec() are
functions which accept exactly one parameter and hence can be passed to change() function. inc()
function increments the value of the argument passed to it ad dec() function decrements the value
of the argument passed to it.

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

In the following program, the function decorated_greetings() is bound to a variable ‘decorated’


which passes a function ordinary_greetings() for decoration. Finally, the decorated function,
decorated() is invoked. ordinary_greetings() function was decorated and the returned function
was given the name ‘decorated’.

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)

In the following example, ordinary_greetings() function is passed to a decorator


decorated_greetings(). Hence on invocation of ordinary_greetings() function automatically
decorated_greetings() function is invoked by passing ordinary_gretings() function as its
parameter.

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.

Code Without List Comprehension


The following program creates a new list based on list ‘fruits’ which contains all elements
containing the letter ‘a’ in their names without employing list comprehension.

Code with List Comprehension


In the following example, the above program is re-written employing list comprehension which

renders the code compact.

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]

The expression in the example above can be interpreted as :


‘Return the item if it is not banana, if it is banana return orange’.

The condition is optional and can be omitted as shown below:

Without if statement:

newlist = [x for x in fruits]

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.

Return vs. Yield


The return is a final statement of a function. It provides a way to send some value back. While
returning, its local stack also gets flushed. And any new call will begin execution from the very
first statement.
On the contrary, the yield preserves the state between subsequent function calls. It resumes
execution from the point where it gave back the control to the caller, i.e., right after the last yield
statement.

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

Generator Yielding Tuple


The yield statement can return more than one value at a time in a tuple as demonstrated in the
following program. In the following example, gen() is a generator function which yields two tuples
containing two elements each.

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:

n = (e for e in range(50) if not e % 3)


i=0
for e in n:
print(e)
i += 1
if i > 100:
raise StopIteration

n = (e for e in range(50) if not e % 3)

for e in n:

print(e)

Generator Expression
# Demonstrate Python Generator Expression

# Define the list

alist = [4, 16, 64, 256]

# Find square root using the Generator Function

out = (a**(1/2) for a in alist)

for e in out:

print(e)

163
Conceptualizing Python in Google COLAB

Let's take an example of a generator that reverses a string.

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

[6, 12, 18, 24, 30]

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

The entire generator pipeline is depicted in the following figure:


[35, 40, 30, 55, 60]

pass_filter

[40, 55, 60]

add_bonus

[50, 65, 70]

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.

A program can employ one of the following approaches:

• anticipate and handle the exception in the program and take the corrective measures
• leave it to the system for processing

Standard or Pre-defined Exception in Python


List of standard exceptions is depicted in the following table:

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.

Displaying Descriptive Error Messages


When an exception is raised inn the program, an object of appropriate exception type is instantiated
and made available to the program. The program can access the exception object using the
following syntax:

except <exception_class> as <instance_name>

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

Handling Multiple Errors


More than one type of exception can be raised in a ‘try’ block and the program can contain different
except blocks for processing exception of each category as demonstrated in the following program:

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.

Note: The order of exceptions does not matter.

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:

• When exception is not thrown


• When exception is thrown
• When function returns

The different cases are depicted below:

181
Conceptualizing Python in Google COLAB
Case 1: No Exception is Raised

Case 2: ‘Division By Zero’ Exception is thrown in ‘try’ Block.

182
Conceptualizing Python in Google COLAB
Case 3: ‘NameError’ Exception is thrown in ‘try’ Block.

Case 4: ‘KeyError’ Exception is thrown in ‘try’ Block.

183
Conceptualizing Python in Google COLAB
The following table different cases summarized above:

try Block except except except except else finally Next


ZeroDivisionError IOError NameError Exception Block Block Statement
Block Block Block Block
No
Exception
result =
10 / 0
x=y
KeyError

Nested try Blocks


One ‘try’ block can be completely nested inside another ‘try’ block and this can continue upto any
level. In such a case, if the exception is thrown in inner-most try block, all the matching except
blocks are examined first, if the matching except block is found, the exception is processed and
the program execution continues, otherwise all the ‘except’ blocks corresponding to outer ‘try’ are
examined. This continues till outermost ‘except’ blocks are examined. If the matching catch bloc
is not found, then ultimately the exception is processed by the runtime system which results in
abnormal termination of the program.

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

Control Flow in Nested try Blocks


Case 1: No Exception is raised

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:

On execution the following output is generated:

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:

On execution the following output is generated:

191
Conceptualizing Python in Google COLAB

Case 4: NameError Exception is raised in Outer try Block


Modify outer and inner try blocks as shown below:

192
Conceptualizing Python in Google COLAB

On execution the following output is generated:

193
Conceptualizing Python in Google COLAB

Case 5: NameError Exception is raised in Inner try Block


Modify outer and inner try blocks as shown below:

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:

On execution the following output is generated:

196
Conceptualizing Python in Google COLAB

Case 7: ValueError Exception Raised in Inner try Block


Modify outer and inner try blocks as shown below:

197
Conceptualizing Python in Google COLAB

On execution the following output is generated:

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.

Rule 2: ‘else’ block if presn should be placed before ‘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.

Note: When multiple exceptions are specified, brackets are required.

What will be the output of the following Python code?

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.

On execution of the above program, the following output is generated:

What will be the output of the following Python code?

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.

On execution of the above program, the following output is generated:

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:

Copying File Path


For coping the path of the file, select and right-click on the file in Colab and select ‘Copy path’
option from the shortcut menu as shown below:

204
Conceptualizing Python in Google COLAB

Basic File Operations


Opening the File for IO
Before you can read or write a file, you have to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods associated
with it. The syntax of open() function is shown below:

file_object = open(file_name,[,access_mode],[,buffering])

The meaning of different parameters is depicted in the following table:

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.

File Access Modes

Here is a list of the different modes of opening a file −

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.

Here is a list of all attributes related to file object –

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

Creating a File and Writing Content


File I/O
The file object provides a set of access methods for performing file I/O, for writing contents to the
file and reading content from the file.

The write() Method


The write() method writes a string to the file opened in ‘w’, ‘w+’, ‘a’ or ‘a+’ modes which is
passed as an argument to it. It is important to note that Python strings can have binary data and not
just text.
The write() method does not add a newline character ('\n') to the end of the string. The syntax of
write() method is shown below:

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

Reading the Entire Content of the File


If no parameter is passed to read() method, the entire content of the file is read as demonstrated in
the following program:

213
Conceptualizing Python in Google COLAB

Tracking File Pointer


File Positions
The tell() method tells you the current position of the file pointer within the file; in other words,
the next read or write will occur at that many bytes from the beginning of the file.

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.

Querying Position of File Pointer


The tell() method of the file object returns the current position of the file pointer from the beginning
of the file which specifies the byte from which the next read or next write operation would
commence.

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

Difference Between w and wb


When the file is opened in ‘wb’ mode for writing in binary format. Passing a string to write()
method of file object throws ‘TypeError’ exception as shown in the following figure:

217
Conceptualizing Python in Google COLAB
To fix the bug use encode() method of ‘str’ class as shown in the following program:

Difference Between r and rb

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

Difference Between w and w+


‘w’ mode creates a new file, if the specified file does not exit or truncates the file, if the file already
exists.

Difference Between r and r+


‘r’ mode opens the file in read mode and places the file pointer at the beginning of the file. ‘r+’
mode opens the file for both reading and writing and does not truncate the contents of the file, if
the file already exists.

Difference Between r+ and w+


Both ‘r+’ and ‘w+’ modes open the file in read and write mode. The difference is that if the file
already exists, ‘w+’ deletes the contents while ‘r+’ does not delete the contents but overwrites it.
In the following program, the following tasks are performed:
• the file ‘test.txt’ is opened in ‘w’ mode for writing the content ‘MCA in SIBER’.
• the file is then closed and re-opened in ‘r’ mode for reading the contents.
• Next, the file is opened in ‘w+’ mode, new content ‘MBA’ is written to the file,

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

Managing File System


Python ‘os’ module provides methods that help you perform file-processing operations, such as
renaming and deleting 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.

The mkdir() Method


You can use the mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method which contains the name of the directory to be
created. The syntax of the method is shown below:

Syntax:
os.mkdir(<dir_name>)

224
Conceptualizing Python in Google COLAB
Creating Directories

The chdir() Method


You can use the chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory. The
syntax of the method is shown below:

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.

Applications of Regular Expressions


Regular expression have wide applications in,
• Pattern matching
• Data validation
• Text searching
• URL matching etc.

‘re’ Module in Python

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 first parameter is the regular expression pattern and


• The second parameter is the string to be tested.

The method returns a match object if the search is successful. If not, it returns None.

re.findall()

The re.findall() method returns a list of strings containing all matches.

228
Conceptualizing Python in Google COLAB
Example 1: re.findall()

If the pattern is not found, re.findall() returns an empty list.

Finding Multiple Occurrences of a Pattern

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()

The syntax of re.sub() is:

re.sub(pattern, replace, string)

229
Conceptualizing Python in Google COLAB
The method returns a string where matched occurrences are replaced with the content of replace
variable.

If the pattern is not found, re.sub() returns the original string.

Replacing Multiple Spaces with a Single Space


In the following program, multiple white space characters are replaced with a single space using
re.sub() method.

Removing Spaces from a String


In the following program, all spaces within the string are removed using re.sub() method.

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

The following program queries the return type of re.subn() method.

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.

Here, match variable contains a match object.

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

match.start(), match.end() and match.span()


The start() function returns the index of the start of the matched substring. Similarly, end() returns
the end index of the matched substring.

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:

Raw string using r prefix

match.re and match.string

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)

Replace pattern as shown below and re-execute:

pattern=':\d+'

236
Conceptualizing Python in Google COLAB

Character Repetitions
The following characters are employed to specify the repetition of characters in a string:

Meta character Meaning


* Zero or more occurrence of a preceding character
+ One or more occurrence of a preceding character
? Zero or One occurrence of a character
. Exactly one character

* Metacharacter (Zero or More Occurrence)


The patter ‘c*’ matches infinite no. of patterns, the strings containing ‘’, ‘c’, ‘cc’, ‘ccc’, . . . .etc.
The following program demonstrates testing whether the given string matches the pattern ‘c*’
The regular expression ab+c will give ac, abc, abbc, abbbc, … and so on.

237
Conceptualizing Python in Google COLAB

? Metacharacter (Zero or One Occurrence)


The patter ‘c?’ matches two search patterns, the strings containing ‘’ and ‘c’. The following
program demonstrates testing whether the given string matches the pattern ‘c?’

The search pattern ‘docx?’ (x is optional) matches one of the patterns ‘doc’ or ‘docx’.

238
Conceptualizing Python in Google COLAB

+ Metacharacter (One or More Occurrence)


The patter ‘c+’ matches infinite no. of patterns, the strings containing ‘c’, ‘cc’, ‘ccc’, . . . .etc. The
following program demonstrates testing whether the given string matches the pattern ‘c+’

The relationship between the meta characters ‘*’ and ‘+’ is that:

{*} = {} U {+}

Hence ‘c*’ pattern contains all strings of ‘c+’ in addition to ‘ ‘.

The regular expression ab+c will give abc, abbc, abbbc, … and so on.

239
Conceptualizing Python in Google COLAB

The curly braces {…}:


It informs to repeat the preceding character (or set of characters) for as many times as the value
inside this bracket.

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

Setting Position for Match


^ (Beginning of the String)
The ^ symbol tells the computer that the match must start at the beginning of the string or line.
The pattern ‘^\d{3}’ is interpreted as exactly 3 digits at the beginning of the string.

241
Conceptualizing Python in Google COLAB

$ (End of the String)


The $ symbol tells the computer that the match must occur at the end of the string or before \n at
the end of the line or string. The pattern ‘-\d{3}$’ is interpreted as the character ‘-‘ followed by
exactly 3 digits at the end of the string.

242
Conceptualizing Python in Google COLAB

Character Classes [] – Set of Characters


[set_of_characters] – Matches any single character in set_of_characters. By default, the match is
case-sensitive.

Example :
[abc] will match characters a, b and c in any string.

[^set_of_characters] – Negation: Matches any single character that is not in set_of_characters. By


default, the match is case sensitive.

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

The Escape Symbol : \


If you want to match for the actual ‘+’, ‘.’ etc. characters literally and no with a special meaning,
add a backslash( \ ) before that character. This will tell the computer to treat the following character
as a search character and consider it for matching pattern as demonstrated in the following
program. In the following program, the characters ‘+’ and ‘*’ are interpreted literally and not as
meta characters.

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)

Without parentheses the pattern

[A-Z]\w?

stands for

‘Any one character in the range A to Z followed by an optional white space character’

Difference Between a(bc)* and abc*

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 :

th(e|is|at) will match words - the, this and that.

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

You can use also the negation operator!

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

Validate Hexadecimal No. Using Regular Expression

248
Conceptualizing Python in Google COLAB
Character Validation

Exercise on Regular Expressions


Give regular expressions for the following

i. non-digit character [^0-9]

ii. first letter of a word is capital [A-Z]\w+

iii. All words starting with ab ^ab.*

iv. All words starting with ab and ending with cd ^ab.*cd$

v. Integer with any no. of digits \d+

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}

It matches at least 2 digits but not more than 4 digits

^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$

Regular expression for an email address :

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 and Object


A class is a template or a blue print for creating objects. An object is a class variable or a runtime
instance of a class.

Creating Classes in Python


The class statement is used for creating a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows − The syntax for creating a class inn
Python is shown below:

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:

‘self’ Keyword in Python


The ‘self’ keyword is used for referring to the data member of the class. Without ‘self’ keyword,
the variable is considered to be the local variable. Also, every member function of the class must
have ‘self’ as its first parameter as shown in the following program. However ‘self’ is not used
while invocating a method.

Object Creation in Python


__new__ is a static class method that lets us control object creation. Whenever we make a call to
the class constructor, it makes a call to __new__. Internally, __new__ is the constructor that returns
a valid and unpopulated object on which to call __init__.

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

data members are referenced using the following syntax:


self.<data_member_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:

Method 1: Using default constructor


p1 = Person()
The above statement creates a ‘Person’ object with name=’xyz’ and age=20.

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.

Method 3: Using two argument constructor


p1 = Person(name=”John”,36)
The above statement creates a ‘Person’ object with name=’John’ and age=36.

Constructor with Default Arguments


In the following program, the constructor of class ‘one’ takes two parameters ‘a’ and ‘b’ with the
default values of 1 and 2, respectively.

263
Conceptualizing Python in Google COLAB

Destroying Objects (Garbage Collection)


The memory management in Python is automatic. Python deletes unneeded objects (built-in types
or class instances) automatically to free the memory space. The process by which Python
periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection.

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.

Accessing the Class Members


Instead of using the normal statements to access attributes, you can use the functions depicted in
the following table:

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.

Built-In Class Attributes


Every Python class keeps following built-in attributes which are depicted in the following table
and they can be accessed using dot operator like any other attribute.

Attribute Name Description


__dict__ Dictionary containing the class's namespace.
__doc__ Class documentation string or none, if undefined
__name__ Class name.

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

The syntax for class inheritance is shown below:

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()

On execution of the above program, the following output is generated:

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.

A Class in Python has three types of access modifiers –

• Public Access Modifier

• Protected Access Modifier

• Private Access Modifier

Public Access Modifier:


The members of a class that are declared public are easily accessible from any part of the program.
All data members and member functions of a class are public by default.

A Program to Illustrate Public Access Modifier in a Class

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.

Protected Access Modifier:


The members of a class that are declared protected are only accessible to a class derived from it.
Data members of a class are declared protected by adding a single underscore ‘_’ symbol before
the data member of that class.

Program to illustrate protected access modifier in a class


In the following program, _name, _roll and _elective are protected data members and
_displayRollAndElective() method is a protected method of the super class Student. The
displayDetails() method is a public member function of the class ‘MCAStudent’ which is derived
from the ‘Student’ class, the displayDetails() method in ‘MCAStudent’ class accesses the
protected data members of the Student class.

272
Conceptualizing Python in Google COLAB

Private Access Modifier:


The members of a class that are declared private are accessible within the class only, private access
modifier is the most secure access modifier. Data members of a class are declared private by adding
a double underscore ‘__’ symbol before the data member of that class.

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:

display_public() → for displaying a public data member, x

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:

Method 1: Using super class name

<superclass_name>.__init__(self,x,y,z)
Super.__init__(self,x,y,z)
‘self’ parameter should be the first parameter while using class name.

Method 2: Using super() method

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.

issubclass() and isinstance() Methods


You can use issubclass() or isinstance() functions to check a relationships of two classes and
instances.
• The issubclass(sub, sup) boolean function returns true if the given subclass ‘sub’ is indeed
a subclass of the superclass ‘sup’.
• The isinstance(obj, Class) boolean function returns true if ‘obj’ is an instance of class
‘Class’ or is an instance of a subclass of Class

278
Conceptualizing Python in Google COLAB

These methods are demonstrated in the following program:

isinstance() Method Demo


The following program demonstrates the use of isinstance() method. The isinstance() method
returns ‘True’ if the instance passed to it as first argument is an instance of the class passed to the
method as second argument and all other classes which are above it in class hierarchy. In the
following program, the variable ‘c’ is an instance of ‘Child’ class which is a derived class of
‘Parent’ class. Hence both the following statements return ‘True’.
isinstance(c,Parent)
isinstance(c,Child)

However, the statement


isinstance(c,Student) returns ‘False’ since ‘Student’ and ‘Child’ are unrelated.

279
Conceptualizing Python in Google COLAB

Base Overloading Methods


Following table lists some generic functionality that you can override in your own classes −

280
Conceptualizing Python in Google COLAB

__str__ → Printable String Representation


When an instance of an class is passed to print() method, the module and class name is displayed
along with the hash code of the object as shown in the following figure:

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==n2 is translated to 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.

Python magic methods or special functions for operator overloading

How to overload the operators in Python?


We can overload all existing operators but we can’t create a new operator. To perform operator
overloading, Python provides some special function or magic function that is automatically
invoked when it is associated with that particular operator. For example, when we use + operator,
the magic method __add__ is automatically invoked in which the operation for + operator is
defined.

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

Overloading binary + operator in Vector Class


When we use an operator on user defined data types then automatically a special function or magic
function associated with that operator is invoked. Changing the behavior of operator is as simple
as changing the behavior of method or function. You define methods in your class and operators
work according to that behavior defined in methods. When we use + operator, the magic method
__add__ is automatically invoked in which the operation for + operator is defined. There by
changing this magic method’s code, we can give extra meaning to the + operator. In the following
example, the __add__() method is overloaded in ‘Vector’ class for defining addition operation on
two vector class objects.

286
Conceptualizing Python in Google COLAB

Overloading binary + operator in Python :


In the following example, the binary operator ‘+’ is overloaded to define addition operation on
two objects of ‘Test’ class which is tested for addition of two numbers and strings.

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.

Python program to overload a comparison operators


The following program demonstrates the overloading of comparison operator in class ‘A’.

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:

Example of inbuilt polymorphic functions :


In the following example, the built-in function len() is used for finding both the length of a string
and a length of a list. Hence, len() is a polymorphic function.

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:

On execution of the above program, the following output is generated:

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:

On execution of the above program, the following output is generated:

293
Conceptualizing Python in Google COLAB

Polymorphism with a Function and objects:


It is also possible to create a function that can take any object, allowing for polymorphism.

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:

• ‘x’ inherited from class ‘A’


• ‘y’ newly added by class ‘B’

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:

• ‘x’ inherited from class ‘A’


• ‘y’ inherited from class ‘A’
• ‘z’ newly added by class ‘C’

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:

Implementation of Complex Class


In the following program, the complex class is implemented with the following functionality:
• Overloading == operator (__eq__)
• Overloading + operator (__add__)
• Overloading - operator (__sub__)
• Stringifying object (__str__)

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:

i. 2/3 and -4/5


ii. -2/3 and 4/5

Test Case 2:

2/3 and 4/3

Test Case 3:

2/3 and 4/5

Test Case 4:

-2/3 and -4/3

Test Case 5:

-2/3 and -4/5

Test Case 6:

2/3 and -4/3

Test Case 7:

298
Conceptualizing Python in Google COLAB
2/3 and -4/5

Standardizing Rational No.s


The following code depicts the standardization procedure before comparing the two rational nos.
If the denominator of a rational no is negative, then the signs of numerator and denominator are
reversed.

Normalizing Rational No.s


The following code depicts the normalization of two rational no.s having different denominators.
If nr1 and dr1 are numerator and denominator of first rational no. and nr2 and dr2 are numerator
and denominator of second rational no. and if dr1 is not equal to dr2, then both numerator and
denominator of first rational no. are multiplied by dr2 and both numerator and denominator of
second rational no. are multiplied by dr1.
Hence the first rational no. is
𝑛𝑟1 ∗ 𝑑𝑟2
𝑑𝑟1 ∗ 𝑑𝑟2

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

Define the following operations on the objects of ‘Number’ class –


- __str__() method for displaying value along with proper sign
• increment
• decrement
• addition
• subtraction
• multiplication
• division
• max
• min

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.

Increment operation on objects of ‘Number’ class


Case 1 –
If ‘sign’ attribute of ‘Number’ object is +ve, then result is addition of one to value attribute and
sign is +ve.

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

Decrement operation on objects of ‘Number’ class


Case 1 –
If ‘sign’ attribute of ‘Number’ object is +ve, then result is subtraction of one from value attribute
and sign is +ve.

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):

if (self.sign=="+" and other.sign=="+"):

return Number(self.value+other.value,"+")

elif(self.sign=="-" and other.sign=="-"):

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

Implementation of Increment Operation


class Number:

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

elif (self.sign=="-" and 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):

if(self.value==0 and other.value==0):

return self

elif(self.sign=="+" and other.sign=="+"):

if(self.value > other.value):

value=self.value

else:

value=other.value

sign="+"

return Number(value,sign)

elif(self.value==0):

if(other.value>0 and other.sign=="+"):

return other

if(other.value>0 and other.sign=="-"):

return self

elif(other.value==0):

313
Conceptualizing Python in Google COLAB
if(self.value>0 and self.sign=="+"):

return self

if(self.value>0 and self.sign=="-"):

return other

elif(self.sign=="-" and other.sign=="-"):

if(self.value < other.value):

return self

else:

return other

elif (self.sign != other.sign):

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

Thought for Case Study 2 -


RationalNumber Class – Modeling Relationship Between Number and RationalNumber Classes

What is relationship between Number and RationalNumber class?

Inheritance

Delegation?

Delegation

Numerator and denominator are ‘Number’ class objects.

Delegate operations to objects of ‘Number’ class.

Number nr

318
Conceptualizing Python in Google COLAB
Number dr

2/3 4/5

r1.nr/ r1.dr

r2.nr/r2.dr

Second Case Study –

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

View publication stats

You might also like