Python
Python
DCA3104
PYTHON PROGRAMMING
Unit 1
Introduction to Python Programming
Table of Contents
1. INTRODUCTION
The computer understands binary language. It is a language that has only two letters, one
can say. These letters are 0 and 1. All other letters, words,
numbers, and even sentences are formed from the combination STUDY NOTE
of these two numbers. During the time when the first generation Lady Augusta Ada
Lovelace is known as the
of computers were developed, scientists had to provide
first programmer of the
commands to the computer using this binary language. Though world.
With the advancement of computer technologies in the coming generations, people moved
on from Machine Language, that is, the language of 0s and 1s to Assembly Language.
Assembly Languages are low level languages created as an intermediate between human
language, primarily English and Machine Language. They use symbols and predefined
keywords instead of 0s and 1s so that humans can easily provide commands to the computer
in a comprehensive language. Abbreviations such as Add for addition, Sub for subtraction,
etc., are used in low-level languages.
After Assembly Language, high-level languages were developed. These are more similar to
human languages and can be easily understood by anyone who does not have much
knowledge or experience of programming languages. They have a set of grammar rules so
that making instructions can be easier. These rules are called Syntax. It is different for
different high-level languages. A compiler and interpreter are used to convert the high-level
language into low-level or binary language. Various such high-level languages have been
developed, primary ones being C, FORTRAN, COBOL, C++, Python, etc.
These days, high-level languages are created such that they can be easy to understand to the
user. They should also have an easier syntax that is not restrained with too many rules. With
the need for complex and large programs used for web-based applications, it is necessary
that the programming language can handle numerous commands, libraries, and datatypes.
It is also essential that the commands are executed quickly with least probability of presence
of bugs and errors.
Python is such a high-level programming language that gives the freedom to the user while
maintaining the capability to hold complex programs. It is open to customization and has one
of the easiest syntaxes. Python was created with the aim to increase readability of code and
allow the programmers to decrease effort and lines of code while writing larger programs.
The competitive times call not just for a high-level programming language, but also for a
rapid application development (RAD) tool. Such tools should be able to design and support
large applications seamlessly while providing features like fast response and a simple
approach. All such needs are fulfilled by Python.
Python is one of the few languages that can be used as both, an interpreted and scripting
language. It is a free and open-source language that is easy to learn and approach. Especially
suited for Web applications, Python makes object-oriented programming simple and
dynamic, enabling one to create large applications that are durable and adaptable.
Python was developed in 1991, with the aim that it could help reduce the time spent on
monotonous and redundant tasks in programming. It is derived from the original scripting
language ABC. At that time, ABC was used solely to teach programming by a few people.
employed at CWI in 1989, where Guido van Rossum was located Guido van Rossum created
Python as a hobby project
at that time. It was released for the use of public in February that can be a descendant of
Unix.
1991, after it was integrated into the Amoeba project at CWI.
Since then, the development of the language has been carried out
at CNRI in Reston, Virginia, United States. By 2000, the developers of Python formed
Pythonlabs under the BeOpen network. Pythonlabs has been maintained and organised by
Guido van Rossum, among other primary developers of Python. Later in the year, Pythonlabs
moved under Digital Creations. It has since been working to develop and enrich the language
with more and better features. All the features, properties, etc., that are added to the
language are managed by Python Software Foundation, a non-profit organisation.
SELF-ASSESSMENT QUESTIONS - 1
Python is the backbone of various web-based applications such as YouTube, Dropbox, etc. Its
functionality and features such as supporting cross-platform operating systems make it a
great tool for various applications. Here are the real-life based applications where Python is
needed and highly used by top-notch companies.
Web Development
Source: Pinterest
Python supports various frameworks. This increases the security, scalability, and speed at
which a web-based application or website is developed and coded. There are multitudes of
framework that support the integration of HTTPS, FTP, SSL, and much more. Frameworks
like Flask, Django, and more can help the processing of JSON, E-Mail, XML, and other such
protocols.
The future is in machine learning and artificial intelligence. It is imperative to learn and
develop languages that can enhance these technologies and Python supports the experience.
For machine learning, the computer should be able to come up with an algorithm based on
its experience and learn by itself. This can be done by libraries such as NumPy, Pandas, and
more which are already present in Python.
Data Science
Game Development
Python also includes libraries that support 3D game engine such as PySoy, PyGame, etc.
These libraries ease and enhance the process of building a game. Python also ensures that
the game processes faster and without any bugs and errors.
Business Applications
Business applications should be scalable to support the business as it grows. They should
also be readable and extensible. Thus, languages like Python provide all such features to the
developers. Various platforms such as Tryton can create applications that are coded in
Python.
Desktop GUI
Using the Tkinter library available in Python, you can create desktop applications as well.
From simple applications such as post-it notes and calculators to high-end applications,
toolkits such as wxWidgets, PYQT, and others provided in Python can help you create and
develop various such applications.
There are various applications such as job listings, research and development, comparison
of prices, etc. when one needs to assess and analyse data from various websites and huge
databases. Python’s libraries such as BeautifulSoup can scrape and analyse such data without
compromising speed and efficiency.
Along with these, Python is used to develop various other applications such as audio and
video supporting apps, CAD applications, embedded applications, and much more. Its
flexibility and scalability make it suitable for high-level computations and complex codes.
SELF-ASSESSMENT QUESTIONS - 2
6. ___________ and _______________ libraries of Python are used in game development.
7. Through libraries such as Pandas, NumPy, etc., one can create programs for
__________________.
8. Python supports integration of HTTPS. (True / False)
When comparing Python with other languages, the one benefit that makes Python unique is
that it works as a bridge between interpreted and scripted languages. It holds the benefits of
both types of languages, making it a much more accessible option than its other counterparts.
Most scripted languages are slower than interpreted languages. However, Python provides
the user with the option to write scripts using Python without compromising on the speed
of the compiler. Python is usually compared to C and C++ because of its similar syntax. It is
majorly used to test applications written in C and C++. Python works better than these two
high-level languages as it provides various benefits over them such as memory allocation
and management, avoiding reference errors. The Python interpreter is responsible for
memory management. Also, with the rich library available in Python, you can write much
shorter and compact programs.
Another such language that can be compared by Python is Perl. Perl is another popular
language that is used for data extraction and text manipulation. It is mostly used for system
administration. However, Perl follows a difficult and much more complex syntax as
compared to Python. Perl can be used to create powerful CGI (Common Gateway Interface)
scripts but the code is difficult to comprehend and people working on a large project often
find it hard to understand each other’s code.
Tcl is also one of the programming languages that is often compared by Python. Tcl is as
powerful as Python and is an easy-to-use scripting language. However, the data types for
variables at Python are much richer than those available at Tcl. Tcl and Python have a similar
toolkit for developing GUI applications, called Tk. Though, people tend to favor Python while
developing such applications for its richer library.
developed. JPython provides various salient features such as providing a true object-
oriented programming environment and a scripting environment for Java.
Activity I
Research various famous websites and applications such as Snapchat, Instagram, Youtube, etc.
For a list of apps and websites that are based on Python and its versions and those which are
based on other programming languages.
SELF-ASSESSMENT QUESTIONS - 3
9. _____________ is an easy-to-use scripting language.
10. _____________ is the amalgamation of features of Java and Python.
11. Python has a similar syntax as C and C++. (True / False)
12. In Python, memory management is done by _________.
Python 2 was first developed and released in 2000. It has been one of the most successful
versions of Python, the most popular one being Python 2.7. It was released in 2010 and is
still in use by various companies.
Python 3 was created in 2008. At that time, most programmers and companies were already
using and were satisfied with the previous version of the language. However, the tools and
features added to Python 3 soon spread amongst the community, leading to a debate among
the programmers regarding which is the better version.
With the constant development and betterment of Python 3 and the strength of version
Python 3.5, it was clear that the newer version of Python is the clear winner of the debate
and should be the choice of new programmers who are just delving into the world of Python.
Now, most programmers agree that Python 2 dictates the legacy and the strength of the
programming language whereas for the newer and faster web-based applications suited to
the speed of the current generation, Python 3 and higher versions are much more suitable.
Here is a comparison between both versions to aid your understanding.
Incompatible Libraries
The libraries that were developed for Python 2 are incompatible with Python 3. Also, seeing
that Python 3 is the future, the libraries developed are strictly compatible with this version
only.
Unicode Support
In Python 2, strings were stored in ASCII by default. If you want to store a string in Unicode,
then you will have to specify a “u”. However, in Python 3, all the strings are stored in Unicode
by default. Unicode is much more versatile as compared to ASCII. It can also save various
symbols, numerals, emojis, Roman numerals, and much more.
In Python 2, if you divide two integers that will result in a decimal answer, then the compiler
will round off the answer to the nearest integer. Hence, to get an answer in decimal form,
you will have to specify decimals in the subtraction. For example, use 2.0 instead of 2.
In Python 3, the compiler is expected to return the result in decimal if the answer is decimal.
You do not have to add a decimal in the question.
Various companies such as Instagram and Facebook are moving from Python 2 to Python 3.
This is because the newer function has a faster runtime. Also, there will be no developments
in Python 2 after the version Python 2.7, making it a thing of the past.
SELF-ASSESSMENT QUESTIONS - 4
13. ____________ was the last version of Python 2, after which its development was
stopped.
14. _____________ and __________ are some of the companies that are upgrading from
Python 2 to Python 3.
15. In Python 3, strings are stored in __________ by default.
16. You need to specify decimals to get the result in decimals in ___________.
The best feature of Python can be its ease. Programmers can pick Python as their first
language to learn. You can easily develop large applications using it. It can also act as a bridge
to connect the programmers to other, more advanced programming languages. Here are
some of the prominent features of Python that make it a flexible and strong option for most
developers.
You can understand code written in Python even if you have no background in programming.
It has an easy syntax that uses the common language without the presence of complex
keywords. Lack of too many keywords and simple semantics used in Python ensures that
one can learn it with relative ease. It is a simplified version of primary programming
languages such as C, Algol, Pascal, etc., and follow the same syntax.
Though an object-oriented language, it is not necessary to use the concept in Python. One can
run various applications and operations without it, a feature that makes it easier to approach
than C++.
Python uses very few symbols within the code, to make coding simple and straightforward.
It does not need a symbol to show the end of a command, nor does it need curly braces ({})
to indicate a block of statements. One can use indentation to group statements as a single
code block, ensuring lesser bugs and easier comprehension of the code.
Source: Sitesbay
Python is an intuitive language. While using C and other such languages, one has to declare
the datatype of the variable before storing any data in it. Also, other features such as system
call, strings or varying lengths, etc., need a chunk of code to be written in C. Python reduces
the time and energy spent on understanding and writing the code by providing built-in
modules to its users. Lists, dictionaries, and other high level data types that can be used in
Python are already built into Python. Thus, using them requires lesser time and
understanding of the language. Also, Python assumes the datatype of a variable once you
assign a value to it, decreasing the length of the code.
Scalable
Scripting languages such as Unix work seamlessly and are easy to use while performing easy
and straightforward tasks. However, once you start adding more lines to the code or features
in the script, it becomes complicated and slow. These days, even smaller applications need
large code and scripts to include all the required features. Hence, these scripting languages
cannot keep up with today’s need of fast and scalable programming languages. Through
Python, one can merge one code to another or insert new features in an existing code without
worrying about the speed of the code. Python ensures more functionality by allowing the
user to change and modify the code by adding plug-ins and advancing architecture of an
existing script.
Object-Oriented Language
Interpreted Language
Python is an interpreted language as the interpreter can print the result when in command-
line mode. Signs such as “>>>” work as a prompt, indicating that the interpreter is ready to
use.
Another way a program can be interpreted is through executing a file. Such a file is called a
script and is saved with an extension of .py. To execute the file, the name of the script has to
be written for the interpreter to understand.
Flexible
A large code can be hard to understand and debug. Python allows fragmenting the code into
smaller, more manageable parts. These parts, or modules, can still interact with each other
and connect with the other in-built modules. Python allows flexibility to the user by letting
them to interact with the external environment while using the module.
Library
Python comes with a rich library of modules that can be integrated into the program. The
library is updated and maintained by Python Standard Library. These modules can ease the
process of coding and shorten the length of the code as well. The library can be used to write
codes that perform the tasks of HTTP, FTP, POP, etc. You can write applications for various
functions with the help of the in-built modules of python that are used to develop graphic
user interface, downloading a webpage, and various others.
Memory Management
Python is a dynamic language. It can not only handle complex programs with ease, but also
supports several environments. Web applications based on the internet and intranet need
such features in a programming language for them to work smoothly. Through the rich
library system and flexibility of Python, you can write several complex programs and codes
that support advanced features such as HTML, SGML parsing, XML, CGI scripts, etc.
Database
Through the in-built modules available in the library of Python, you can handle several flat
file databases. It has the capability to provide interfaces for major databases. One of the most
essential and multi-featured databases of Python is Python API. It eases the process of
writing codes for applications through which you can communicate with different databases.
Object Distribution
Through Python, you can use objects that are distributed over various platforms. The code
can communicate and interact with objects that are coded or available in other languages.
One such example is passing data to COM components.
Embeddable
Python interpreter can be extended with low-level modules. These extensions let the
programmer customise the program according to the needs and interface of the application
needed. You can connect Python to external libraries and modules to implement new data
types in the code. Extension modules on Python can be programmed in other languages such
as C and C++ for CPython and in Java for JPython.
GUI Programming
Python holds a graphic user interface library Tkinter that allows the user to create GUI
applications for different systems and libraries such as Windows MFC, X Window system of
Unix, Macintosh, and more. Tkinter has the object-oriented interface of TK GUI API.
Portable
Python is written as ANSI C. Hence, it is not tied to one particular operating software and can
be used over a large number of platforms without losing any of its features or credibility. One
can write, execute, test, and upload a program written in Python in various environments
including Macintosh, Linux, and Windows. However, the application will run as per the
commands specified in it. If the commands are specified for one environment, for example,
Linux, then the program will not be able to implement properly when interpreted in other
environments.
Freeware
Python is an open-source language and thus can be redistributed freely. Anyone can use
Python’s source in any way they want without harming or putting it as risk. Also, the users
are dissuaded from trying to take over the copyright of the source code. The programmers
and users around the world can freely use Python to create codes using modules from the
library in byte-compiled form.
Exception Handling
Through exception handling, Python can generate a stack trace of errors. This is when due
to an error or bug in the program, Python exits. With the help of the trace, you can detect
errors during run time without the need of statements that can check errors. The
programmer does not have to spend a lot of time debugging the code as the Exception
Handler can detect the problem, diffuse it, and perform a maintenance check.
SELF-ASSESSMENT QUESTIONS - 5
17. Python is considered a scripting language. (True / False)
18. Python does not need to be compiled before being run. (True / False)
19. It is necessary to understand and implement object-oriented programming while
using Python even for the simplest programs. (True / False)
20. Python is mainly used for web-based applications. (True / False)
Python is majorly used to write various web-based applications. To make the process of
coding easier, various modules are created and stored in the library of python. The collection
of these modules is called a framework. Frameworks allow one to integrate codes for low-
level details and help the programmer to save time.
By using various frameworks, one can automate the implementation of common commands,
thus giving the user the time to spend on web-based application logic and algorithms.
Django
It is an open-source and free framework. Based on the DRY principle, or Don’t Repeat
Yourself, Django uses ORM mappers. Object-relational mapper is used to manipulate the data
from a database. It uses an object-oriented paradigm. Through Django, one can get various
essential features in their code such as ORM, template engine, URL routing, authentication,
and database schema migrations.
Web2Py
It is another full-stack framework for Python that is scalable and open-source. It can be
installed without any special prerequisites. Web2Py can be implemented and run-in various
environments and different platforms. It protects the code against cross-site scripting, SQL
injection, etc. It comes with its own code editor, debugger, and has a one-click deployment
as well. It does not support Python 3 as of yet.
Flask
This lightweight micro-framework is customisable and adapts to the needs of the user. It
provides multitudes of features such as a quick and seamless debugger, built-in development
server, secure cookie support. It also supports HTTP request handling, can plug in any ORM,
supports Jinja2 templating, and is Unicode based.
Bottle
The bottle provides default features such as templating, routing, a built-in development
server, an abstraction layer over the WSGI standard. It is a micro-framework whose server
can support all other WSGI-capable HTTP servers. It can also access data to create file
uploads, cookies, headers, etc.
CherryPy
Different frameworks are suited for various applications. All offer different functionalities
that can be chosen as per the purpose of the program. You will have to assess the need for
the program and choose the framework that provides the required features.
Activity II
Create an algorithm for any program or task of your choice. Find the frameworks that
can help you ease the algorithm and shorten your time if you were to code the algorithm
using Python.
SELF-ASSESSMENT QUESTIONS - 6
21. Flask is a ____________ kind of framework.
22. __________ is the collection of modules that can be integrated in a Python code.
23. _____________ can run various HTTP servers at the same time.
24. Web2Py can support both Python 2 and Python 3. (True / False)
8. SUMMARY
9. GLOSSARY
Introduction to
Python
Language
Popular
Frameworks
of Libraries
About Python
Language
Need and
Applications
of Python
Language
Instagram uses Python as a runtime use to execute their code. They have a database of more
than 800 million active users. Python provides them with efficiency and speed needed to
maintain such a database and execute the code seamlessly.
They collect and manage their data with an interpreter called InstaLab. It collects
information of a user without affecting the user’s experience on the app and website.
They are always looking for ways that can decrease the workload in the interpreter.
According to the stats, 90% of the instructions handled by the interpreter are related to
operand stack manipulation, control flow, and attribute access.
It was a complete success by using the python in the Instagram to track the runtime and to
store all the needed information’s.
Questions
1) Find out more about the techniques used by Instagram to decrease their runtime and
load on the interpreter.
2) Discuss various frameworks that applications like Instagram can use to decrease the
lines of code.
12. ANSWERS
TERMINAL QUESTIONS
Answer 1: Object-oriented programming is one in which each data and functions are
attributed as objects. An abstract data type is created by the developer. These objects are
defined as classes. The objects are used to provide structure to the programming.
Answer 3: Python is considered an interpreted language because the code goes through an
interpreter while being run. The interpreter turns the keywords and other commands to
machine language so that the computer can process it.
Answer 4: Python is used to develop web-based applications that support protocols such as
HTTPS and FTP. It is also used to create seamless and faster 3D game through various
libraries present in Python.
Answer 5: In Python 2, strings were stored in ASCII by default. If you want to store a string
in Unicode, then you will have to specify a “u”. However, in Python 3, all the strings are stored
in Unicode by default. Unicode is much more versatile as compared to ASCII. It can also save
various symbols, numerals, emojis, Roman numerals, and much more.
Answer 1: Python 2 stores strings in ASCII code by default whereas they are stored in
Unicode in Python 3. No small brackets are needed for keywords in Python 3 as opposed to
Python 2. Python 2 rounds of the answer of division it is in decimal form. Python 3 gives a
decimal answer. The development of Python 2 has stopped; hence no run time developments
will be done in that version.
Answer 2: Python is an interpreted language. That means that, unlike languages like C and
its variants, Python does not need to be compiled before it is run.
Python is suitable for object orientated programming in that it allows the definition of classes
along with composition and inheritance.
Answer 3: Frameworks are collection of modules that decrease the number of lines of
commands. In Python, various frameworks can be integrated. These are divided into two
subcategories, full stacked and micro frameworks. The following are the most prominent
ones used by developers.
Django
Flask
Bottle
Web2Py
CherryPy
Answer 4: Python is mostly used to develop web-based applications. It is also used for the
following purposes.
Game development: Using PyGame and other libraries, 3D games can be developed using
Python.
Data Science: Python can manage a huge database and analyse it. Thus, it can be used by
data scientists to obtain results.
Web Scraping Applications: Python can analyse various websites and compare the data in
them.
BOOKS:
E- REFERENCES:
• Python Programming Certification Training Course, last viewed on March 23, 2021 <
https://www.edureka.co/python-programming-certification-training >
• Python Tutorials and Sample Programs, last viewed on March 23, 2021 <
https://www.w3schools.com/python/ >
• History of Python, last viewed on March 23, 2021
< https://en.wikipedia.org/wiki/History_of_Python >
DCA3104
PYTHON PROGRAMMING
Unit 2
Environmental Set Up and Introduction
Table of Contents
1. INTRODUCTION
As we learnt, Python is an essential tool for developing web-based applications with large
databases. Not only that, Python can handle external files with immense data and has the
ability to analyses them with the least error and most efficiency. These features make Python
a suitable choice for scientists who need to investigate the data for their experiments or
evaluate the data obtained from observations. Python can examine the data and visualize it
in a well-manageable manner.
Anaconda Inc. developed the product and takes care of its maintenance. As it is an Anaconda
Inc. product, it is also known as Anaconda Individual Edition and Anaconda Distribution.
Package Management System Conda manages the various package versions of Anaconda.
This package manager was rolled out as a stand-alone open-source package. The reason
behind this decision was the usage of the package for things other than Python. There is a
small and bootstrap version of Anaconda, which comprises only the Python, Conda, a few
packages it is dependent on, and some other packages. The version is known as Miniconda.
• Anaconda allows you the opportunity to libraries and dependencies with Conda.
• Users have the option to download from over 1500 R/Python data science packages.
• User can use NumPy, Dask, Numba, and Pandas to analyze data scalably and quickly.
• Train and build ML and deep learning models with Scikit-learn, Theano, and
TensorFlow.
• Perform visualization with Bokeh, Matplotlib, Datashader, and Holoviews
2. SYSTEM REQUIREMENTS
You need to ensure that all your system meets all the requirements before you proceed with
the installation of Anaconda. Depending on whether you are using the free Anaconda
distribution or you are an Anaconda Enterprise 4 user, the system requirements will be
different. Let us look at the system requirements for both of them one by one-
Source: mrmint.fr
Fig 1: Anaconda
Hardware Requirements
Without satisfying the hardware requirements, it will not be possible to move ahead with
the installation. The requirements are-
Software Requirements
The minimum software requirements are essential to ensure the smooth functioning of the
application. They are-
• The system should have MongoDB 2.6. It will be provided with the installation files.
• The user should have the Anaconda Repository license file.
• RHEL/CentOS 6.5 to 7.4, Ubuntu 12.04+. Additionally, Ubuntu users might need to
install cURL.
• The user should have Linux system accounts. The following are required- Mongod
(RHEL) or MongoDB (Ubuntu)
• The system should have access to the Anaconda server.
• Cron entry is required to start the repo on reboot.
Security Requirements
The security requirements ensure that the data is protected and no data-breach takes place.
The security requirements are-
Network Requirements
TCP ports will be required. Most of the below requirements are optional, and it is up to the
user if he considers them as must-haves.
o repo.anaconda.com
o anaconda.org
o conda.anaconda.org
o binstar-cio-packages-prod.s3.amazonaws.com
o 820451f3d8380952ce65-
4cc6343b423784e82fd202bb87cf87cf.ssl.cf1.rackcdn.com
• An outbound Simple Mail Transfer Protocol: Transmission Control Protocol 25 (if not
using AD/LDAP) email notifications. It is not compulsory to incorporate it.
• An outbound LDAP(s): TCP 389/636 for authentication integration. It is not a
mandatory requirement.
Other Requirements
• A license file provided to you by Anaconda at the time of purchasing the product.
• The installation tokens for Binstar and anaconda-server channels provided by
Anaconda while purchasing the product. It is not applicable for air-gapped installs.
• It is an optional requirement: Your Anaconda.org account credentials. It is not
applicable for air-gapped installs.
It is mandatory to review the system requirements before installing the Anaconda individual
edition. The requirements are-
SELF-ASSESSMENT QUESTIONS - 1
1. A RAM of 16 GB will not suffice for the Anaconda installation. (True or False)
3. INSTALLATION OF ANACONDA
Once you are done verifying the system requirements, the next step is to start with the
installation process. If you do not want several packages to be installed with Anaconda, you
can choose to install Miniconda. It is a smaller version of Anaconda that includes Python,
Conda, and its dependencies.
On macOS, Windows, and Linux, it will be the most convenient to install Anaconda for the
local user. Thus, administrator permissions will not be required. The following are the steps
to install Anaconda on your system-
1) Go to the
STUDY NOTE
https://www.anaconda.com/products/individual link
Anaconda is most popularly
to download Anaconda for your respective OS (macOS, used for machine learning and
data science.
Windows, or Linux). You can download the installer
either for Python 3.7 or Python 2.7 (whichever is the
latest). Also, you can download it for a 32-bit machine or a 64-bit machine as per your
machine specifications.
2) The Anaconda setup would have downloaded in .exe format. Click on the file to open.
Click on the 'next' button.
3) You should reach the license agreement page. Read the agreement and click on 'I Agree'
and move to the next page.
4) You can choose to install Anaconda only for yourself or for all users. You will need
administrative privileges to install it for everyone.
5) Choose the folder where you want to install it. You will be able to see the available space
on the system and how much is required by the application.
6) Now, you reach the screen of advanced options. Firstly, you need to add Anaconda to the
PATH environment variable of the system. Now, register it as the primary system Python
3.7. If you add Anaconda to the PATH, it will be found before any other installation. Click
on the "Install" button.
7) It will take some to extract the files and unpack the packages on the machine. The
installation will be complete in some time. Click on the 'next' button
8) The next screen will inform you about PyCharm. Click on the 'Next button. The
installation is complete. Click on the 'Finish' button.
9) Now, you will be able to see Anaconda in the Start menu. You can open a Jupyter
notebook and create a new notebook.
SELF-ASSESSMENT QUESTIONS - 2
6. Anaconda can only be installed for local user. (True/False)
7. _______ is a mini version of Anaconda.
8. You will need ________ privileges to install Anaconda for all users on your system.
9. Miniconda includes _____, _______, and _______.
10. The extension of Anaconda software is ____________.
4. ANACONDA NAVIGATOR
The Anaconda Navigator is a Graphical User Interface (GUI) that allows you to conveniently
manage environments, Conda packages, and various channels without the need of using
command-line commands. The navigator is included in the Anaconda distribution and allows
you to launch various applications. Navigator can be used to search for packages on the
website Anaconda.org, or in a local Anaconda Repository. It is available for macOS, Windows,
and Linux.
To run, several scientific packages are dependent on particular versions of other packages.
Data scientists often use several versions of many packages and use distinct environments
to separate these different versions. The command-line program Conda is both an
environment manager and a package manager. This feature helps data scientists in ensuring
that each version of every package has all the dependencies it needs and works as per
expectations.
Navigator is a convenient, GUI way to work with environments and packages without having
to type Conda commands in the terminal window. You can use the navigator to find the
packages you are looking for, install them in the environment, run the packages, and update
them.
• JupyterLab
• Jupyter Notebook
• VSCode
• RStudio
• Spyder
• Glueviz
• Orange 3 App
• PyCharm
• Anaconda Prompt (Windows only)
• Anaconda PowerShell (Windows only)
User having an advanced level of experience in Conda can build their applications as well.
The simplest way to run a piece of code in Navigator is using Spyder. Navigate to the
navigator home tab and click on Spyder. You can write and execute your code.
The process to start the Navigator depends on the Operating System. Follow the below steps
to start the navigator in different Operating systems:
1. Windows: Click on the Anaconda Navigator Desktop app from the Start Menu. Another
way could be to search for Anaconda Prompt from the Start Menu and then type in the
command anaconda-navigator.
2. Linux: Type in "anaconda-navigator" after opening the terminal window. The
Navigator will open up.
3. MacOS: Click on the Anaconda Navigator icon from the launchpad. Alternatively, you
can open the terminal from the launchpad and type in anaconda-navigator.
Activity I
Divide into groups in your class or among your friends. Base the division on the factor
that which person owns a macOS, a Windows, and a Linux. Compare the interface of
Anaconda in different operating environments.
SELF-ASSESSMENT QUESTIONS - 3
11. What should you type in the terminal window in macOS to launch the Anaconda
Navigator?
12. In how many ways can you launch the Anaconda Navigator in Windows?
13. Can we work in Anaconda Navigator without having to type commands?
14. The Anaconda Navigator is a Character User Interface. (True or False)
15. Anaconda Prompt can only work on _______________ operating software.
Modules refer to a file containing Python definitions and statements. Any file containing a
Python code, for example, Abc.py, is known as a module, and its module name would be ABC.
Any package in Anaconda can be installed using the command "Conda install Package name".
All packages are located in the package repository. Apart from the packages, the major
components of Anaconda are listed below-
5.1 JUPYTERLAB
One of the biggest advantages of JupyterLab is the option to arrange several documents side
by side in the working area using splitters and tabs. Various activities and documents
integrate seamlessly and thus enable the creation of new workflows which act as a push for
interactive computing. A few examples of the same are-
• The Code Consoles provide temporary scratchpads for executing and running the code
interactively. It behaves as major support for rich output. A code console can be
connected to a notebook kernel which will act as a computation log from the notebook.
• Documents that are kernel-backed allow code in any format of a text file (Markdown,
R, Latex, or Markdown) to run in a Jupyter kernel interactively. Outputs of notebook
cells can be mirrored into a tab of their own. These tabs can be side by side with the
notebooks. Simple dashboards are enabled with interactive controls along with a
kernel.
• Multiple views of documents are allowed where viewers enable live editing of their
documents which will be reflected in the documents of other viewers.
Another advantage of JupyterLab is that it allows handling and viewing data formats in
various file formats like JSON, PDF, and CSV. You will also get the option to use key maps and
customizable shortcuts on the keyboards.
The Jupyter Notebook is popular for extending the console-based approach to interactive
computing in a new direction. It provides a web-based application that can capture the end-
to-end computation process. The process involves documenting, developing, and executing
the code followed by communicating the results to the users. The Jupyter notebook
comprises two components:
Notebook documents contain both the input and output of an interactive session in addition
to the text that accompanies the code and is not meant for execution. Thus, Jupyter
Notebooks can be considered as a computational record of the sessions. It also includes
mathematics, explanatory text, and executable code. These documents are JSON files and can
be easily shared with colleagues. As we are using Jupyter in a browser, our computer will be
acting as the server. Hence, Jupyter does not need to send our data elsewhere.
5.3 Spyder
5.4 PYCHARM
Another free version is also available called Edu. It is used to learn programming languages
for other technologies related to educational tools.
The paid version of PyCharm is called Professional. It is widely used by developers for code
assistance, visual debugging, remote configurations, assistance, etc. The salient features of
PyCharm are explained below.
Code completion: Through PyCharm you can experience intuitive code completion for built-
in and external packages alike.
Code coverage: Files with extension .py can be run outside of PyCharm editor as well.
Package Management: The packages installed are displayed with appropriate visual
representation.
Refactoring: Through refactoring, one can name one or more files at the same time.
PyCharm makes this process much smoother.
Local History: PyCharm keeps track of the changes made in a file locally.
5.5 VS CODE
VS Code or Visual Studio Code supports code and development in various programming
languages through its extension model. You can use the Python extension to use the VS Code
for developing programs and scripts in Python. Here is a brief list of features provided by the
VS Code when used for Python.
• It supports all versions of Python, including the classic Python 2.7 and the newer
versions of Python 3.4 and above.
• It offers code completion with its unique IntelliSense.
• It enables the automatic use of virtual environments and conda.
• You can use Jupyter environments and Jupyter Notebooks for code editing.
• Visual Studio Code also provides themes through which you can customize the UI as
per your choice.
• Varied language packs ensure that the experience of working on the VS Code is
inclusive and localised.
• Code snippets
• Debugging Support
5.6 GLUEVIZ
Glue has become an integral part of the complete Python programming experience with its
indispensable features and the ability to explore relationships between related datasets. One
can explore the environment of object-oriented programming with the help of Glue. It is used
to analyse astronomical data such as the formation of stars through clouds and
comprehending medical data. prominent features of Glue are listed below.
Linked Visualizations: With the help of Glue, you can visualise data in the form of
histograms, 2D, 3D images. scatter plots, etc. It also supports the brushing and linking
paradigm. Thus, if data is selected in a graph, then it propagates to other sets of data.
Scripting Ability: You can integrate Python codes into Glue seamlessly. The Glue itself is
written in Python. The integration can help in cleaning, input, and analysis of the data.
Data Linking: Glue has immense potential when it comes to linking two or more sets of
different data. It uses logical links that relate to these data and with the help of them,
visualizes it. The links can be specified by the programmer and are flexible.
large data and provides comprehensive visualizations for the chosen data. Orange 3 also
supports basic machine learning skills and analyses.
The features of Orange 3 have been a boon for various fields of research where the scientists
need to analyses the data obtained from a multitude of experiments. Here are some of its
features that make it an easily approachable option.
Interactive Visualization: You can scatter plot, box plot, make decision trees, hierarchical
clustering, linear projections, heat maps, and more.
Visual Programming: You do not have to dive deep into the coding part to make it work.
The graphic user interface includes widgets that make analyzing datasets much easier.
5.8 RSTUDIO
RStudio is a data science tool that is free and open-source. RStudio amalgamates its features
with Python to bring data scientists and users the best of both ecosystems. R language comes
with a rich selection of libraries that make any kind of statistical analysis possible. There are
around 12000 packages available in CRAN. Through the integration of R and Python, you can
run scripts that handle a huge amount of data.
RStudio IDE has been created primarily for the use of data analysis and statistics. Though
you cannot construct models using R, you have access and flexibility to using different
libraries.
Anaconda Prompt is a command-line shell where you can type in commands to perform a
function instead of using the mouse or keyboard shortcuts. One can solve various problems
while using Python with the help of Anaconda Prompt. Anaconda Prompt works similarly to
Command Prompt as well. The difference is that when using Anaconda Prompt, you can still
use Anaconda and conda commands from the prompt. You do not have to change the
directories or the path.
Conda does not work in the command prompt. To update conda, you will have to use the
Anaconda prompt. When you open Anaconda Prompt, you will find that it already has the
locations of the commands and scripts that are saved on the system. You can run these scripts
using the prompt.
Anaconda PowerShell Prompt is a window shell environment in which you can run conda
commands. On the Anaconda PowerShell, the user can run various PowerShell commands.
These commands will not be recognized by the usual Anaconda Prompt.
SELF-ASSESSMENT QUESTIONS - 4
16. ____________ is the Python module used by data scientists.
20. Which of the following is not a Python stack module supported by Spyder?
A. Stream API
B. Pandas
C. NumPy
D. Cython
Now that the setup of the Jupyter Notebook is complete, let us try to run a simple program
on it. Here are the steps that will guide you through creating a notebook and running a code
in it.
Step 1: First, open the terminal and head to the directory where you want to save the
notebook. Now, type the command Jupyter notebook. The program will initiate a local server
or at any other specific port.
Step 2: Once the Jupyter Notebook window pops up on your screen, create a new Notebook.
Step 4: Now, click on the cell where the code is written. Press SHIFT+ENTER. You can also
click on the play button at the top of the cell.
Step 5: Once you run the code, the output will appear in the space at the bottom of the
window. You can now press the stop button to stop running the code.
System
Requirements Installation of
Anaconda
Running a simple
code Python
using Jupyter
and Spyder
Environmental Anaconda
Ste up and Navigator
Introduction
JupyterLab
Different Anaconda
Modules for Powershell
JupyterNoteboo
Anaconda (Windows Only)
k
Anaconda
Spyder Prompt
(Windows
Only)
PyCharm RStudio
VSCode Orange 3
Glueviz App
7. SUMMARY
8. GLOSSARY
9. CASE STUDY
A school has recently set up and needs a website to expand their online activities such as
offering online courses, study resources, and notices to the students and other aids for
parents. They also need the website to accommodate the enrolment form for new students
and submitting applications for other certificates.
The website needs to be scalable, easily navigable, and light-weight. A technical team has
been set up that needs to determine the requirements of the school, download Python and
understand its workings, determine the system requirements that will be needed to develop
the code for the website. They will also have to install Python and its different execution
modes. The team can employ the modules of Python available to make the task easier and
faster.
Source-basicpy.com
Discussion Questions:
1. Which modules will you suggest to be used for the development of the website if you
were a part of the team?
2. Discuss why the technical team chose Python as the programming language to develop
their code in?
11. ANSWERS
1. False
2. False
3. Windows and MacOS
4. 5
5. No
6. False
7. Miniconda
8. Administrative
9. Conda, Python, its dependencies
10. .exe
11. Anaconda-navigator
12. 2
13. Yes
14. False
15. Windows
16. RStudio
17. Professional
18. Jupyter Notebook
19. Modules
20. A) Stream API
TERMINAL QUESTIONS:
Answer 2: Miniconda is a smaller version of Anaconda. It includes Conda, Python, and its
dependencies.
• JupyterLab
• Jupyter Notebook
• VSCode
• RStudio
• Spyder
• Glueviz
• Orange 3 App
• PyCharm
• Anaconda Prompt (Windows only)
• Anaconda PowerShell (Windows only)
Answer 4: You can click on the Anaconda Navigator icon from the launchpad to open the
Anaconda Navigator. Alternatively, you can open the terminal from the launchpad and type
in anaconda-navigator.
Answer 1: There are various modules of Python. These are developed to ease the process of
development and debugging. Here are the two modules.
1. PyCharm: Created especially for Python, this module has an intuitive code completion
along with various other features including debugging, refactoring, code coverage and
more.
2. VS Code: Visual Studio Code can also be used to write and code scripts for Python. It
analyses the data and provides visual aids for its better comprehension.
Answer 2: IDE are Integrated Development Environments that are developed for Python.
These make the process of coding, debugging, and implementing a code in Python easier.
They have inclusive features and are much more intuitive text editors. They are lightweight
and are used by people with little experience in coding to analyses data or by people who are
beginning to learn a programming language.
Answer 3: PyCharm is another popular IDE used for creating scripts in Python. It provides
various essential tools that enhance the experience of developers while using Python. They
provide an integrated environment to enhance the productivity of app development in
Python. It is available in editions. The free and open-sourced one is called the Community
version. The paid version of PyCharm is called Professional. It is widely used by developers
for code assistance, visual debugging, remote configurations, assistance, etc. The salient
features of PyCharm are explained below.
Code completion: Through PyCharm you can experience intuitive code completion for built-
in and external packages alike.
Code coverage: Files with extension .py can be run outside of PyCharm editor as well.
Package Management: The packages installed are displayed with appropriate visual
representation.
Refactoring: Through refactoring, one can name one or more files at the same time.
PyCharm makes this process much smoother.
Local History: PyCharm keeps track of the changes made in a file locally.
Answer 4: It is mandatory to review the system requirements before installing the Anaconda
individual edition. The requirements are-
• If your operating system is older than what is currently supported, you can find older
versions of the Anaconda installers in the archived section.
• The system architecture should have the following features: Windows- 64-bit x86, 32-
bit x86; MacOS- 64-bit x86; Linux- 64-bit x86, 64-bit Power8/Power9.
Books:
E-References
• Python Programming Certification Training Course, last viewed on March 25, 2021
https://www.edureka.co/python-programming-certification-training
• Python Tutorials and Sample Programs, last viewed on March 25, 2021
https://www.w3schools.com/python/
• Integrated Development Environments, last viewed on March 25, 2021
https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
DCA3104
PYTHON PROGRAMMING
Unit 3
Python Variables and Datatypes
Table of Contents
1. INTRODUCTION
Now that you have understood how essential Python is for developing any application,
especially web-based ones, the next step is to learn different elements of the language. Till
now, you have learnt that alphabets are an essential part of learning. In the next unit, you
understood why you need a dedicated workspace, or a notebook to fit our analogy. The next
Take an example. A family of four need to go to a relative’s place. Now for the transportation
of 4 members, getting an empty bus will be called a waste of space, money, and fuel. Most of
the seats on the bus will go empty. Now, you will also not get a bicycle for them. The bicycle
does not have enough space for all four members. Similarly, computers categorize different
kinds of data that require different memories. This way, each data type has enough memory
to store its value.
For example, when one is recording someone’s age, it is usually done in whole numbers.
Whereas, when recording someone’s height, you need a decimal number. Intuitively, one
might say that a whole number requires less space for storage in comparison to a decimal
number. Thus, both these numbers will be allocated different sizes of memories by the
computer.
Through this chapter, you will come to understand the working of Python and its syntax.
Once you understand the syntax, you will be able to write basic programs that include
various operators, variables, and datatypes. Various real-world examples will also guide you
through the varied applications of Python and its straightforward syntax.
❖ Explain the concept of variables and how to declare and assign a value to them.
❖ Describe the difference and uses of local and global variables.
❖ Describe how to delete a variable from the memory.
❖ Describe and familiarize yourself with basic categories of data types used by Python.
❖ Understand various Python keywords and their functions in a program.
2. PYTHON VARIABLES
Different programming languages have different mechanisms for storing or calling any data.
You can retrieve data directly or indirectly from the computer storage. Languages such as C
and C++ allow the user to access the memory directly.
STUDY NOTE
Whereas, there are some programming languages such as
Python is an object-oriented
Java, Visual Basic, and more that follow such a mechanism that language, thus all variables,
you can only retrieve data through indirect methods. functions, and modules are
treated as objects.
As mentioned in the previous unit as well, Python is an object-oriented language. That means
Python uses objects to store and designate all types of data stored in the memory. What is an
object? It can be defined as an entity of the memory that contains any value or data. In
Python, data is defined either as an object or through its relation with an object.
Identity: Identity can be called the address of the memory where the object is to be stored.
Each identity is unique so that all objects are defined differently.
Type: Type refers to the operations that can be performed on the data that is stored in the
object. In Python, the built-in function type () is used to define the type of the object.
In Python, a variable is defined as the object that can store only one value and have a single
attribute. The interpreter allocates memory to a variable depending upon its data type.
SELF-ASSESSMENT QUESTIONS - 1
1. In Python, all variables are ___________.
4. C and C++ let the user access the memory directly. (True/False)
3. IDENTIFIERS RULES
Identifiers are names defined by the user to denote a variable. In the above example, we
represented the variables by the names ‘a’ and ‘b’. Thus, these are identifiers. Identifiers are
the basic blocks of a Python program. We can use one identifier to represent one single
variable only in a particular program.
You cannot use any word as an identifier. Because of the presence of keywords in Python,
there are certain rules that you will have to follow while naming identifiers. These are
explained below.
These are not rules that you must follow while naming identifiers in Python. However, these
conventions are followed so that a program can be understood by other users as well.
• Class names begin with an uppercase letter whereas all identifiers begin with a
lowercase letter.
• Private identifiers should begin with an underscore (_).
SELF-ASSESSMENT QUESTIONS - 2
6. Keywords can be used as identifiers. (True or False)
7. Python_P23 is a legal identifier. (True / False)
8. _____________ cannot be used in an identifier.
9. Which of the following is a valid identifier name?
A. !identify
B. Identify_1
C. Identify
D. Keyword1
10. __________ Identifiers should begin with an underscore (_).
Now that you have understood the rules that need to be followed while naming an identifier,
here are the ways that you can declare a variable in Python.
Number Variable: Variables that are used to save number values are numeric variables.
Python supports three types of numbers integers, floating-point numbers, and complex
numbers. Take the example provided below to understand how these variables are declared.
num = 20
float_num = 26.90
a = 3 + 4j
String Variable: Strings are a sequence of characters. These are declared under single or
double-quotes. Some examples are given below.
str_1 = ‘Example1’
str_2 = “Example2”
In Python, you do not have to declare the variable before you can assign a value to it. Once
you assign the value, automatically the memory is reserved and the data is stored in the
location. To assign a value to a variable, the equal sign (=) is used.
For example:
a = 10
b = 20
b-a
#Output
10
Here, the operand to the left side of the equal sign is called variable. The operand on the right
side is the data stored in that variable.
Along with numeric values, such as integers, decimals, etc., you can also assign string values
to a variable. The string is a sequence of characters whose sequence cannot be altered. They
are always written inside single inverted commas.
For example:
a = ‘best’
b = ‘friend’
a+b
#Output
‘bestfriend’
Local variables are defined inside a function. A function is a set of commands that are
arranged in a different block than the whole program.
The local variables can only be used inside the function. They have no meaning when called
outside of it.
For example,
def f ():
print (a)
a = 44
a = 33
f ()
print (a)
The above program will fail to show output and give an error instead. This is because the
variable a is local to the function f and cannot be declared or defined outside of it. Here is an
example that will work:
def f ():
a = ‘Python’
print (a)
f ()
Global variables are defined and declared outside a function. You can use and call them
anywhere in the program, even inside a function.
For example,
def f ():
print (a)
a = 64
f ()
Here, the output will be 64. As you can see, the variable 'a' is defined and declared outside
the function and then called inside it. Thus, a is a global variable.
In a huge program where lots of variables are used, it is good practice to delete those which
have served their purpose. This helps in maintaining the memory and free up space in RAM
that can be used to perform and handle other tasks. To delete a variable, the keyword del is
used in Python. the del keyword is used to delete an object in Python and since variables are
objects as well, the keyword can be used in this case as well.
For example:
a = “hello”
del a
print (a)
In the output will, the interpreter will give the error that ‘a’ is not defined.
Activity I
Write a program that works as a calculator. That is, the user provides two values to
the program and it adds, subtracts, multiplies, and divides them.
SELF-ASSESSMENT QUESTIONS - 3
11. ________ keyword is used to delete a variable.
12. ___________ variables can be used only inside the function where they are defined.
13. In Python, declaring the variable before assigning value to it is mandatory.
(True/False)
14. The print function is used to get a value on the output screen. (True/False)
15. Which of the following statement shows multiple assignments?
A. a1, a2, a3 = 8
B. a1 =8, b1 = 8
C. 8 = a1, a2, a3
D. 8 = a1, 8 = a2
5. PYTHON DATATYPES
The data that is stored in the memory can be categorised into various types. Python’s
interpreter assigns space in the memory as per the requirement for the type. Each such type
is called a data type. These data types can perform different operations.
Strings
Strings are text type data types. These are a series of characters that are saved in the memory
in the sequence that they are provided. They are enclosed in either single or double-quotes.
However, while using strings, you should keep in mind that the quote that you have used to
enclose the string cannot be used inside the string. For example, “won’t” is valid. However,
‘won’t’ will give you a syntax error. Here are some examples of string.
str = “Hello”
str_1 = ‘World’
str_2 = “Goodbye!”
In Python, strings are immutable. Hence, once declared and assigned a value, they cannot be
changed. When you assign a new value to it, another object is created.
When you need to save long sentences or paragraphs using string and need to divide the
lines, you will have to use ‘\n’ wherever you need a line break.
Another thing to keep in mind is the use of triple quotes, such as “ “ “ or ‘ ‘ ‘. When using triple
quotes, the new line will not escape the string and will be considered a part of it.
For example:
#Output
To find the length of the string, that is the number of characters used in the string, you can
use the function len (). For example:
Another thing to note is that Python, unlike other programming languages, does not support
character type. There is no way to store a single character other than using string. A single
character can be extracted from a string using slicing. Slicing is
STUDY NOTE
a method through which the index of a character in a string is
used to extract it from the complete string. Here is an example In all programming languages,
the indexing begin from 0 (zero)
to make you understand better. onwards.
str = ‘playing’
print (str [0])
Similarly, you can slice a substring as well. For this, you will have to use a colon in a way that
is shown in the example.
If you do not specify the end of the index, then the range will be up to the end of the string.
For example:
If you want to slice the string from the end, then you will have to use negative indexing. Note
that the negative indexing, that is, from right to left, starts from -1.
For example:
5.1 Numbers
Number data types are used to store numeric values. These are categorised as an immutable
data type. An immutable data type is one in which changing the value of the data type results
in a newly allocated object. You can create a number data type simply by assigning a value to
it. For example:
var = 8
You can change the value stored in var by reassigning another value. For example,
var = 8
var_1 = 6
var = var_1
The output of the program, when you print var will give the value 6.
In Python, the number data type is further divided into four types. These are explained
below.
Integers
These are the most commonly used data types. As defined in mathematics, integers are
numbers ranging from negative to positive, including zero. However, due to constrictions of
memory, in Python, the integers have a range from -2,147,483,648 (-2^31) through
2,147,483,647 (2^31 - 1).
Integers are represented in decimal format, that is, with base 10. However, one can also
define them using the octal and hexadecimal format. If you are using integers in octal or
hexadecimal format, then ensure that you use the prefix 0 and 0x respectively. To specify
that the data type that you are using is an integer, you can use the constructor function
provided in the example below.
For example:
a = int (60)
Long Integers
Long integers are a subtype of integers. These are when you need a number that is greater
than 231 or lesser than -231. Long integers in Python do not have a range and are limited as
per the virtual memory of your computer system. The memory should be large enough to
accommodate and save a long integer. While defining a long integer, you should use the suffix
‘l’ or ‘L’. These can also be defined in the form of decimal, octal, and/or hexadecimal.
Whereas 826353738L, 0X52462354L and -6253902628L are the examples of long integers.
Study Note: To represent long integers, you can use both ‘l’ and ‘L’ but the uppercase ‘L’ is
preferred to avoid confusion of lowercase ‘l’ with ‘1’ (number 1).
Floating point numbers or as commonly known as, float, are numbers with a decimal point.
They have two parts; one is the decimal point part and the other is the exponent part. The
latter is optional and it is mandatory to define it while using a float. They are assigned 8 bytes
of memory. The 52 bits are taken up by mantissa, 11 by the exponent, and the one remixing
bit is for the negative or positive sign.
The exponent part is denoted by an uppercase or lowercase ‘e’ or ‘E’. The sign mentioned
just before ‘e’ is the sign of the exponent. The absence of mention of sign, in any case, will
mean that it is positive.
Some examples of floating-point real numbers are 9.0, 55.8977, -658.99, 52.66-E37, -
88.223e6, etc.
To explicitly define that a variable stores a floating data type, you can use the function float
().
Complex Numbers
Complex numbers in Python are represented by two floating numbers taken in an order of a
+ bj. Here, a represents the real part and b is the imaginary part of the complex number. The
imaginary part is always followed by a lowercase ‘j’ or uppercase ‘J’. (Usually, ‘j’ in lowercase
is used). Some examples of complex numbers are 7 + 4j, -8.9 +5j, -876j, 2e4j, etc.
In some cases, if you want to print or extract only the imaginary or real part of the complex
number, then you can do so by using its data attributes. This has been shown through an
example provided below. A variable can be specified to store a complex number with the
help of the function complex (ij)
You can also get the conjugate of the complex number. If a complex number is defined as a +
ib, then its conjugate will be a – ib. Using the attribute complex.conjugate will print the
conjugate of the complex number in Python.
The sequence data type is another essential data type that is commonly used in Python to
store a series of data together. These are further divided into the following types.
Lists:
Lists work similarly as arrays in C. The one difference is that in lists, you can store values of
different data types together. The items in a list are enclosed inside a square bracket []. Each
value is separated with a comma. The values saved in a list are indexed and ordered. Thus,
when you print a list, the order of the values stored in it does not change.
A list is alterable. You can add items to the list, remove them, delete the list, etc., once it has
been created. You can also store the same values in a list. As they have a different index, the
user will be able to differ between the same data.
For example,
As mentioned, the indexing in the list starts from 0 as well. Thus, in the above example,
element 23 has an index of 0, 56 has 1, and so on.
Here are the methods that you can implement in the list. These are built-in and can be used
using the functions that are listed in the table below.
TABLE 1: METHODS FOR LISTS
Method Use
insert () To add an element to the list at a specified position or index
extend () To add the elements of a list to another list
count () To count the number of elements, present in the list.
append () To add an element at the end of the list
clear () To remove all the elements of the list.
pop () To remove an element from the list at a specific index.
reverse () To reverse the order of the list
sort () To sort the list
Tuples
Tuple functions are similar to lists but with one difference. They are immutable. Values
stored in a list can be changed and altered even after the list has been created. Such a feature
may become an issue in some programs. Thus, in such cases, tuples can be used. Tuples are
enclosed in parentheses with each element separated by a comma. They are ordered as well
and allow repeating a single value.
For example,
tuple1 = (3, 6, 9)
To join two tuples together, you can use the + operator. It is shown in the example below.
tuple1 = (3, 6, 9)
tuple2 = (“a”, “b”, “c”)
tuple3 = tuple1 + tuple2
To add items to the end of the tuple, you can use append () similarly as in a list. Other
functions and methods such as remove (), del, etc., work similarly in both tuples and lists.
5.3 Boolean
Boolean type is used to store one of the two values: true or false. Bool is used to test whether
the result of an expression is true or false. This can be used when you are comparing two
values. If you run such a conditional statement as shown in the example, Python will give
True or False as a result.
The bool () function is used to verify whether a value is true or false. Here, being a true value
means that it is acceptable by Python.
For example,
5.4 Set
Just like lists and tuples, sets are used to store a collection of data. Through set, you can store
multiple items in a single variable. The collection is unordered and unindexed. That is, the
data stored in a set is not saved in a sequence. Hence, you cannot surely say in which order
the sets will appear or get printed. They are immutable as well. That means, once a collection
of data is stored in a set, it cannot be changed. Also, no two sets can have the same value.
You cannot completely change the values stored in a set but you can add new data. And,
example of a set is provided below.
To add new items to a set, you can use the function add (). The method is shown in the
example below.
When you print the set, you will find four values in it, namely, pencil, eraser, ruler, and pen
arranged in random order.
You can add the values of one set to another using the function update (). For example,
#The output will be: pencil, eraser, ruler, protractor, and divider.
The update () function can be used to add any iterable object such as lists, tuples, etc.
The function remove () or discard () can be used to remove a value from the set. For example,
set_1 = {“pencil”, “eraser”, “ruler”}
set_1.remove (“ruler”)
This way, you can remove the value “ruler” from the set. STUDY NOTE
To empty the complete set, you can use the method clear (). Dictionaries were not ordered
in versions Python 3.6 and
earlier. This was updated from
For example, set_1.clear () will remove all the values from the
Python 3.7.
set.
The del keyword will delete the set completely.
For example, del set_1
5.5 Dictionary
Imagine you want to look up a number in the logs of your mobile phone. You do not
remember the number, and surely you would not remember the index at which it is saved.
How will you search for it then? Using the name of the person whose number you are
searching for. The name of the person is called key whereas the phone number will be the
value.
In Python, you can save the pair of key: value together in the form of dictionary data type. In
a dictionary, one key is associated with only one value. It is enclosed in curly braces {} and
each pair of key: value is separated by a comma.
For example:
dict_1 = {
“name”: “Aakash”,
“birthyear”: 1998,
“rollnumber”: 891
}
The values in a dictionary are stored in order. No duplication of the value of a key is allowed
in a dictionary.
Here are the functions and methods that you can use to create, modify, and add to a
dictionary.
TABLE 2: METHODS FOR DICTIONARY
Method Use
clear () To remove all the elements of a dictionary
copy () To return a copy of the dictionary
get () To return the value of a specific key
keys () To get a list of the keys included in a dictionary
update () To update the dictionary by adding key:value pairs
values () To get a list of values present in the dictionary
pop () To remove the element of the specified key
SELF-ASSESSMENT QUESTIONS – 4
16. Tuples are _________ data types and thus, cannot be changed after they are created.
17. ________________ is the data type in which value is stored with a key instead of an
index.
18. ______________ data types store two values, true and false.
19. To signify that a number is a long integer, it is suffixed by ___________.
20. You can remove a value from a set with method _______________
6. PYTHON KEYWORDS
Every programming language has a definite syntax and rules that need to be followed while
witting a program. Python reserves some of the names that cannot be used as programmer-
defined identifiers. These predefined identifiers are called keywords. Here is a list of
keywords used in Python.
• and
• assert
• break
• while
• continue
• class
• del
• elif
• else
• def
• exec
• except
• for
• from
• global
• finally
• if
• is
• lambda
• not
• in
• pass
• or
• raise
• return
• try
• print
• yield
Till now, we have learnt to use global (to define global variables) and print (to print a
variable or value on the output screen).
Activity II
Write a program that combines three or more sequence data types. Try making
different combinations such as lists with tuples, tuples with dictionaries, etc. Note if
you get any syntax error.
SELF-ASSESSMENT QUESTIONS – 5
21. Keywords are predefined identifiers. (True/False)
7. SUMMARY
• An entity that contains data is called an object. Python uses objects to define any data.
An object has three components: an identity, a type, and a value.
• Objects whose value can be changed after creation are called mutable objects. Those
whose values cannot be altered once they are created are called immutable.
• Names given to variables in a programming language are called identifiers.
• Variables reserve memory locations to save data.
• = sign is used to assign value to a variable. In Python, a variable can be assigned a value
without declaring it before.
• Python has various data types divided among categories: number type, sequence type,
text type, mapping type, Boolean type, set type, and binary type.
• The numeric type has four kinds of data types: integers, long integers, floating type real
numbers, and complex numbers.
• Sequence type has two data types, lists and tuples. These are ordered collections of
data. They have indices. Lists are mutable data types whereas tuples are immutable.
• A string is a collection of characters. It is defined by enclosing it in single or double-
quotes.
• Sets are an unordered collection of data that does not have any index.
• Dictionary is used to store data in the pair of key: value.
• The words that cannot be used as programmer-defined identifiers are called keywords.
8. GLOSSARY
Variables: The names that are used to locate the memory of a value.
Global Variables: A variable that is declared outside of a function and can be accessed
anywhere in the program.
Data types: The classification of values stored to perform any task in a Python program.
Float: Numbers that are represented with a decimal point or have a fraction part.
Tuples: They are sequence data type to store a collection of data in order and are immutable.
Boolean: Boolean is a data type that is used to store two values: True or False.
Set: Data type that is used to store multiple values in a single variable.
Dictionary: It is an unordered collection of data arranged in the form of key: value pair.
Keywords: Words reserved in Python that are used to define the syntax and structure of
Python.
Python
Keywords Identifiers
Rules
Python Variables
and Datatypes
Declaring variable,
assigning value,
Numbers multiple assignment,
and deleting a
variable
Sequence
Types
9. CASE STUDY
There is a college admission in an engineering college and thousands of new students have
joined in each course as per the mark obtained in the 12th standard.
These students belonged to different schools with different subject category and have joined
different courses as per the percentage scored. The college has planned to create a database
using Python to segregate the students as per their name, enrolment number, school, city,
and course.
With the help of the python code, they have created a database with all the student
information’s from their personal address to academic details.
So, they're using information forms of lists and tuples for his or her simple management and
understanding. Once the info is made, the school can unleash identity cards for these a
hundred students.
With the help of python they are using data types of lists for their ease of management and
understanding. Once the database is created and finalised, the college will issue the identity
cards for these newly joined students.
Source: bestpy.com
Questions
1) Discuss what changes could the college make in the database to decrease the memory
space required to save the data of each child.
2) Can you recommend using data types other than lists and tuples that can be used by the
college? Give reasons for your answer.
Q1. What are the four types of numeric data types in Python?
Q3. Write a Python program, that returns the sum of all items in a list.
Q4. Write a Python program to get the largest number from a list.
11. ANSWERS
1. Objects
2. True
3. False
4. True
5. A. Value
6. False
7. True
8. Special characters
9. B, C, D. identify_1
10. Private
11. del
12. Local
13. False
14. True
15. A. a1, a2, a3 = 8
16. Immutable
17. Dictionary
18. Boolean
19. L
20. Remove or discard
21. True
22. A. you_and
23. class
24. if
25. clear ()
TERMINAL QUESTIONS
Answer 1: A variable is the name that the user gives so that they can reserve the space in the
computer memory to save a value. Variable name can include any lowercase, uppercase
letters along with digits and underscore.
Answer 2: Variables names should not be keywords and should not include special
characters. Thus, var_1, variable2, etc., can be valid variable names.
Answer 3:
float1 = 8.9
float_2 = 6.9
float_3 = float1 + float_2
print (float_3)
Answer 4: To represent a long integer in Python, the number is followed by ‘l’ or ‘L’. Thus,
882722L is a long integer.
Answer 5: Strings are text type data types. These are a series of characters that are saved in
the memory in the sequence that they are provided. They are enclosed in either single or
double-quotes. However, while using strings, you should keep in mind that the quote that
you have used to enclose the string cannot be used inside the string. For example, “won’t” is
valid. However, ‘won’t’ will give you a syntax error. Here are some examples of string.
str = “Hello”
str_1 = ‘World’
str_2 = “Goodbye!”
Answer 1: In Python, the numeric data types are of the following four types:
Long Integers: These are same as integers but do not have a range and depend upon the size
of the computer memory.
Answer 2:
def string_length(str1):
count = 0
for char in str1:
count += 1
return count
print(string_length(‘AString'))
Answer 3:
def sum_list(items):
total = 0
for num in items:
total += num
return total
numbers = [1, 2, 3, 4, 5]
print(sum_list(numbers))
Answer 4:
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
BOOKS:
E-REFERENCES:
• Python Programming Certification Training Course, last viewed on March 23, 2021,
<https://www.edureka.co/python-programming-certification-training>
• Python Tutorials and Sample Programs, last viewed on March 23, 2021,
<https://www.w3schools.com/python/>
• History of Python, last viewed on March 23, 2021,
<https://en.wikipedia.org/wiki/History_of_Python>
DCA3104
PYTHON PROGRAMMING
Unit 4: Operators 1
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Unit 4
Operators
Table of Contents
8 Identity Operators - 7 23 - 24
9 Operator Precedence 3 8 25 - 26
10 Summary - - 27
11 Glossary 4 - 28 - 29
12 Case study - - 30
13 Terminal Questions - - 31
14 Answer - - 32 - 35
15 Suggested Books and e-References - - 36
Unit 4: Operators 2
DCA3104: Python Programming Manipal University Jaipur (MUJ)
In1.the
INTRODUCTION
previous units, you learned about variables and data types that are used in Python. A
Python program needs these basic elements so that one can define the objects that are
needed to create a program. However, a program cannot only be created with the help of
variables. These variables need to perform some sort of function so that their data can be
manipulated. Only through manipulation, comparison, and identification of variables can we
proceed with Python and code programs that perform a certain function.
All programming languages are essentially computer languages. And the basic function of a
computer language is to compute data. The data entered should be available for performing
basic operations such as addition, subtraction, division, multiplication, and other elementary
mathematical operations.
To perform these operations, Python uses various symbols. These symbols hold
specifmeanings and each has a special function. The symbols indicate to the interpreter what
kind of operation is to be performed on the variables where the symbols are used. These
symbols are known as operators. Operators are used to performing specific mathematical or
logical manipulations.
Operators take one or more values or expressions and provide another value. The value
provided is obtained after operating the previous values as indicated by the operator used.
You can group various operators together in a single expression and the interpretation will
apply them one after another, in a specific order. Various operators can take a different
number of values. Some operators used in Python will need only one value to perform their
function. Some may need two or more values to work. One should take care that they define
the required number of variables while using an operator so that they do not get an error in
their program.
In this unit, we will learn the various operators that are applicable in Python and how some
may differ from the ones that you know from mathematics. With the help of these operators,
you will be able to create basic programs that yield the desired value.
Unit 4: Operators 3
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Unit 4: Operators 4
DCA3104: Python Programming Manipal University Jaipur (MUJ)
2. ARITHMETIC OPERATORS
Python allows the use of various arithmetic operators that are used to perform mathematical
operations such as addition, subtraction, division, multiplication, etc. These operators are
essentially used to perform calculations using the Python programming language. The
operators can be used on numeric data types such as integers, long integers, floating-point
real numbers, complex numbers, and others that can be defined in Python. All these
arithmetic operators are explained in detail below.
2.1. Addition
The addition operator, signified by the symbol ‘+’, is used to add two operands. The syntax
through which it works is shown below. It needs at least two values or operands at its either
side for it to work.
Syntax:
x+y
Example:
a=5
b=8
c=a+b
print (c )
STUDY NOTE
Unit 4: Operators 5
DCA3104: Python Programming Manipal University Jaipur (MUJ)
2.2. Subtraction
The subtraction operator, represented by ‘-‘ also works similar to the addition operator. It
finds the difference between the two operands that are written at its either side.
Syntax:
x-y
Example:
a=5
b=8
c=a-b
print (c )
2.3. Division
The division operator, also known as float division operator to differentiate it from floor
division, is used to divide the first operand from the second. In Python, it is not necessary to
define two floating-point real numbers to get the answer in decimal. You can get the answer
is float even if the integers divided are not perfectly divisible. Thus, in Python, the decimal is
not truncated even if the values used are defined as integers.
Syntax:
x/y
Example:
a=5
b = 20
c=b/a
print (c )
#The output of the program will be 4.
Unit 4: Operators 6
DCA3104: Python Programming Manipal University Jaipur (MUJ)
2.4. Multiplication
The multiplication operator multiples the two operands that are placed on either side. You
can multiply two different data types using this operator.
Syntax:
x*y
Example:
a=5
b=8
c=a*b
print (c )
#The output of the program will be 40.
2.5. Remainder
The modulus operator, represented by ‘%’ is used to find the remainder of a division. It
divides the first operand by the second and returns the value of the remainder obtained after
the division.
Syntax:
x%y
Example:
a = 40
b=9
c=a%b
print (c )
#The output of the program will be 4.
2.6. Exponent
Unit 4: Operators 7
DCA3104: Python Programming Manipal University Jaipur (MUJ)
The exponent operator, also known as the power operator, is STUDY NOTE
used to yield the value when a number is raised to a power. The The operator for floor division
was introduced in version
second operand defined here will be the power. Python 2.2 and onwards
Syntax:
x ** y
This indicates that the interpreter will compute the value of xy.
Example:
a=5
b=2
c = a ** b
print (c )
#The output of the program will be 25.
There are times when you need a division to be in the form of an integer. Python has the
feature of providing a floating result even if the operands used in the division are integers.
However, for some operations, an integer result is needed. Thus, floor division can be used
in such cases.
Syntax:
x // y
Example:
a=7
b = 54
c = b // a
print (c )
#The output of the program will be 7.
Unit 4: Operators 8
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS - 1
Unit 4: Operators 9
DCA3104: Python Programming Manipal University Jaipur (MUJ)
3. COMPARISON OPERATORS
There are situations when you need to compare two quantities and take a decision as per the
result. For example, when you need to find whether a person is eligible to cast a vote or not,
you will need to compare their ages to the standard, that is, 18 years. If their age is more than
18, then they can cast a vote. However, if the opposite is true, then the person will not be
allowed. Such decisions need to be made in various scenarios and situations.
To get a result in these cases, you can use comparison operators. Comparison operators, or,
also known as relational operators, are used to compare two values. The yield a value in the
terms of True or False. That means, while comparing two properties, the relation between
them can either be true or false. The following operators are used in Python to establish a
relation between given operands.
Syntax:
x>y
Example:
a=5
b=8
print (a > b)
#The output of the program will be False.
The operator used to show that the first operator is lesser than the second operator.
Syntax:
x<y
Unit 4: Operators 10
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Example:
a=5
b=8
print (a < b)
#The output of the program will be True.
Equal to
This operator with the symbol “==” is used to compare two operands and find that they are
both equal. Note that the equal to “==” operator is different from the assigning operator “=”.
Syntax:
x == y
Example:
a=5
b=8
c=a+b
print (c == a)
#The output of the program will be False.
Not Equal to
The operator not equal to, represented by “!=” is used to find whether two operands are
equal or not.
Syntax:
x != y
Example:
a=5
b=8
c=a+b
print (c != a)
Unit 4: Operators 11
DCA3104: Python Programming Manipal University Jaipur (MUJ)
The operator yields the result true when the first operand is either greater than or equal to
the second operand.
Syntax:
x >= y
Example:
a=5
b=8
print (a >= b)
#The output of the program will be False.
The operator has the symbol “<=” and is used to yield a value by comparing two values and
finding whether the first operand is less than or equal to the second operand.
Syntax:
x <= y
Example:
a=5
b=8
print (a <= b)
#The output of the program will be True.
Unit 4: Operators 12
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS - 2
6. Which operator means less than or equal to?
A. >=
B. >
C. <
D. <=
10. Relational operators can yield values in the form of True or False. (True or
False)
Unit 4: Operators 13
DCA3104: Python Programming Manipal University Jaipur (MUJ)
4. ASSIGNMENT OPERATORS
Assignment operators are used to assigning the desired value to a variable. The most
commonly used assignment operator is one that we have been using in most of the programs
till now, that is “=”. The operator directly stores the value in the data address assigned. In
addition to this, there are various other assignment operators in Python.
These are shorthand operators that are used to shorten an expression. These are explained
in the table below.
Activity I
Draw a flowchart and algorithm of a program that works performs various arithmetic
operators that are applicable in Python.
Unit 4: Operators 14
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS - 3
11. The shorthand operator used for the expression a = a + 1 is _____________.
12. ________ is the assignment operator most commonly used in Python or any
programming language.
13. The operator used to find the product of a number with the number itself or its
multiples is ________.
14. __________ operator performs AND on the operands and assigns the value to the
first operand written on the left.
A. 9
B. 13
C. 6
D. None of the above.
Unit 4: Operators 15
DCA3104: Python Programming Manipal University Jaipur (MUJ)
5. BITWISE OPERATORS
In Python, bitwise operators are used to performing calculations and manipulations bitwise.
The integers are converted into bits or in binary form and the required functions are
performed bit by bit, from left to right. These operators only work on integers and cannot be
performed on floats and another form of data types.
The table below details the description of each bitwise operator used in Python along with
its syntax.
Unit 4: Operators 16
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS - 4
16. ___________ is the symbol of the bitwise left shift operator.
17. _____________is the symbol for the bitwise XOR operator.
18. In Bitwise operator, the integer if first converted in ___________ form.
19. ____________ provides the result similar to multiplying the number with a power of
two.
20. The operator that provides the compliment of the number provided is
_____________.
Unit 4: Operators 17
DCA3104: Python Programming Manipal University Jaipur (MUJ)
6. LOGICAL OPERATORS
Logical operators work similarly to Boolean operators. In Python, there are three logical
operators, and, or, and not. Logical AND, represented by “and” yields a true value if both the
operands are true. Logical OR, written as “or” is true when one of the operands is true.
The logical NOT, or, as written in Python “not” give false if the operand is true and vice versa.
The operands written on either side can be relational expressions. Such an arrangement of
expressions is called logical expressions. A logical expression can yield only True or False
values.
Syntax:
a and b
a or b
not a
Example:
a = True
b = False
print (a and b)
print (a or b)
print (not a)
#The output of the example code given above will look like this:
False
True
False
Unit 4: Operators 18
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS - 5
21. The output of the following program will be
a = True
b = False
print (not a)
A. True
B. False
C. a
D. b
23. ________ operator yields true when both the operands are true.
24. ___________ operator gives the opposite of the operated operand.
25. NAND is a logical operator used in Python. (True or False)
Unit 4: Operators 19
DCA3104: Python Programming Manipal University Jaipur (MUJ)
7. MEMBERSHIP OPERATORS
There are times when you need to test whether a value is present in the given list or other
sequence data type. For this, Python provides membership operators. There are two
membership operators under membership.
in operator: The operator yields true when the given value is found in the sequence.
Syntax:
x in y
not in operator: The operator is used when the given value is not present in the tested
sequence.
Syntax:
x not in y
Example:
a=3
y = {3, 4, ‘a’, ‘b’, 5}
print (a in y)
#The output of the code will be True.
There is another special type of operator called the dot operator. The symbol “.”, is used to
access the instance variables and methods of class objects.
Syntax:
student.age
Let's look at some examples:
Accessing Object Attributes
You can use the dot operator to access the attributes or properties of an object. For instance,
if you have an object of a class, you can use the dot operator to access the class's attributes.
class MyClass:
def __init__(self):
Unit 4: Operators 20
DCA3104: Python Programming Manipal University Jaipur (MUJ)
In this example, my_object.my_attribute uses the dot operator to access the my_attribute
attribute of the my_object object.
Calling Methods
Here, my_object.my_method() uses the dot operator to call the my_method method of the
my_object object.
Accessing Modules
Python's dot operator is also used to access functions, classes, or variables defined in a
module.
import math
print(math.pi) # Output: 3.141592653589793
print(math.sqrt(16)) # Output: 4.0
In this example, math.pi and math.sqrt use the dot operator to access the pi constant and the
sqrt function in the math module.
Unit 4: Operators 21
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS – 6
26. When a value is present in a sequence, then the “not in operator” will provide
_________ result.
27. What will be the output of the code that is given below?
x = “I am a Python Code”
print (‘o’ in x)
A. True
B. False
C. Python
D. None of the above
28. Membership operators can be operated on dictionary data types. (True or
False)
29. Membership operators can provide only _________ and _________ as output.
30. ___________ is the symbol of the dot operator.
Unit 4: Operators 22
DCA3104: Python Programming Manipal University Jaipur (MUJ)
8. IDENTITY OPERATORS
Identity operators check whether the identity of two operators is the same or not. They do
this by checking the address where the data is stored in the memory. There are two such
identity operators. These are explained below.
is operator: It yields the value as true when the operands are identical and have the same
memory address.
Syntax:
x is b
is not operator: It provides the result as true when the operands are not identical and have
different memory locations.
Syntax:
x is not b
Example:
a=6
b=6
print (a is b)
print (a is not b)
#The output of this will be as follows: True False
Unit 4: Operators 23
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS – 7
31. What will be the output of the following program?
a = [1, 2, 3]
b = [1, 2, 3]
print (a is b)
A. True
B. False
C. [1, 2, 3]
D. None of the above
32. is not operator cannot operate on strings. (True or False)
33. Identity of two lists can never be same. (True or False)
Unit 4: Operators 24
DCA3104: Python Programming Manipal University Jaipur (MUJ)
9. OPERATOR PRECEDENCE
The combination of values, variables, functions, and operators is called an expression. The
interpreter in Python can test and interpret whether an expression is valid or not. When an
expression includes more than one operator, then the interpreter operators them as per a
precedence level.
An arithmetic expression in Python when written without any parenthesis will be calculated
from left to right. All the arithmetic operators into different levels as per their order of
precedence. It is through the order of precedence of an operator that its priority is decided.
The precedence of operators in Python is listed in the table below.
Operator Name
() Parentheses
** Exponent
+x, -x, ~x Unary plus, unary minus, and Bitwise NOT
*, /, //, % Multiplication, division, floor division,
modulus
+, - Addition and subtraction
<<, >> Bitwise left and right shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, <, >, >=, <=, is, is not, in, in not Comparison operators, identity operators,
membership operators
not Logical NOT
and Logical AND
or Logical OR
Unit 4: Operators 25
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Note that some operators have equal precedence. In such cases, they are evaluated from left
to right. This is called operator associativity.
SELF-ASSESSMENT QUESTIONS – 8
34. Which is the order of precedence in Python?
a) Parentheses
b) Exponential
c) Multiplication
d) Division
e) Addition
f) Subtraction
A. a, b, c, d, e, f
B. b, a, c, d, e, f
C. b, a, d, c, e, f
D. a, b, c, d, f, e
35. Which of the following have the same precedence level?
A. Addition and subtraction
B. Multiplication, division, and addition
C. Multiplication, division, addition, and subtraction
D. Addition and multiplication
36. Which of the following has the highest precedence?
A. Exponential
B. Addition
C. Multiplication
D. Parentheses
Unit 4: Operators 26
DCA3104: Python Programming Manipal University Jaipur (MUJ)
10. SUMMARY
• Operators in Python are used to perform operations on the values and variables.
• There are standard symbols for each operator used to perform logical and arithmetic
operations.
• Arithmetic operations are used to perform mathematical operations such as addition,
subtraction, division, and multiplication.
• Floor division gives an integer answer no matter the data type of the operands.
• Comparison operators compare the given two operands to give true and false as results.
• Logical operators are used to performing Boolean operations such as AND, NOT, and
OR.
• Bitwise operators are used to performing various actions on bits. Integers are
converted into binary form before being operated by bitwise operators.
• Assignment variables are used to assign values to the variables. Most commonly, “=” is
used in Python.
• Assignment variables can help shorten the code by providing a shorthand of
expressions.
• Identity operators are used to checking whether two variables belong to the same
memory location.
• Membership operators are used to testing whether a variable is present in the given
sequence data type or not.
• The dot operator is used to access a data member present in a class.
• The operators used in Python are operated based on their priority level in order of
precedence. It is known as PEDMAS in short.
• PEDMAS means Parentheses, Exponent, Division, Multiplication, Addition, and
Subtraction.
• When operators are used without parentheses in an expression, then they are
evaluated from left to right if they have the same precedence level. This is called the
associativity of operators.
Unit 4: Operators 27
DCA3104: Python Programming Manipal University Jaipur (MUJ)
11. GLOSSARY
• Operand: The part of the computer instruction that defines the data which is to be
manipulated or operated on.
• Operators: The special symbols in Python that carry out arithmetic, logical, or
relational computation.
• Logical expression: It is a statement that can be either true or false.
• Truth table: It is a table that shows the truth-value of a logical expression.
• Conditional operator: Also known as a ternary operator, the conditional operator is
used to evaluate a condition applied to one or more Boolean expressions.
• Increment operator(+=) It is a unary operator that adds one from the operand.
• Decrement operator(-=): The unary operator that subtracts one from the operand.
• Dot operator: It is a member operator that is used to access the member of a class.
• Operator precedence: The order of operations that dictates which procedures need
to be performed first.
• Associativity: It determines how the operators of the same precedence level will be
processed in the absence of parentheses.
• Identity operators: Operator used to compare two or more objects that have the same
memory location.
Unit 4: Operators 28
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Bitwise
operators
Assignment
operators
Logical
operators
Operators
Membership
Comparison and Identity
operators operators
Operator
Arithmetic Precedence
Operators
Unit 4: Operators 29
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Each professor can enter the marks obtained by a student on the website and the final result
will be automatically calculated. The final result will include the total marks obtained by a
student, their percentage, average score, rank, and grade.
The result should also be able to take in values when a student was unable to attend an exam.
A team has been created to code a program that can perform all these functions while also
creating a merit list in the order of highest to lowest marks.
The program should take in the values for each student from different professors and
compute the percentage and other mathematical data.
The program should be capable of deciding whether a student has passed or not as per the
percentage and grade obtained.
Imagine yourself as a part of the team that has been tasked to code the program. Based on
this situation, answer the following questions.
Source: bestpy.com
Questions
1. Which operators will be used to create the program and calculate all the required values?
Discuss their types.
2. Discuss how the code can be simplified to ensure that all users can understand and use
it.
Unit 4: Operators 30
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Q1. Write a Python program that accepts the value of the radius of a circle and gives the area
of the circle in output.
Q2. Write a Python program that accepts the value of an integer and computes the value of n
+ nn + nnn.
Q3. Write a Python program that calculates the number of days between two given dates.
Q4. Write a Python program that gives the volume of a sphere with the radius entered by the
user.
Q5. Write a Python program that adds three numbers entered by the user and then returns
a value that is three times their sum.
Q1. Write a Python program that finds the difference between the number input by the user
and 90. If the number is greater than 90, then the program will yield a value that is double
the absolute difference.
Q2. Write a Python program that takes in the value of the base and height of a triangle and
calculates its area.
Q3. Write a Python program that calculates the lowest common multiple of the given two
positive integers.
Q5. Write a Python program that calculates the amount received on a principal amount with
the given rate of interest applicable over the given number of years.
Unit 4: Operators 31
DCA3104: Python Programming Manipal University Jaipur (MUJ)
14. ANSWERS
1. B. x**y
2. //
3. Integer
4. %
5. True
6. D. <=
7. B. false
8. A. true
9. !=
10. True
11. +=
12. =
13. *=
14. &=
15. C. 6
16. <<
17. ^
18. Binary
19. Bitwise left shift
20. Bitwise NOR
21. B. false
22. A. True
23. AND
24. NOT
25. False
26. True
27. A. True
28. True
Unit 4: Operators 32
DCA3104: Python Programming Manipal University Jaipur (MUJ)
TERMINAL QUESTIONS
Answer 1:
from math import pi
r = float (input ("Input the radius of the circle : "))
print ("The area of the circle with radius " + str(r) + " is: " + str (pi * r**2))
Answer 2:
a = int (input ("Input an integer : "))
n1 = int (“%s" % a )
n2 = int (“%s%s" % (a,a) )
n3 = int (“%s%s%s" % (a,a,a) )
print (n1+n2+n3)
Answer 3:
from datetime import date
f_date = date (2014, 7, 2)
l_date = date (2014, 7, 11)
delta = l_date - f_date
print(delta.days)
Unit 4: Operators 33
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Answer 4:
pi = 3.1415926535897931
r= float (input (“Enter the value of radius of the sphere: ”))
V= 4.0/3.0*pi* r**3
print ('The volume of the sphere is: ',V)
Answer 5:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))
sum_of_numbers = num1 + num2 + num3
result = 3 * sum_of_numbers
print("The result is:", result)
Answer 1:
def difference(n):
if n <= 90:
return 90 - n
else:
return (n - 90) * 2
print (difference (22))
print (difference (14))
Answer 2:
b = int (input ("Input the base : "))
h = int (input ("Input the height : "))
area = b*h/2
print ("area = ", area)
Answer 3:
def lcm (x, y):
if x > y:
Unit 4: Operators 34
DCA3104: Python Programming Manipal University Jaipur (MUJ)
z=x
else:
z=y
while (True):
if ((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print (lcm (4, 6))
print (lcm (15, 17))
Answer 4:
x, y = 4, 3
a=x+y
b=x-y
result = a * a * b
print ("({} + {}) ^ 2) = {}".format (x, y, result))
Answer 5:
amt = 10000
int = 3.5
years = 7
future_value = amt*((1+(0.01*int)) ** years)
print(round(future_value,2))
Unit 4: Operators 35
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Books:
E-References:
• Python Programming Certification Training Course, last viewed on March 23, 2021<
https://www.edureka.co/python-programming-certification-training >
• Python Tutorials and Sample Programs, last viewed on March 23, 2021
< https://www.w3schools.com/python/ >
• History of Python, last viewed on March 23, 2021
< https://en.wikipedia.org/wiki/History_of_Python >
Unit 4: Operators 36
DCA3104: Python Programming Manipal University Jaipur (MUJ)
DCA3104
PYTHON PROGRAMMING
Unit 5
Branching and Looping in Python
Table of Contents
SL Fig No / SAQ /
Topic Page No
No Table / Graph Activity
1 Introduction - -
3-4
1.1 Learning Objectives - -
2 Python IF-Else Conditions - 1
5-6
2.1 Indentation in Python - -
3 The If-Else Statement 1, 2 2, I
7 - 12
3.1 The El-if Statement - -
4 Python Loops 3, 3, II
4.1 For Loop - -
13 - 16
4.1.1 Using Sequence - -
4.1.2 Using Range() - -
5 Nested For Loop in Python - 4, III
17 - 20
5.1 Using Else Statement in Loop - -
6 While Loop 4 5, IV 21 - 23
7 Break and Continue
- 6, V
1. INTRODUCTION
In the previous units, we learned about what a programming language is and how it is used
to communicate with a computer. Programming languages are used to create programs that
control the actions of a computer and to implement algorithms efficiently.
You were also introduced to the Python language, which is a general-purpose programming
language. Python is used to create simple algorithms, perform mathematical and engineering
calculations, and handle large amounts of data. Unlike other programming languages, Python
has a relatively simple syntax that allows a programmer to create programs with a few lines
of code.
Python's simple and easy-to-understand structure has made it popular among beginner and
professionals. Its versatile nature has made Python the most used programming language
for the internet's most popular websites.
In this unit, you will be introduced to different types of conditional statements, types of loops
and all the conditions, variables, and statements used in them.
Conditional statements are lines of code that help execute different instructions based on
certain conditions. These statements assist a programmer to direct the flow of code
execution and control how an application interacts with a user. Conditional statements are
also known as Branching. When a set condition is checked and met, the program may branch
off in one way or another and proceed in the relevant direction.
Loops, on the other hand, are sets of code that are repeated as long as a condition is valid or
a sequence is completed.
As you may recall, keywords are reserved words used in Python that cannot be assigned any
value. In this unit, you will use the if, else, pass, etc., keywords. You will also use different
operators like arithmetic operators, assignment operators, logical operators, comparison
operators, etc., in loops and branching.
❖ Use the Python IF, If-Else, ELIF, and ELSE statements to write and read structured
programs.
❖ Implement simple loop structures using the FOR and WHILE Loops to read and write
programs.
❖ Use nested and chained conditional statements.
❖ Construct algorithms that use conditional and loop structures.
Conditional expressions in Python are logical expressions where logical operators compare,
evaluate, or check if the input (operand) meets the conditions and returns 'True'. The block
of code gets executed based on this. If the expression returns a 'False', the block does not
execute, and the cursor moves on to the next line of code.
Most programming languages require that their conditional blocks are enclosed in
parentheses, curly brackets etc. In Python, this is not required. However, a semi-colon (':')
must follow the conditional statement in the same line, and the following statements should
have a proper indentation.
SELF-ASSESSMENT QUESTIONS - 1
1. Conditional statements are also known as ________________.
2. According to the Python guidelines, the indentation of the body is equal to
____________.
3. In Python, indentation is represented as _____________.
4. Python provides a unique set of operators for coding. [True/False]
5. No programming language requires their block of code to be enclosed in
brackets. [True/False]
6. '!=' returns a 'False' value if one variable is equal to the other. [True/False]
7. All conditional statements should end with a:
a) colon (:) b) semi-colon (;)
c) comma (,) c) period (.)
'If' is the simplest conditional statement in Python. When the specified condition of the 'if'
statement is met: the block of code or compound statement under it is executed. The 'if'
statement has the following structure in Python:
if < conditional expression > :
... < block >
Source: geekforgeeks.org
Example:
T = float(input(’What is the water temperature? ’))
if T > 24:
print(’Water is safe!’)
print(’Jump in!’)
# First line after if part
In the above example, Python will ask the user to input the water
temperature. If the temperature is more than 24, the condition is STUDY NOTE
'True', and the print commands are executed. If the temperature is '#' represents a comment
in the code. The comment
less than 24, the condition is 'False'. The program moves to the statements are not
executed but are only
code after the if block without executing anything. In other words, written to understand the
the program gives no response when the temperature is below 24. code properly.
However, as a programmer, you will want your application to perform a set of steps when a
condition is met (True statement) and another set of steps when it is not (False statement).
We use the if...Else statement to execute different blocks of code based on the True or False
criteria.
The if...Else structure is as follows:
if < conditional expression > :
... < block >
else :
... < block >
Example:
We can use the same example of temperature mentioned above:
T = float(input(’What is the water temperature? ’))
if T > 24:
print(’Water is safe!’)
print(’Jump in!’)
else:
print('Better not go in!')
# First line after if-else
When the if condition evaluates to 'False', the print command in the else part is executed
automatically. It is only logical because if the first condition is false, then the second one is
true.
The branching execution of the elif (short for else if) statement
STUDY NOTE
is based on several alternatives. It is also known as the
There is no limit to the
number of elif statements if...elif...else statement and involves using many elif statements.
that can be used in one
Python evaluates all the elif statements in succession and only
block of code.
executes the block under the first elif expression. In other
words, it does not matter if there are more than one 'True'
conditions. Python stops at the first 'True' value, executes it, and then exits the if...elif...else
structure.
In case no elif statement returns the "True" value, the else block is executed. In most cases,
however, the else expression is not required and can be omitted. It is up to the programme
to determine whether or not an else expression is required in the code.
A. Chained Conditionals
Using elif in the chained conditional expressions is quite straight forward as mentioned
above and has the following syntax:
if < conditional expression > :
... < block >
elif < conditional expression > :
... < block >
elif < conditional expression > :
... < block >
elif < conditional expression >:
... < block >
elif < conditional expression > :
... < block >
:
:
:
else :
... < block >
Example:
if choice == 'a':
... print("You chose 'a'.")
elif choice == 'b':
... print("You chose 'b'.")
elif choice == 'c':
... print("You chose 'c'.")
else:
... print("Invalid choice.")
Each condition is checked in the given order. If the second elif statement returns 'True', "You
chose 'b'" is printed and the cursor exits the chained structure to move to the next code line.
B. Nested Conditionals
The nested format has an outer conditional with two branches. The second branch has an if
expression with two branches of its own, and so on. Although this format has good structure
with indentation, it becomes very difficult to read nested expressions in the long run. Hence,
it is better to avoid this when you can.
Source: thecrazyprogrammer.com
You may encounter situations where nothing has to be done if a condition returns 'True'.
Since Python does not permit an empty block in the code, we use the "pass" statement. It is
written as:
if < conditional expression > :
... pass # don’t do anything
Composite Expressions
To combine two conditional expressions, we use the logical operators: "and", "or", or both to
make a composite conditional expression.
Example:
if < conditional expression > and < conditional expression > :
... < block >
OR
Activity I
Write a Python program that prompts the user for a string and calculates the number
of letters and digits separately. Use the if…elif…else statement for this program.
SELF-ASSESSMENT QUESTIONS - 2
8. A block of code should always have an else statement. [True/False]
9. The pass statement is executed when the given condition is satisfied.
[True/False]
10. Any number of elif statements can be used in a code. [True/False]
11. Two expressions are concatenated to form a _____________________.
12. elif stands for ___________.
13. if x >= 0 :
print ('Your number is a whole number')
The above code will always give a:
a) positive integer b) negative integer
c) any number d) cannot say
4. PYTHON LOOPS
Source: teststeststests.com
The for loop executes each statement in a sequence and is hence used with Python's
iterables that include: a string, list, tuple, dictionary and set. Unlike in the while loop, you do
not have to set a looping variable in the for loop. The structure of for loop in Python is:
for < var > in < iterable > :
... < statement >
... < statement >
As looping is controlled by the number of items in the iterable, infinite loops cannot likely be
formed. However, the variable can accidentally be manipulated in the body of the loop,
resulting in an infinite loop. Hence, programmers should check, vet and recheck the code
before execution.
As mentioned above, loops use a set of items called iterables to execute statements. A
Sequence is a generic term used to refer to iterables. Python has many types of sequences;
however, the most common types are:
• Lists - These are the most versatile sequences. The elements of a list can be any object
that can be added, reassigned or removed.
• Tuples - These sequences are similar to lists. However, they cannot be changed.
• Strings - These are special sequences that can only store characters and have a unique
notation. Apart from characters, sequence operators can also be stored as a string.
Sequence Operators
The range function is used to repeat or loop a block of code a given number of times. We
know that Python is a zero-indexed programming language. Hence, by default, it returns a
sequence of elements starting from zero index. The index sees an increment by 1 till the set
range is reached.
The range() function is used as:
for < variable > in range( < number > ) :
... < block >
The loop will run from a 0 value variable to a value equal to the number specified minus one.
Example:
for x in range( 5 ) :
... < block >
The loop will run from x=0 through to x=4 with increments of 1.
The starting value of a range() be change from the default 0:
for x in range( 2, 5 ) :
... < block >
The loop will run from x=2 through to x=4 with increments of 1.
The increment values can also be changed as follows:
for x in range( 5, 16, 2 ) :
... < block >
The loop will run from x=5 through to x=15 with increments of 2.
Activity II
Write a Python program that asks the users for a number and give the number’s
multiplication table a output. The table should be from 1 to 20. You can use the range
function in the for loop.
SELF-ASSESSMENT QUESTIONS - 3
14. _______________ is a set of statements that are repeatedly executed.
15. The looping expressions used in Python are ____________ and ___________.
16. Sequences are also referred to as _____________.
17. String sequences store numbers. [True/False]
18. It is impossible to form infinite loops in Python. [True/False]
19. The Operation seq[i] will return the ith item in a sequence. [True/False]
20. In Python, the index numbers start from ___ by default.
a) 1 b) 0 c) any number d) cannot say
21. The following code will give you values of x from:
for x in range( 1, 9 ) :
... < block >
a) 1 to 9 b) 1 to 7
c) 1 to 8 d) 0 to 8
The program evaluates the outer loop first, executing the first iteration. The iteration triggers
the next (nested) loop to completion. The program returns to the top of the outer loop,
completes the second iteration, and triggers the nested loop again. The loop continues till
the sequence is complete or there is a disruption in the process.
Let's take a look at an example to understand how we can nest for loops in Python:
num_list = [1, 2, 3]
alpha_list = ['a', 'b', 'c']
for number in num_list:
... print(number)
... for letter in alpha_list:
...print(letter)
#Output
1
a
b
c
2
a
b
c
3
a
b
c
From the above output, we can see that the program executed the first iteration to print '1',
goes to the nested loop to print 'a, b, c' consecutively. Once the inner loop is complete, it goes
back to print '2' in the outer loop, and again prints 'a, b, c' by triggering the inner loop, so on.
We got the above output because the loop iteration ended normally and the else statement
was executed.
Let's see what happens when the loop does not end normally:
for currentLetter in 'Hi everyone!':
print ('The current letter is', currentLetter)
if currentLetter == 'r':
break
else:
print ('All letters were printed.')
#Output:
>>>
The current letter is H
The current letter is i
The current letter is
The for loop terminated as soon as the letter 'r' was encountered due to the if condition
provided. The break statement disrupts the code abruptly. Hence, the else statement did not
execute as the loop did not complete normally.
Activity III
Write a Python program that finds the numbers between 1000 and 2700, that are
divisible by 7 and are also multiples of 5. Use a nested for loop.
SELF-ASSESSMENT QUESTIONS - 4
22. A nested loop is triggered only after the outer loop is executed. [True/False]
23. The else expression is executed even if there is a disruption in the code.
[True/False]
24. The else statement can be used in a loop even without the ________ statement.
25. _______ character is used to break a long line of code.
26. The output of the following code is:
for i in range(10):
if i == 5:
break
else:
print(i)
else:
print("Here")
a) 0 1 2 3 4 b) 1 2 3 4 c) 0 1 2 3 d) 1 2 3
6. WHILE LOOP
The while loop is used to repeatedly execute a block of code as long as the given condition is
satisfied. The while loop has the following syntax:
Source: codestown.com
The expression controls the loop execution and involves looping variable(s) with logical
operations. The looping expression sets the condition based on which the loop will continue
to run or terminate.
While executing an assignment statement in the while loop, the right- STUDY NOTE
hand side of the expression is evaluated first. The evaluated result is In Python, any non-zero
value is viewed as ‘True’
then assigned to the variable. In loop expressions, the variable is while ‘None’ and 0 are
interpreted as ‘False’.
evaluated and repeatedly updated while the given condition is 'True',
otherwise it is terminated.
The statement x+=1 adds 1 to x in each loop iteration. This ensures that the loop does not
become an endless loop.
Activity IV
Write a program that finds the Fibonacci series between 0 to 50. Every next number in
the Fibonacci sequence is found by add the previous two numbers
SELF-ASSESSMENT QUESTIONS - 5
27. The output of the following code is __________.
i=1
while True:
if i%3 == 0:
break
print(i)
i+=1
28. The output of the following code is:
i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
a) 0 1 2 0 b) 0 1 2 c) 1 2 3 d) 0 1 2 3 4
29. In loops, the value on the right-hand side is evaluated first and if it meets
the condition, it is assigned to the variable. [True/False].
30. ___________ are used with operators to make loop expressions.
31. The while loop executes the loop expression when the variable evaluates
to __________.
Example:
word = input ('Type a word that is less than 5 characters long: ')
letterNumber = 1
for i in word:
print ('Letter', letterNumber, 'is', i)
letterNumber+=1
if letterNumber > 5:
print('The word you have entered is more than 5 characters long!')
break
The above code will print each letter of the word you have entered. However, if the character
count exceeds 5, the break statement in the code will terminate the code after 5 characters.
Letter 1 is A
Letter 2 is v
Letter 3 is a
Letter 4 is l
Letter 5 is a
The word you have entered is more than 5 characters long!
Similar to the break statement, the continue suddenly stops the STUDY NOTE
running iteration. However, instead of terminating the loop, it Both the break and
continue statements are
goes back to the loop expression for re-evaluation before used to terminate the
continuing. If the re-evaluated results do not comply with the current iteration or loop
without checking the test
expression, the loop terminates and the program moves to the expression
next line after the body of the loop. If the expression is still valid,
the program continues with the next iteration.
Example:
for i in range(6,15):
if i==9:
continue
print (i)
#Output:
>>>
6
7
8
10
11
12
13
14
>>>
The program prints all numbers between 6 to 15 except 9. When the variable i is equal to 9,
the if statement is executed and the continue statement under it will force the program to
skip the print statement before it moves to the next iterable.
Activity V
Create a Python code that prints all numbers between 0 to 30, except 10 and 15. Use
the continue statement in the code.
SELF-ASSESSMENT QUESTIONS - 6
8. SUMMARY
• Branching or conditional statements are used to set the parameter for the execution of
a code.
• Conditional expressions are logical and follow operations similar to those in
mathematics such as equal to (==), less than (<), greater than (>), less than or equal to
(<=), greater then or equal to (>=), not equal (!=), etc.
• The if...else expression is used to execute an action in the case of both 'True' and 'False'.
One block of code is executed if the condition is ‘True’ and another block is executed if
it is ‘False’.
• The conditional statements may be executed in a sequential manner (chained
conditionals) or different conditional may be nested within a conditional statement
(nested conditionals).
• The pass statement is used instead of an empty block in Python. If the condition is ‘True’
and a pass statement is given, no action is executed.
• The composite conditional expression can be constructed using "and" and "or". The
‘and’ operator returns ‘True’ if both conditions are met, while the ‘or’ operator returns
‘True’ if even one condition is satisfied.
• Python gives programmers the freedom to nest loops and statements in any
combinations without any restrictions.
• Looping keeps executing a code block until the conditions are evaluated as 'False'.
• The looping expression sets the condition for which the loop will continue to run.
Unlike the while loop, the for loop does not require a looping variable for execution.
• Sequences are collections of items or elements that can be iterated over using a loop.
Lists, tuples, strings, etc., are called sequences. We can perform tasks on sequences
using operators or functions like ‘+’, ‘*’, seq[i], etc.
• The range() function sets a limit or range using which a loop returns values. Range()
uses indexing to retrieve items.
• Python indexing starts from ‘0’.
• In nested loops, the else statement can be used even without the if statement.
• The break statement is used to abruptly exit the code, while the continue statement is
used to go back and re-evaluate the conditional expression.
9. GLOSSARY
Branching and
looping in
Python
Indentation
in Python
While Loop
Using Else
Statement
The If-Else
in Loop
Statement
Python
Loops
The Elif
Statement
For
Loop
Source: https://bit.ly/3dbKa1Z
A new accounting firm saw a rise in their clientele only a few months after their
establishment. They realized that the traditional method of maintaining client accounts
through MS Excel would no longer be feasible. In order to not loose their clientele, the firm
decided to use Python programming language to automate data tasks.
They used Python loops to iterate over the data in lists and data frames. This helped them to
automatically calculate and convert the values in the lists and database. The system set up
by the firm successfully retrieved client data, filtered it and organized it for analysis. The
conditions for this were set using the for and while loops.
Python provides a simple and clean coding syntax and the accounting system proved to be
quite affective for performing data tasks in a less amount of time.
Discussion Questions
4) Write a code that accepts string input and calculates the number of character and digits.
5) Write a nested loop statement that will prompt the user to input a number and print
the range of numbers from 1 to the input number.
6) Write a program that will prompt the user to input a number and give a sum of all the
natural numbers up to the input number.
7) Using the if...else condition, write a program that will let people below 18 and above 60
know they cannot ride a rollercoaster.
8) The following code will give the output:
for val in "star":
if val == "a":
break
print(val)
print("The end")
11. ANSWERS
1) Branching
2) Four spaces
3) ‘…’
4) False
5) False
6) True
7) a) colon (:).
8) False
9) True
10)True
11)composite conditional expression
12)else if
13)a) Positive integer
14)loop
15)for, while
16)iterators
17)False
18)False
19)True
20)b) 0. Python is a zero-index language
21)c) 1 to 8.
22)True
23)False
24)if
25)‘\n’
26)a) 0 1 2 3 4
27)error! Explanation: There should be no space between = and +
28)b) 0 1 2. else statement is not executed as loop breaks.
29)True
30)looping variables
31)“True”
32)break
33)continue
34)True
35)False
36)c) none of the above. “True” and “False” are reserved words in Python.
B. TERMINAL QUESTIONS
1) Answer Output:
s
t
r
n
g
e
r
The end
All the characters up till 'a' are printed. If the string is 'a', the block is not executed. This
is because the continue statement is executed when 'val' is 'a'. The program then moves
to the next iterable, that is, 'n' and continues the loop. Hence, we see all characters,
except 'a' are printed.
2) The statements used to manipulate or change the execution flow of a program are
known as control flow statements. A typical Python code sequentially executes a
program (from top to bottom) but some statements in Python can break this order of
execution. They include loops, branching, etc.
3) Loop interruption statements let users terminate a loop iteration without letting the
loop run its full course. There are two loop interruption statements:
break statement: This statement terminates the loop completely and shifts the control
flow directly outside the loop.
continue statement: This statement terminates only the current loop iteration and
shifts the control flow to the next iteration of the loop.
4) Code answer:
s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
5) Code Answer:
x = int(input('Enter a number: '))
while x != 0:
for y in range (1, x):
print (y)
y+=1
x = int(input('Enter a number: '))
6) Code Answer:
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n
while i <= n:
sum = sum + i
i = i+1 # update counter
# print the sum
print("The sum is", sum)
7) Code Answer:
x = int(input('Enter your age: '))
if x < 19 or x > 60:
print('You are too young or too old to ride!')
else:
print('Welcome, you are of the right age!')
If the user enters an age between 19 and 60, the program will print "Welcome, you are of the
right age". On the other hand, if the age is below 19 or above 60, the program will tell the
user they are too young or too old.
8) Output:
s
t
The end
In this program, we iterate through the "star" sequence. We check if the letter is 'a', then
we break from the loop. Hence, we see in our output that the letters till 'a' (s and t) get
printed. After that, the loop terminates.
9) Code Answer:
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [5, 3, 7, 2, 6, 9, 4, 8, 1]
E-REFERENCES
<https://geek-university.com/python/the-if-statement/>
DCA3104
PYTHON PROGRAMMING
Unit 6
OOPS Through Python
Table of Contents
SL Fig No / SAQ /
Topic Page No
No Table / Graph Activity
1 Introduction - -
3-4
1.1 Learning Objectives - -
2 Class in Python - 1 5-6
3 Object in Python - 2 7-8
4 Object References - 3 9 - 10
5 Object identity - 4,I 11 - 12
6 Creating Methods in Python - 5, II 13 - 16
7 Implementation of Encapsulation - 6
17 - 19
8 Implementation of Polymorphism - 7 20 - 22
9 Implementation of Inheritance 1 8 23 - 26
10 Summary - - 27 - 28
11 Glossary - - 28
12 Case Study - - 29
13 Terminal Questions - - 30
14 Answer Keys - - 31 - 36
15 Suggested Books and e-References - - 37
1. INTRODUCTION
In previous units, you have learned about the basic programming and syntax of Python. You
can now make simple programs that can do basic arithmetic operations and build upon those
basics. However, most real-life problems cannot be solved using functions and modules
alone; what you need is an object. Python is an object-oriented language, though using OOP
is not necessary as you start learning the language.
OOP is an essential part of a programming language that lets us manage the complexities we
face in real-life situations. With each year, we are surpassing our technological management,
including more complex features in our machine. Take software applications as an example.
Back in time, these used to be very straightforward and served only one purpose. However,
with time, their functionality has grown. Now, you expect that an application will have
various features in it. While programming, these features need to be managed, so their
complexities do not affect the user's experience.
Like to understand the working of a machine, it has to be broken into smaller and more
manageable parts; similarly, it is better to take basic components during programming and
then build the program from down. Objects are the basic blocks of programming that enable
a programmer to handle real-life situations. They act as building blocks that come together
to create a building. Before diving into OOP through Python, you first need to understand the
components of OOP and how it works.
• Objects: Everything that we see around ourselves is an object. A book, a table, a fan,
everything is an object that is further classified and given a name for our better
understanding. In software development and programming language, this concept of
object is used to simplify understanding the problem at hand. Any entity that has some
sort of physical characteristics is classified as an object. For a programming language, an
object has a definite state, shows a unique identity, and displays a behaviour.
• Classes: If each object in the world is an object, then there will be millions of objects that
one has to consider. However, the management of such a large number can become
complex and inefficient. Thus, as in human life, we have classified similar objects in one
group. In a programming language, we classify the objects that show the same behaviour
or have the same state in a class.
• Benefits of OOP: Object-oriented programming has the foremost benefit of being
essential to consider and compute real-life situations. It lets the programmer
conceptualize the real-world problem in terms of a programming language.Through
OOP, you can reuse the class you once created. It reduces redundancy and increases the
efficiency of programming and readability. You do not have to change the entire
algorithm if you want to change one program component. OOP gives you the freedom to
make changes while leaving the other parts unaffected.
2. CLASS IN PYTHON
To understand the term class, take an analogy like cats, jaguars, tigers, cheetah, and more.
All these animals come under the cat family. On the other hand, dogs, wolves, foxes, and such
come under the dog family. You can consider them subclasses
that come under the larger class of animals. It is the concept of STUDY NOTE
classes that are considered in Python as well. Classes in Python are
usually names using
singulars with the first
In Python, a class is defined as an object constructor. It acts as a letter in uppercase.
To create a class in Python, you will use the class keyword The name of the class immediately
follows the statement. An example is shown below.
Example:
class ClassName:
a=6
After class creation, an associated new class object is created quickly. This class object has
the same name as the class. With the class object's help, you can access different class
attributes and instantiate new objects. As you can see, the class does not inherit anything
from any other class. Later in this chapter, we will study the inheritance property.
If you create a class with no attribute, the interpreter will give an error. Thus, you either have
to put an attribute inside the class or write the keyword “pass”. This keyword tells the
interpreter that it can move on to the next command line.
Also, note that everything inside the class is indented. In Python, indentation is an essential
part of the syntax. Being indented means that the command or code is associated with the
class. In the future, you will notice, indentation is used in the case of "if", "for", and other such
cases.
SELF-ASSESSMENT QUESTIONS - 1
1. A class name can be any word written in any syntax as desired by the user.
[True/False]
4. To indicate that a code belongs to a class defined above it, one has to use
___________ in Python.
3. OBJECT IN PYTHON
We have covered the fact that everything in Python is treated as an object. Variables,
functions, lists, tuples, dictionaries, sets, etc., every entity defined
STUDY NOTE
in Python becomes objects. When you define an integer, it belongs
To access the class
to an integer class, just like a lion belongs to the animal class. function, we use the name
of the object along with the
Every object in Python has its own class. In a class, you define data dot operator.
structures that can hold data members. These data members, such
as variables and constructs, are accessed by an object of the class.
In order to check the type of user-defined classes and all objects, the function
isinstance(object, type) is used.
Example Program: Here is a code that displays the name and grade of the student.
class Student:
name = “Ishan”
grade = 8
stu1 = Student()
print(stu1.name)
print(stu1.grade)
Ishan
• Here, the object is stu1, and with the dot operator, we accessed the student's name and
grade.
SELF-ASSESSMENT QUESTIONS - 2
6. _____________ is used to access the class function with an object.
4. OBJECT REFERENCES
Imagine an arrow. It is your object, your variable name that you created in the memory. The
arrow, once released, will find a place to lodge, which will be its memory location. In Python's
terms, whenever you proceed with the variable assignment, that is, assigning a value to a
variable, what you are doing is forming an equation. You create the left side of the equation
by declaring a variable. This variable gets saved in the memory
STUDY NOTE
with the address, say, 1800. Thus, the address 1800 refers to the
Using the built-in function
variables that you created. In Python, everything, including the type() can return the type
of the object.
variable, is an object; therefore, this 1800 becomes your object
reference that the variable's name will represent.
The object reference is the indication of the memory location of the object placement. Take
an example below to understand the concept deeper.
Example:
a=5
b=6
c=8
a=b
b=c
print (a, b)
6, 8
• The value of a, as assigned to the user, should be 5. Similarly, the value of b should be 6.
However, when you wrote 'a = b' and 'b = c', what you essentially did is commanded that
a is b, and b is c. Thus, the location of variable 'a' became the location of variable 'b', and
the location of 'c' became that of 'b'. Changing the object reference also changed the value
stored in that variable.
An object in Python exists as long as it has an object reference. If the number of object
references drops to one, then that object is no longer accessible. Thus, we say that the lifetime
of the object that began with its creation ended. In the future, we can store other data in this
empty memory.
SELF-ASSESSMENT QUESTIONS - 3
11. The location in the memory where the object is stored is:
A. Reference
B. Object reference
C. All of the above
D. None of the above
5. OBJECT IDENTITY
Example:
n = 60
id(n)
7811108
Activity I
Create a program that declares two objects. Assign the object reference of one object
to the other (for example, if you have objects a and b, you can simply write a = b).
Compare the object identity of the objects. Now, create two objects that store the same
value. What are their object identities? Discuss the results.
SELF-ASSESSMENT QUESTIONS - 4
16. In Python no two objects have same identity. [True/False]
17. The function id() in Python, returns integer value representing:
A. Identity of the object
B. the location in the memory where the object has been stored.
C. All of the above
D. None of the above
18. When there is no ___________ for an object, only then its identity becomes available
to be assigned to any other object.
Before you begin to create Python methods, you will first have to grasp the concept of
function. A function is a set of commands or parameters which are closed under a
parenthesis. They perform a specific action and return a value.
STUDY NOTE
Functions are great tools to simplify and shorten the length of the
A Python method is
code. If you find that you have to perform an action repeatedly in a similar to functions but
it is applicable on
program, then instead of writing the code again and again, all you objects.
have to do is write it once in a function. Now, whenever you need
to perform a function, you will have to call the function. It will return the value so that your
code works impeccably and has a few codes as possible.
Python has various built-in functions that perform the functions that are commonly used
across various programs. Take print () for an example. It displays the result that you want to
print on the output screen. How does it do it? The commands required to display a result
have already been coded in the print () function. Hence, a user does not have to write it again
in every program. Similarly, functions like len() and many others are available in the library
of Python.
Users can also define and create functions in Python. You will have to use the keywords “def”
to define a function. You can add parameters and commands inside the function and then call
the function anywhere in the program.
• The code creates a function named "hello". It prints the string "hello" with the name
entered by the user. Notice that the second line of command is indented to tell the
interpreter that it is associated with the function. You can call this function in the
program, as is shown below.
Now that you have understood the concept of functions let's move on to methods. You must
have come across the word methods in the previous units, especially while defining various
data types such as lists, sets, tuples, dictionaries, etc. For example, by using the method
append (), to the end of a list you can append an object. Or using the method remove ()
deletes an object from the sequence data types. As you have already used methods in
programs, you must have a vague idea about the term's meaning.
A method is a process through which you represent a class's behaviour the objects associated
with the class. In Python, a method works similarly as a function. However, a method must
be called on an object.
You can refer to previous units to get the list of methods along with their description in
Python.
A method needs to be created inside a class. The example provided below explains the syntax
needed to be used to create a method.
Example:
class Hello:
def __init__(self):
pass
print(f"Hello, {name}")
return name
myname = Hello()
myname.printhello('Ayush')
• Here, the method defined is printhello (). It has parameters and returns a value.
What is __init__ ()? If you are familiar with other object-oriented languages such as C++, you
might know that a special function is used to initiate the class attributes. This function is
called constructor and usually has the same name as the class. In Python, the method __init__
is used for the same purpose. The parameter in this is self, as it calls to the class itself. The
keyword “pass” is used as the method cannot be kept empty.
Activity II
Find the error in the code given below.
class Bird:
def __init__ (self, name, age)
self.name = name
self.age = age
def sing (self, song):
return “sings”. format (self, name, song)
def chirps(self):
return “is chirping”. format (self, name)
sparrow = Bird ( “Sparrow”, 3)
print(sparrow.sing (“Happy”))
print(sparrow.chirps())
SELF-ASSESSMENT QUESTIONS - 5
19. A method can be created anywhere in the program. [True/False]
20. Functions are a set of commands that have parameters and return a value.
[True/False]
21. To define a method, you need to use the keyword def. [True or False]
7. IMPLEMENTATION OF ENCAPSULATION
Through encapsulation, you can wrap data and methods in one unit. Thus, other users cannot
access the elements of the unit or change them. The method is beneficial to avoid any
accidental changes in the data. Encapsulation allows change in an object's variable only
through the object's method. Such variables are called private variables.
Encapsulation is easily exemplified by class. It encases all of the elements as well as the data.
such as member functions, variables, etc., and does not allow any changes.
Protected members
The members of a class are not available to access from the exterior of the class. Accessibility
is permitted within the class or its subclasses only. In Python, a data member is protected by
prefixing it with a single underscore "_".
Private members
Private members are secured, but these cannot be accessed even by the super or parent
class's subclasses, and a double underscore "__" is used as a prefix to inform the interpreter
that a data member is private. Note, remember that the init() method is preceded and
followed by a double underscore.
Here is a sample code that signifies protected and private members in a Python program.
STUDY NOTE
A class is a programming
construct that contains all
of the variables and
methods specified within
it.
Sample code:
class MyClass:
def __init__(self):
class ChildClass(MyClass):
def __init__(self):
super().__init__()
print(self._b)
obj1 = MyClass()
print(obj1.a)
Try to run the program and find the output that you get.
SELF-ASSESSMENT QUESTIONS - 6
24. Private members of a class cannot be accessed. [True or False]
8. IMPLEMENTATION OF POLYMORPHISM
Assume a situation where you have to calculate the price of an item. The price is stored in
the form of a list, a tuple, or even a dictionary. Depending upon the type of instance, you will
have to put conditions in your program to retrieve the value.
You can let the object decide the operation and carry it out by itself in such a situation. The
object can retrieve its value on its own. You will not have to make any corrections or change
the data type again. It is possible through polymorphism.
Similarly, functions like len(), del, etc., can be used with various data types. When using the
function len(), you do not know whether the data type whose length you can calculate is an
integer or a string. The function will return the length of the data type, regardless of its
nature. Here is an example.
Example:
When it comes to classes, polymorphism comes especially handy as, through it, Python
permits the usage of methods of the same name across various classes in a program. You can
also define polymorphic functions. The functions will perform the action for which the
commands are provided without knowing the object's data type or other attributes.
Example:
return x + y + z
15
Similarly, through polymorphism, you can apply two distinct class types in the same manner.
Another essential function of polymorphism is overriding. When a child class obtains a
parent class's properties through inheritance, it is practical to alter a method in the inherited
child class. The process involves the reimplementation of the method in child class. This
method is called method overriding. All methods of the parent class, except private methods,
can be overridden through polymorphism. However, the opposite of this is not possible. You
cannot override a method in the subclass through the super or parent class.
SELF-ASSESSMENT QUESTIONS - 7
29. Why is polymorphism used?
A. There is less code to write.
B. Program code takes less space
C. The programmer can think on an abstract level
D. The code will be elegant and easy to maintain
30. Overriding means changing the behaviour of methods of derived class methods in
the parent class. [True or False]
31. It is possible to override a ___________ private method.
9. IMPLEMENTATION OF INHERITANCE
STUDY NOTE
Inheritance is transitive in
nature. That is, if a subclass
inherits the properties from the
base class, then all the
subclasses of that subclass will
also inherit those properties.
Here is a sample code to show
you how inheritance works.
class Employee:
self.name = name
self.ID = None
def getName(self):
return self.name
def getID(self):
return self.ID
def checkemployee(self):
return False
class Department(Employee):
def checkemployee(self):
return True
emp = Employee("Ayush")
emp.ID = "145"
For the child class to identify its parent class, it needs to mention the parent class in its
definition. This method is subclassing or calling the constructor of the parent class. The
syntax followed for this is as follows.
Types of Inheritance
The types of inheritance are divided based on the number of child and parent classes.
• Single Inheritance: The attributes of a single parent class are passed on to the child
class.
• Multiple Inheritance: When a derived class gets its properties to form more than one
superclass, it is called multiple inheritances. The subclass derives all the properties of
the parent classes.
• Multilevel Inheritance: When another generation of classes further inherits the
parent and child class features, it is classed as a multilevel inheritance.
• Hierarchical Inheritance: When more than one derived class receive the properties
from one individual parent class, then it is the case of hierarchical inheritance.
• Hybrid Inheritance: Hybrid inheritance occurs when various types of inheritances are
used together.
SELF-ASSESSMENT QUESTIONS - 8
32. Which of the following is a wrong statement about inheritance in Python?
A. The inheriting class is referred as a subclass.
B. Private members from a class can be acquired.
C. Inheritance is a feature of OOP
D. Protected members of a class can be inherited.
35. When a subclass is defined in Python that serves a subtype, the keyword used
is a subtype. [True or False]
36. _____________ is when different types of inheritance are used at the same time.
Class in Implementation
OOPS Through
Python Python of Inheritance
Object in
Python
Implementation
of Polymorphism
Object
References
Implementation
Object Identity
of Encapsulation
Creating Methods
in Python
10. SUMMARY
• When two or more inheritances are used at the same time, it is hybrid inheritance.
11. GLOSSARY
Object: It is a unique data structure that is defined with the help of its class. It includes data
members as well as methods.
Class: It's an object prototype that's been defined by the user. It specifies the class's
attributes.
Data member: It is a class variable that carries the data related to a class and its objects.
Class variable: It is a variable that all the instances in the class share. They are defined
outside of the methods of class but exist inside the class.
Instance variable: The variable that belongs to the class's instance where it is defined.
Function overloading: When one function is assigned with more than one behaviour.
Inheritance: The method of transferring the attributes of one class to other classes that are
obtained from it.
Encapsulation: It enables the user to use an object without the knowledge of how it is
constructed.
Polymorphism: It enables the user to call an object's method without the knowledge of the
class or type of the object.
A University is planning to convert its library and all its resources to be available online. The
system of borrowing books is to be automated for a smoother function of the library. The
system created should be such that the students can access the library's database even if they
are not on the campus.
For this, a team has been set up. The team has to create light, well-structured, and easy to
navigate software for the users. They have been given a time limit to convert one section of
the library online through this software.
The team decided to keep the application code as short as possible to increase the project's
efficiency. The application is created such that if one enters the unique code given to each
book, then all other information regarding the book will appear, including its title, author,
publication house, and publishing year. The application should add books to the database,
view a book, and delete a book from the records.
Source-
Discussion Questions:
1. What classes should be defined to create the application? Can you find the inherited
classes and their objects?
2. Write and execute the code required for the application.
Q1. Develop a program to construct a class and display the namespace of the class.
Q2. Write a program to form an instance of a class and print the instance's namespace.
Q4. Create a class in Python names Student. Print the type of class.
Q2. Formulate a Python program that derives all the unique subsets of the given set. Take
the input set to be [2,7,8].
Q3. Formulate a Python program that discloses the cube of a given number using pow(x,n).
Q4. Formulate a Python program to exhibit the class name of an object as output.
14. ANSWERS
1. False
2. Class
3. Docstring
4. Indentation
5. A, B, C
6. Dot operator
7. Instantiation
8. B. classname.attribute
9. True
10. False
11. Object reference
12. no longer valid
13. a
14. False
15. True
16. True
17. C. All of the above
18. B. Object reference
19. False
20. True
21. True
22. True
23. A and C
24. False
25. True
26. True
27. Double underscore
28. A. Encapsulation
TERMINAL QUESTIONS
Answer 1:
class dis_solution:
if sset:
return [current]
print(name)
Answer 2:
class MyClass:
self.x = x
self.y = y
print(instance.__dict__)
Answer 3:
def square(x):
return x*x
print(square(4))
Answer 4:
class Student:
pass
print(type(Student))
Answer 5: Inheritance is the process through which the attributes of one class are moved to
other classes constructed from it. One class can derive its properties from one or multiple
parent classes. Similarly, one superclass can have one of the multiple subclasses.
roman = OrderDict()
def romam_num(num)”
for r in roman.keys():
x, y = divmod(num, r)
yield roman[r] * x
num -= (r * x)
if num <= 0:
break
num = 30
print write_roman(num)
Answer 2:
class SetSolution:
if sset:
return [current]
print(SetSolution().sub_sets([2, 7, 8]))
Answer 3:
class pow_solution:
return x
if x==-1:
if n%2 ==0:
return 1
else:
return -1
if n==0:
return 1
if n<0:
return 1/self.pow(x,-n)
val = self.pow(x,n//2)
if n%2 ==0:
return val*val
return val*val*x
print(pow_solution().pow(2, 3));
Answer 4:
import itertools
x = itertools.cycle('WXYZ')
print(type(x).__name__)
Answer 5:
Provision for controlling access to methods and variables is available and applicable in an
object-oriented python program. This provision eliminates the modification of data by
accident, and this process is known as encapsulation. One can define a class's data members
as private or protected to ensure that other users cannot access the data. It is also beneficial
to protect the data or data members against any accidental changes.
BOOKS:
• Dusty Phillips (2010) Python 3 Object Oriented Programming. 1st edn. Packt Publishing
Limited.
• Allen Downey, Jeffrey Elkner, Chris Meyers (2015) Learning with Python. 1st edn.
Dreamtech Press.
• Booch (2009) Object-Oriented Analysis and Design with Applications, 3rd edn. Pearson
Education India.
• Sebastian Raschka (2017) Python Machine Learning. 2nd edn. Packt Publishing.
REFERENCES:
<https://realpython.com/python3-object-oriented-programming/#what-is-object-
oriented-programming-oop>
<https://www.programiz.com/python-programming/object-oriented-programming>
<https://www.youtube.com/playlist?list=PLQ1vEpscLn-vrc-5Nynkr7AEfko0k4tEr>
DCA3104
PYTHON PROGRAMMING
Unit 7
String Handling
Table of Contents
SL Fig No / SAQ /
Topic Page No
No Table / Graph Activity
1 Introduction - -
4-5
1.1 Learning Objectives - -
2 Concepts of Strings - 1 6-7
3 Creating a String - 2,I 8- 9
4 Indexing and Splitting - 3, II 10 - 12
5 Reassigning Strings - 4 13 - 15
6 Deleting the Strings - 5 16 - 17
7 String Operators - 6 18 - 23
8 String Formatting - 7
24 - 25
8.1 format() method - -
9 Different String methods 1 8 , III
9.1 capitalize() - -
9.2 casefold() - -
9.3 center(width ,fillchar) - -
9.4 count(string,begin,end) - - 26 - 31
9.5 join(seq) - -
9.6 len(string) - -
9.7 lower() - -
9.8 partition() - -
10 Summary - - 32
11 Glossary - - 33
12 Case Study - - 34 - 35
13 Terminal Questions - - 36
14 Answer Keys - - 37 - 39
15 Suggested Books and e-References - - 40
1. INTRODUCTION
In the previous section, we have discussed OOP (Object-Oriented Programming) in Python.
Python is a dynamic, versatile, and open-source programming language. You can read a
python program very easily. It can run on different software available, which makes it a
portable language. Different methods and approaches can be implemented in Python to solve
a problem. Object-Oriented Programming methods solve the problem by creating objects
and classes. This method makes programming easy to understand. You can even share the
classes that you have created.
Now in this unit, we are going to tell you further about this STUDY NOTE
programming language. String handling is a crucial topic in any
Unlike C++ and Java,
programming language. As we already know that Python has a Python Programming does
not utilize braces to delimit
large standard library that contains numerous codes, modules, codes. Indentation is
compulsory in Python. If
and functions that makes it easy to code in this language. Python you select to import it from
the ______ further
has a built-in class called ‘str’ for strings that consist of several package_____, it provides
you a witty error.
features. In pythons, strings can be closed by either single quotes
or double-quotes. Most people commonly use single quotes for their convenience. However,
use single quotes for closing your string when it contains double quotes in it. Similarly, use
double quotes to contain your string when your string contains a single quote in it to give a
clear code (e.g., "I don't need it").
A string can be a word or a sentence. It can also contain multiple lines, but a backlash should
succeed each line to avoid a new line. Multiple line strings can be depicted by ''' or """. Strings
in Python are known as immutable because they cannot be changed once they are created.
New strings can be created using old strings. For instance, to make a string 'Hi there', we can
add up two strings ('Hi' + 'there') to produce the desired string.
2. CONCEPTS OF STRINGS
As we already know, Python's strings are immutable, so once they are formed, they cannot
be changed. However, there are different ways to create new strings from the older ones
discussed in separate sections one by one. These methods and functions are pre-built in
Python's standard library to carry out these processes of creating new strings. We also have
a wide range of operators to develop new strings explained in the coming sections.
We can access the characters in the strings using the square brackets [] syntax. Zero-based
indexing is used in Python, therefore for the string 'good', s[1] is o. Python displays an error
message if the index is out of bound.
SELF-ASSESSMENT QUESTIONS - 1
1. The data or text enclosed with single quote, double-quote or triple quote is
known as _________.
3. CREATING A STRING
As said before, strings in Python can be made by enclosing a sequence STUDY NOTE
of characters in single quotes, double quotes, or triple quotes
Triple quotes can be
depending upon the string. E.g. used when multiple
lines are present in the
string.
Activity I
Suppose you are a software engineer working in a company. You need to develop some
programs based on Python Programming and explain the importance of Python
programming to your team. Start with creating a program that prints a string
containing a single quote. For example, a string which says, (Hey there, I haven’t seen
you in a very long time). Try with all the types of quotes, and then discuss the results
with your team.
SELF-ASSESSMENT QUESTIONS - 2
6. Strings are the sequence of __________.
Indexing means acknowledging an element within the string by its position from either left
or right. Indexing can be done by either positive or negative numbers depending upon the
position from where it is starting. We use the standard [] syntax to specify the position of an
element within the string. In contrast, splitting or slicing means to get only a part of a subset
from the present string. [ ] is known as the slicing operator. We have presented examples
below for you to understand this concept more clearly.
use negative numbers. For the last element in the string 'football',
str[-1] will be used. Similarly, for str[-6], the returned value will be 'o'. This is useful for
programmers when they want to access a character or element from the string; they need
not find the string's length, just use the indexing from the right.
Note that if you try to use the index out of range or use a number that is not an integer, Python
raises an IndexError. E.g., for the string 'football', str[8] will cause Python to raise an error
because there is no eighth element, and str[2.5] will also raise an error, and Python will ask
the programmer to use an integer and nothing else.
Let's come to the splitting of strings. As discussed already, splitting refers to accessing a
subset or smaller string from the given string. The syntax for this operation takes the form
of string[start:stop], where start refers to the index of the first character that is to be included
and stop refers to the index of the last character or element to which the slicing operator has
to take without including the last character.
Let's take an example to understand more clearly. Take a string 'COMPUTER' and index it
from both the left and right sides.
0 1 2 3 4 5 6 7
C O M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1
Both the forward and reverse indices are given for the string 'COMPUTER'. So for str[1:4],
the value will be 'OMP'. You can see in this particular example that we have not included the
fourth value; the stop only indicates where the computer has to stop. Let’s look at more
examples.
For the negative splitting, see that we have started from -1 and stopped at -8. So for str[-5:-
1], the string value will be 'PUTE'. Note that whenever we split or slice the string, the element
that has to be included in the slice will have to be at the right side of the start value and
similarly to the left of the stop. So if you try for str[-1:-5], no values will be included in the
sliced string because there is nothing to be included to the right of index -2.
Activity II
Create two non-empty strings with n number of elements. Modify the program to
rotate all the letters in the string by:
1. Left by two digits
2. Right by two digits
Discuss the approach used and the output of the program.
SELF-ASSESSMENT QUESTIONS - 3
11. Getting a subset of the string is called _______.
12. The method to refer each element in a string by its position is called _____.
13. Indexing can be done only from the left side. [True/False]
14. You can reverse a string by using the slice operator. [True/False]
5. REASSIGNING STRINGS
The strings in Python are immutable; that is, they cannot be changed once created. But there
are ways to update it. The easiest thing you can do is assign a completely different value to
the existing string. This is most useful as in Python; item assignment is not supported in
strings. Let's take a look at the following example.
#creating a string
str = ‘PYTHON’
str[1] = ‘y’
print(str)
For this output, Python will show an error because the item assignment is not valid in Python.
Now reassign the existing string to a completely new value that you want in the output.
Python programming language also has an in-built function in its standard library where you
can use it to replace the string's value with what you want and however many times you
want. The syntax for the replace() function is shown below.
STUDY NOTE
string.replace(old, new, count)
Python allows you to
allocate the same
The old parameter refers to the old string that has to be replaced. value in many
variables in one
The new parameter refers to the new string that has to replace the statement. It will also
allow you to allocate
old one. The count parameter shows how many times the old one values to many
variables at once.
has to be replaced with the new one. Look at the example shown below:
We hope that the above example has made the concept of reassigning strings clear to you.
SELF-ASSESSMENT QUESTIONS - 4
16. To replace the value within the string, you can use this function. _________.
18. The strings in Python can be changed once they are created. [True/False]
The strings cannot be changed once they are created, so for convenience, if a string is no
longer required, you can delete that string with the del keyword. Take a look at the example
given below:
error because the elements cannot be deleted from We cannot change or delete the character
directly from an existing string, but we can
the string. Let's take a look at another example. take the help of slicing and the operators to
get the desired result.
Again, the output will show that there is no such string named str because we have deleted
it already before the printing function.
SELF-ASSESSMENT QUESTIONS - 5
21. The keyword used to delete a string is _____________.
7. STRING OPERATORS
Strings operators in Python refer to the different types of string operations applied to code’s
string type of variables. When used in any code, these operators make it much easier to write
and read. Pythons allow several operators that are presented below:
Concatenation refers to adding or joining two or more strings with the "+" operator's help.
Take a look at the code given below.
A string can be repeated any number of times by using the "*" operator. Look at the code
given below to understand the operator clearly.
#repetition of strings
str = ‘hey’
print(str*2)
print(str*3)
print(str*4)
#The output is as follows.
heyhey
heyheyhey
heyheyheyhey
To write a code more easily and keep the code clear, programmers The placeholders can be
empty or contain names
often use this operator to assign the string to a variable. To get a or numbers following
the values that have to
more clear picture, go through the following examples. be inserted.
We have already discussed the splitting or slicing of strings in the previous sections. This
operator is used to take out the elements from the given string using the slicing operator.
Equals to is presented by "==" and not equals to is presented by "!=". when two strings are
compared using the equals to the operator, then the boolean value TRUE is returned if both
the strings compare the same and FALSE is returned if they are not same. Similarly, when
two strings are compared using the not equals to the operator, then the boolean value TRUE
is returned if they are not the same, and FALSE is returned if they are the same.
These two operators are used to see whether a particular element is present in the string or
not. For instance, 'x' in a string returns the boolean value TRUE if x is indeed present in the
string and FALSE if not. Similarly, 'x' not in a string returns the boolean value TRUE if x is not
present in the string and FALSE if it is present.
This operator is very useful when you have to add a non-allowed element in a string. The
non-allowed operator is preceded by the backslash or the escape operator "\".
SELF-ASSESSMENT QUESTIONS - 6
26. The joining of two strings is called ___________.
27. Escape sequence character is used when you want to insert a non-allowed
character. [True/False]
28. Assignment of the strings is done using the operator “==”. [True/False]
8. STRING FORMATTING
Python uses C-style string formatting to create new formatted strings. As we have already
learned the old way of string formatting using the “%” operator, we can now move forward
to a new and different string formatting method.
str.format(val1, val2…)
In this, the val1 and val2 represent the values to be formatted and added in the string. It can
represent the element’s position that has to be formatted and can be from any data type. The
placeholders {} are present in the string in which the values have to be inserted. Look at the
given code below to understand in a better way.
SELF-ASSESSMENT QUESTIONS - 7
31. This method is used when we have to create formatted strings in Python __________.
Python programming language has a wide range of built-in methods that can be used
whenever necessary on the code. A string object calls the methods according to their
properties.
9.1. capitalize()
This python method is called when you have to convert the first character of the string to a
capital letter or uppercase. The syntax of this method is given below:
str.capitalize()
No parameters are used in this method. In case a number is present as the first character of
the string, then no change happens when this method is called. Look through the given code:
9.2. casefold()
You can call this method to convert the strings into lower STUDY NOTE
case. The syntax of this method is given below. All the methods, when used in a
code, return new values. No change
in the original string is done.
str.casefold()
No parameters are used in this method. Look through the given code:
This method is used to return a centred string. The syntax of this method is given below.
str.center(width ,fillchar)
In this, the width is the required length according to the programmer's input and the fillchar
(optional) is the character used to fill in space. The default option for fillchar is space, that is
" ".Look through the given code in which “0” is used as the padding character:
9.4. count(string,begin,end)
This method is called when you want the number of times a particular element is used or
occurred in the string. The syntax of this method is given below.
str.count(string,begin,end)
The string here is the one in which we have to count the values. Begin specifies the position
to start from, but the default is set to the start. End refers to position till we want to search,
and the default value for the end is the last of the string. Look through the given code:
9.5.join(seq)
This method is called when you have to join or concatenate all the iterables together. There
must be a string given to separate the iterables. The syntax of this method is given below.
str.join(seq)
In this,seq refers to the sequence in which the strings have to be joined. For example:
9.6. Len(String)
In Python, whenever we have to find out the length of the string, we call this len() method to
know the value. The syntax of this method is given below.
len(string)
Look through the given code:
#using len(str)method
str = ‘I love Python’
print(len(str))
#The output is as follows.
13
9.7. Lower()
This method is called when you have to convert the whole string into a lower case. The syntax
of this method is given below.
str.lower()
No parameters are used in this method. Look through the given code:
9.8. partition()
This method is called to divide the string into three parts and gives a tuple in return. The
syntax of this method is given below.
str.partition()
The value that is inserted in the bracket decides the splitting point. The first part is before
the given value, the second part is the value itself, and the third part is after the value. Look
through the given code:
Activity III
Create a string in a program. Make only half of the letters in the string in uppercase.
Let the other half letters remain in the lowercase. Create this program using at least
two different approaches. Discuss the results.
SELF-ASSESSMENT QUESTIONS - 8
36. This method returns a centered string _____________.
38. lower() converts the first character of the string into lower case. [True/False]
39. partition() divides the string into as many as parts you want. [True/False]
Concepts of Creating a
Strings String
Deleting
the Strings Indexing
String Handling
and
Splitting
String
Operators Reassigning
Strings
String
Formatting
Different String
methods
format()
method partition()
capitalize()
lower()
casefold
() len(string)
center Count(string
(width, , begin, end)
fillchar)
join(seq)
10. SUMMARY
11. GLOSSARY
PARSING:
The parsing process is a standardized process. The foremost idea is to first translate the
input characters into a more conceptual representation like name: x, integer: 7.
Theconceptual characters are referred to as tokens. The tokenization process is completely
defined in the language reference.
For example:
indent
name: f
left-paren
name: x
right-paren
Then the tokens are collected into statements, class definitions, expressions, function
definitions, etc.
Source: alumini.media.mit.edu
DISCUSSION QUESTIONS:
1. From the above study, determine how the Python interpreter performs?
2. As a software programmer, explain the Python fundamentals in Data Science and do
you think Python Programming is beneficial in technological companies?
Q1. Write a program to find the length of the string "python" without using the len function.
Q2. Write a program to check if the letter 'o' is present in the word 'World'.
Q3. Specify the type of value that will be returned by the centre (width, fillchar) method in
Python.
Q1. In the given string “BANANA”, count the occurrences of all characters within a string.
14. ANSWERS
1. String
2. Empty String
3. True
4. False
5. D. All of the above
6. ASCII codes
7. Array data structure
8. False
9. True
10. A and C
11. Splitting
12. Indexing
13. False
14. True
15. C. str[-2:-4]
16. replace()
17. TRUE
18. FALSE
19. FALSE
20. B. x = “HELLO”
21. Del
22. FALSE
23. FALSE
24. FALSE
25. A. del str
26. Concatenation
27. TRUE
28. FALSE
29. TRUE
30. D. %g
31. format()
32. FALSE
33. FALSE
34. TRUE
35. B. string.format(val1, val2…….)
36. center(width ,fillchar)
37. TRUE
38. FALSE
39. FALSE
40. D. str.count(string,begin,end)
TERMINAL QUESTIONS
Answer 1:
s = "python"
count = 0
for char in s:
count += 1
print("Length of the string is:", count)
Answer 2:
str = “World”
print(“o” in str)
Answer 3: The method centre( ) returns centred in a string of width specified by the
programmer. The padding will be done by the character specified by the programmer.
Answer 5: In Python, once the strings are created, then they cannot be changed. The new
operation has to be performed, or methods are called to change something and form new
strings.
Answer 1:
str = “BANANA”
print(str.count(“B”))
print(str.count(“A”))
print(str.count(“N”))
Answer 2:
str1 = str1[::-1]
print("Reversed String is:", str1)
Answer 3:
Answer 4:
Answer 5:
• Paul Barry (2016), Head First Python: A Brain-Friendly Guide, 1st edition, O’Reilly
Publisher.
• Wes McKinney (2017), Python for Data Analysis: Data Wrangling with Pandas, NumPy,
and Ipython, 1st edition, O’Reilly Publisher.
• Swaroop C H (2013), A Byte of Python, Kindle edition, ebshelf Inc.
• Charles Severance (2016), Python for Everybody: Exploring Data in Python 3, Kindle
edition, Amazon Digital Services.
REFERENCES:
<https://docs.python.org/3/library/string.html>
<https://www.w3schools.com/python/python_ref_string.asp>
<https://realpython.com/python-string-formatting/>
<https://realpython.com/lessons/string-operators/>
BACHELOR OF COMPUTER
APPLICATIONS
SEMESTER 5
DCA3104
PYTHON PROGRAMMING
Unit 8: Lists 1
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Unit 8
Lists
Table of Contents
Unit 8: Lists 2
DCA3104: Python Programming Manipal University Jaipur (MUJ)
1. INTRODUCTION
In the previous units, you learned about different kinds of data structures that are used in
Python. These data structures are used to store data in the desired sequence. You have also
learnt the properties of different data structures and sequence data types and how they store
data in the computer memory. With this unit, you will understand the concept of lists used
in Python. Lists are one of the most essential and basic data types. They work similarly to
array in languages C and C++. They store data such as numbers, characters, and even other
data structures in some form of structure.
Python has six built-in sequential data types. Among these, lists, tuples, dictionaries are the
most common ones. The chapter will detail the functioning and operations that are possible
in a list. Other built-in sequence types are the ones that we have already covered in the
previous units. These are strings, Unicode strings, buffer objects, and xrange objects.
Python allows you to store data in a sequence in such a way that you can change the sequence
in the future. You can also use data types that do not support the feature of changing the
sequence while the data structure is being actively used.
Sequential data structures are used when dealing with the collection of values. You can
choose to store similar or different type of data types in a single data structure. Using them
can ease the difficulty level of the code and shorten it so that it is understandable to the user
as well. By using data structures such as lists and tuples, you can make sure that your code
is clean, well-arranged, and easy to manipulate and work with.
For example, you can create a data structure for each student that stores their name, roll
number, address, and marks obtained. Such a data structure will require saving different
data types such as string, integer, and floating-point real numbers. Or, you can create a data
structure that exclusively stores the marks obtained by students in a class in the sequence of
their roll numbers. In such cases, using data structures is the best way to make sense of the
huge data in hand.
Unit 8: Lists 3
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Unit 8: Lists 4
DCA3104: Python Programming Manipal University Jaipur (MUJ)
2. LISTS
Lists are sequential data structures that can contain different data types. They are mutable;
thus, you can change the content and the indexing of the list
STUDY NOTE
while working on it. This feature makes them different from
Python has two kinds of data
other data structures such as tuples and dictionaries and structures, or called container
makes them one of the most versatile data structures in as they contain data. These two
types of sequence containers
Python. and mappings container.
In Python, lists are created by adding the elements of the list inside square brackets []. The
elements inside the brackets are separated by commas. A list can have any kind of data type
such as integer, float, strings, etc. They can also be any number of elements in a list, the limit
depends upon the memory space of the computer system that you are working on.
Example:
a_list = []
a_list = [1, 3, 5]
a_list = [1, ‘harish’, 3]
a_list = [44, [76, 88, 99], 45, ‘a’]
All the above examples are valid in Python. Thus, a list can have mixed data variables, as well
as a list, can be nested into another list. Such lists are called nested list.
Unit 8: Lists 5
DCA3104: Python Programming Manipal University Jaipur (MUJ)
If you try to access a value of the index in a string that does not exist, then the interpreter
will show you an IndexError. Also, one should note that the indexes are always integers
numbers. Using float or other data types as indexes will result in an error called TypeError.
Indexing in nested lists is called nested indexing. Examples are shown below.
Example:
a_list = [1, 3, ‘a’, ‘b’, [4, 5, ‘list’]]
print (a_list [2])
print (a_list [4] [1])
Python also allows negative indexing of the elements in a list. These are used when the list is
to be read from right to left, that is, from the last element of the list to the first. Thus, to
reverse a list, you only need to use negative indexing.
STUDY NOTE
In the above example, add the code provided below. Negative indexing begins
from -1 instead of 0.
print (a_list [-2])
When accessing a single element of a list, you will use indexing. But what if you need to access
more than 1 elements of a list? You can, no doubt, use indexing several times. But if the
elements that you want to access are sequences together in the list, then you can simply use
slicing or splitting.
Slicing is the method through which you can access ranges of elements. This can be done by
separating the indices of the first and last element of the desired range with a colon.
One should note that the index used on the left of the colon refers to the first element that
you want to include while splitting. Whereas, the index on the right of the colon should be
the number of the element that lies after the slice. Go through the example given below to
better understand this.
Unit 8: Lists 6
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Example:
odd_numbers = [1, 3, 5, 7, 9, 11, 13, 15]
print (odd_numbers [1:4])
Activity 1
Create a list that includes marks obtained by a student in various subjects. In the list,
try accessing various elements through indexing and slicing. Use negative indices as
well and find if all combinations yield the desired result. Take note where you find that
the slicing does not work as expected.
Example:
even = [2, 4, 6, 8, 10]
even [0] = 0
print (even)
You can also update the values of several elements in a list with the help of slicing. Use the
code provided below in the above example and find the output.
even [1:4] = [ 2, 4, 6, 8]
Unit 8: Lists 7
DCA3104: Python Programming Manipal University Jaipur (MUJ)
SELF-ASSESSMENT QUESTIONS – 1
1. _____________________ data structures are used when you need to store the data in
order.
2. Lists are enclosed in ______________________ brackets.
3. The list is a mutable data structure. (True\False)
4. Lists can include different data types at a time. (True\False)
5. Which of the following is not a valid list?
a) [1, 2, ‘string’]
b) (1, 2, 3)
c) [‘string’, 1, 2, 3]
d) [‘h’, ‘p’, ‘r’]
3. LIST OPERATORS
There are various things through which lists can be used and manipulated. You will find that
some of these operations are common with all other sequence data structures. Python offers
various methods through which the elements and values of a list can be changed and
updated. These were discussed briefly in the previous units as well. Some of the most
common operations are explained here.
3.1 Repetition
A list can be repeated n number of times with the help of the operator *. The operator creates
a list that has the original list repeated the desired number of times. Here is an example of
repetition in lists.
mylist = [ 3, 6, 9, 12, 15]
print (mylist * 3)
As you might know that in C when you declare an array, you have to provide the number of
elements included in the array during its initialisation. However, in Python, there is no such
requirement. There are cases when you need the list to acquire a definite sequence in the
memory.
Unit 8: Lists 8
DCA3104: Python Programming Manipal University Jaipur (MUJ)
For example, you create an empty list. There are no elements in the list but you need space
to store at least 10 elements in the list. You can introduce one element and repeat it using
the * operator like [0] * 10.
If you want the interpreter to read that there is nothing in the list, or that the list is empty,
then you can right None inside the square brackets of the list. An example is shown below.
Example:
mylist = [None] * 10
print (mylist)
#The output of the program will yield the keyword None printed 10 times.
None, None, None, None, None, None, None, None, None, None
3.2 Concatenation
STUDY NOTE
Two or more lists can be joined together with the operator
Only two similar types of data
“+”. This joining of one sequence with another is called structures can be concatenated
concatenation. The lists can have different data types stored together. For example, you
cannot concatenate a string
in them and can be of different lengths. with a list. s
Example:
lista = [1, 2, 3]
listb = [4, 5, 6]
print (lista + listb)
3.3 Membership
Membership operators are used to checking whether an element is present in a list or not. If
the element is found in the list, then the operator will yield True as the output. If no such
element is present in the given list, the output will be false. There are two member operators
in Python, in and not in.
Example:
Unit 8: Lists 9
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Membership operators have multitudes of uses in real life, especially for security purposes.
For example, it can be used to check whether the entered password matches the one that is
saved.
3.4 Iteration
There are times when you need to manipulate all the elements present in the list with a
similar set of codes. In such cases when the code needs to be performed on all elements of
the list, the list is iterated. There are various ways you can use iteration in the list. These are
explained below.
#Output
1
2
3
4
5
Unit 8: Lists 10
DCA3104: Python Programming Manipal University Jaipur (MUJ)
list = [1, 2, 3, 4, 5]
length = len (list)
for i in range (length):
print (list [i])
#Output:
1
2
3
4
5
#Output:
1
2
3
4
5
#Output:
Unit 8: Lists 11
DCA3104: Python Programming Manipal University Jaipur (MUJ)
1
2
3
4
5
Using enumerate ()
The method enumerates () is used when you need to convert the list into a list of tuples that
can be iterated. Its working is shown through the example.
list = [1, 3, 5, 7, 9]
for i, val in enumerate (list):
print (i, “,”, val)
#Output:
0, 1
1, 3
2, 5
3, 7
4, 9
Using Numpy
When dealing with lists with n number of dimensions, it is better to use an external library
such as NumPy that can speed up the process.
import numpy as mylist
a = mylist.arange (9)
a = a.reshape (3, 3)
for x in mylist.nditer (a):
print(x)
#Output:
0
1
2
3
Unit 8: Lists 12
DCA3104: Python Programming Manipal University Jaipur (MUJ)
4
5
6
7
8
3.5 Length
In some cases, you may need to find the length of the list. This can be done through several
methods. Without using a special function, you can find the length of the list, that is, the total
number of elements includes in a list, in the following way.
list = [1, 3, 5, 7, 9]
i=0
for j in list:i = i +1
print (str(i))
Example:
#even = [2, 4, 6, 8]
even.append (10)
print (even)
#The output will be: 2, 4, 6, 8, 10
Using the method extend (), you can add several items to the end of the list.
Example:
odd = [1, 3, 5, 7]
th=[9, 11, 13]
odd.extend (th)
print (odd)
Unit 8: Lists 13
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Example:
odd = [1, 3, 5, 7]
odd.insert (1, 2)
print (odd)
Note that in the function insert (), the first number represents the index where the new
element is to be included and the second number represents the value that needs to be
included.
Unit 8: Lists 14
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Other methods can be used to delete an element from the list. These include remove (), pop
(), and clear (). remove () is used to delete a given item. pop () is used to delete an item at the
given index. the clear () method is used to empty the complete list.
SELF-ASSESSMENT QUESTIONS – 2
Unit 8: Lists 15
DCA3104: Python Programming Manipal University Jaipur (MUJ)
4. BUILT-IN FUNCTIONS
Python provides various in-built functions that can be used to perform various processes on
the list and its elements. You can use these functions to ease the code or to know more about
the given list. The prominent functions in Python for lists are explained below.
Example:
odd = [1, 3, 5, 7]
print (len (odd))
#The output will be 4.
Example:
odd = [1, 3, 5, 7]
print (max (odd))
#The output will be 7.
Example:
odd = [1, 3, 5, 7]
print (min (odd))
#The output will be 1.
Unit 8: Lists 16
DCA3104: Python Programming Manipal University Jaipur (MUJ)
string1 = “python”
print (list (string1))
#The output will be: [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
SELF-ASSESSMENT QUESTIONS – 3
Unit 8: Lists 17
DCA3104: Python Programming Manipal University Jaipur (MUJ)
5. SUMMARY
• Lists are sequential data structures that work as an array. They store multiple items or
values in a single variable.
• Lists are ordered and allow duplicate values. They are mutable data structures, thus,
the values in a list can be changed after its definition.
• Items in a list have a definite order or sequence which does not change during its
operation. The order is represented with indices.
• The index is an integer value given to each element present in a list. They start from 0
(zero).
• One can update a value in the list with the help of the assignment operator.
• To update two or more elements, present in a list, splitting or slicing can be used. Slicing
is the method through which one can access a part of the list.
• Python allows various operations that can be operated on a list. By using various
operators, the list can be manipulated in different ways.
• Using the multiplication operator can repeat the values included in a list n number of
times.
• By using the addition operator, one can merge two lists such that their elements create
one greater list. This merging process is called concatenation.
• Membership operators are used to testing whether a value is present in a list. These are
in and not in. They yield Boolean values, that is, True and False.
• One can use iterations through various methods and loops so that they can iterate a
certain set of commands overall or selected elements present in a list.
• One can find the length of the list, that is, the number of elements present in the list
with the in-built function available in the Python library called len ().
• There are various methods to add an element to a list. Among them, append () is used
to add an element at the end of the list and insert () is used to add one or more element
at the desired location in the list.
• To remove an element from the list, one can use methods such as remove (), pop (), and
clear (). The keyword del can also be used to remove one or more elements from the
list.
Unit 8: Lists 18
DCA3104: Python Programming Manipal University Jaipur (MUJ)
• One can compare the values and length of two lists with the help of the in-built function
in Python called cmp ().
• To find the least or greatest value in a list, min () and max () functions are used,
respectively.
• list () function is used to convert the parameter into the list.
6. GLOSSARY
• List: A sequential data function that is mutable and ordered.
• Index: Index is the integer value given to each element in a list to identify it uniquely.
• Slicing: It is the feature through which one can access parts of a list.
• Concatenation: It is the process of joining two lists together from end to end to create
a new list.
• Iteration: The process of performing a similar function on one item after another.
• Member operators: Operators that provide True value if an element is present in a
list.
Unit 8: Lists 19
DCA3104: Python Programming Manipal University Jaipur (MUJ)
max (list)
len (list)
list (seq)
Update the list Lists
value
Indexing and
Adding and
List splitting
removing
elements Operations
from a list
Concaten Members
Iteration Length
Repetition ation hip
Unit 8: Lists 20
DCA3104: Python Programming Manipal University Jaipur (MUJ)
7. CASE STUDY
Shopping cart list creation using Python
A store is upgrading its inventory system by making the complete process online. The store
owner decides that the best language to make software will be Python for its ease of learning,
light-weight structure, and various functions and methods integrated into the library.
The owner wants to create an app that records the list of items that are available in the store.
The list of the items should be created such that items can be added, removed, and updated
in the list in the future.
Along with that, the owner needs a method through which the sales of all items can be
compared every month. That is, there should be a list that records the sales of each item
available in the store for each month. Based on the results obtained from the comparison of
these lists, the owner plans to decide whether to continue stocking an item in the store or
not.
The program should also provide the item that was sold the most in a month and one that
was sold the least. It should also let the owner remove various items at a time as their
availability and demand changes according to the season.
Imagine yourself as a part of the team that has been tasked to create such a program. Discuss
and derive an answer for the following questions.
Source: bestpy.com
Questions:
1. Which data structure do you plan to use? Discuss the benefits and disadvantages of each
data structure to create such a program.
2. Which functions and methods you can employ in the program so that it delivers every
expectation of the store owner?
Unit 8: Lists 21
DCA3104: Python Programming Manipal University Jaipur (MUJ)
8. TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS
Q1. Write a Python program and use the concept of indexing to print a date, given year,
month, and day as numbers.
Q2. Write a Python program that prints a text in a box of a given length. The output should
look something like this:
+——————————————————————————+
| |
| I am a code |
| |
+——————————————————————————+
Q3. Write a Python program that checks the user’s name and PIN code of a user.
Q4. Write a Python program to print the sum of all elements in a list.
Q5. Write a Python program that prints the largest number present in a list.
8.1 Answers
1. List
2. Square
3. True
4. True
5. B
6. clear ()
7. append ()
8. +
9. Membership
Unit 8: Lists 22
DCA3104: Python Programming Manipal University Jaipur (MUJ)
10. b) del
11. True
12. True
13. Del
14. +
15. Membership
16. B) [‘a’, ‘e’, ‘I’, ‘o’, ‘u’]
17. B) 0
18. empty
19. string
20. 0
TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS:
Answer 1:
months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]
endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st']
year = input('Year: ')
month = input('Month (1-12): ')
Unit 8: Lists 23
DCA3104: Python Programming Manipal University Jaipur (MUJ)
sAnswer 2:
sentence = input("Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2
print(" ")
print (' ' * left_margin + '+' + '-' * (box_width-2) + '+')
print (' ' * left_margin + '| ' + ' ' * text_width + ' |')
print (' ' * left_margin + '| ' + sentence + ' |')
print (' ' * left_margin + '| ' + ' ' * text_width + ' |')
print (' ' * left_margin + '+' + '-' * (box_width-2) + '+')
Answer 3:
database = [
['albert', '1234'],
['dilbert', '4242'],
['smith', '7524'],
['jones', '9843']
]
username = input('User name: ')
pin = input('PIN code: ')
if [username, pin] in database:
print ('Access granted')
Unit 8: Lists 24
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Answer 4:
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
Answer 5:
def max_num_in_list(list ):
max = list [ 0]
for a in list:
if a > max:
max = a
return max
print (max_num_in_list([1, 2, -8, 0]))
Answer 2:
def is_first_list_longer(list1, list2):
return len(list1) > len(list2)
words1 = ["apple", "banana", "cherry"]
words2 = ["dog", "elephant"]
Unit 8: Lists 25
DCA3104: Python Programming Manipal University Jaipur (MUJ)
Answer 5:
def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
eliflen(s) >len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n=1
while (n <len(s)) and (l[i+n] == s[n]):
n += 1
if n == len(s):
sub_set = True
return sub_set
a = [2,4,3,5,7]
Unit 8: Lists 26
DCA3104: Python Programming Manipal University Jaipur (MUJ)
b = [4,3]
c = [3,7]
print (is_Sublist(a, b))
print (is_Sublist(a, c))
E-REFERENCES:
• Python Programming Certification Training Course, last viewed on March 25, 2021
<https://www.edureka.co/python-programming-certification-training >
• Python Tutorials and Sample Programs, last viewed on March 25, 2021
< https://www.w3schools.com/python/ >
• Integrated Development Environments, last viewed on March 25, 2021
< https://wiki.python.org/moin/IntegratedDevelopmentEnvironments >
Unit 8: Lists 27
DCA3104: Python Programming Manipal University Jaipur (MUJ)
BACHELOR OF COMPUTER
APPLICATIONS
SEMESTER 5
DCA3104
PYTHON PROGRAMMING
Unit 9
Tuple, Sets, and Dictionary
Table of Contents
1. INTRODUCTION
In the previous chapters, you learned about the specific characteristics and distinctiveness
of different features in the Python programming language like various operators, data types,
etc. Python allows programmers to use basic operators that are similar to mathematical
operators such as addition (+), multiplication (*), exponentiation (**), etc. Variables are also
a key component in Python coding for memory storage and to execute tasks. As you now
know, there are also many types of data types that the variables can store, such as string,
integer, boolean, floating numbers, etc.
You also learned about branching and looping in Python. Conditional statements and loops
are used by a programmer when they want to change the program direction. They do this by
setting conditions that direct the program execution. The previous chapters also covered
data structures and some of the types of data structures.
Data structures provide a fundamental construct to your program based on which you can
organize data and retrieve them more efficiently. You have already learned how to use some
data structures/sequence/iterables like list and string. Iterators are objects that store a
given number of values that can iterate. Lists, tuples, sets, and dictionaries all act are iterable
containers from which you can get an iterator.
In this chapter, you will learn about other data structures like tuple, sets, and dictionaries.
You will learn how to create, add, update, delete and retrieve data from these data structures
in your program. This unit's activities will help you familiarise yourself with the given data
structures and assess how to utilize them efficiently.
❖ Create, delete and use the basic operations in a tuple. You will also be able to index and
slice in a tuple.
❖ Create and use different functions in Sets like set(), update(), add(), and discard().
❖ Create, add and delete data in a Dictionary. You will also know how to access data,
perform iteration, and use the built-in functions of a Dictionary.
2. TUPLE
A tuple is an ordered collection of items and is a part of the standard Python language.
Programmers can use a tuple to store multiple items or objects in a single variable.
2.1 Introduction
The tuple is like a list in many aspects and is one of Python's
STUDY NOTE
built-in data types. However, unlike a list, tuples are immutable.
If the individual elements in a
That means we cannot change the elements once we assign tuple are mutable, we can
change their values within
them to a tuple, but we can reassign or delete an entire tuple. the tuple.
Another feature that differentiates a list and a tuple is how they are enclosed. We enclose the
items of a list within square brackets ("[...]"). On the other hand, we use parenthesis or round
bracket ("(...)") to enclose the elements. Although we use parenthesis in a tuple, we refer to
the index number of the elements (enclosed in square brackets) to access them, similar to
lists and strings.
You can also make tuples without using the parenthesis, but it a good practice to use them.
# tuple without parenthesis
l = q, f
print(l)
(q, f)
For the most part, tuples include more than one item. However, the comma must be used
even when creating tuples with single elements.
You can also create tuples with a mix of various data types or nested elements.
# tuple with mixed data types
a=12
my_tup = (a, 'Hi', 3.4)
print(my_tup)
# nested tuple
my_tup = ('horse', [2, 7, 6], (1, 4, 2))
print(my_tup)
In both indexing and slicing, the index operator "[]" is incorporated to access an element. The
program then fetches the respective item from the given tuple (counting from the left).
Indexing is limited only to the number of items in the tuple. If you try to retrieve an element
beyond the index range: the program will raise an IndexError.
Using float or other data types will result in a TypeError. Hence, only integers are allowed in
indexing.
my_tuple = ('my', 'name', 'is')
print(my_tuple[1])
Similarly, if you wish to retrieve items from a nested tuple, you use nested indexing.
# nested tuple
nes_tuple = ("horse", [2, 7, 6], (1, 5, 8))
# nested index
print(nes_tuple[0][3]) # s is retrieved
print(nes_tuple[2][2]) # 8 is retrieved
In slicing, we use the slicing operator (:) to retrieve a range of elements. To understand how
the range works, imagine that the index is present between the elements instead. To access
a range, we use the index that will slice that particular range.
Example:
slice_tuple = ('l', 'o', 'n', 'g', 'i', 't', 'u', 'd', 'e')
print(slice_tuple[1:4])
# elements 2nd to 4th are sliced
# output will be ( 'o', 'n', 'g' )
You can also access a range from the beginning or end to a particular.
slice_tuple = ('l', 'o', 'n', 'g', 'i', 't', 'u', 'd', 'e')
print(slice_tuple[6:])
# elements from 7th to end are sliced
# output will be ( 'u', 'd', 'e' )
slice_tuple = ('l', 'o', 'n', 'g', 'i', 't', 'u', 'd', 'e')
print(slice_tuple[:6])
# elements from beginning to 5th are sliced
# output will be ( 'l', 'o', 'n', 'g', 'i', 't' )
In the above example, if you try to print the tuple "my_tuple," the program will throw a Name
Error.
A. Addition: Using the addition operator (+), we can concatenate two or more tuples.
# '+' will join the three tuples given
t = (2, 5, 0) + (1, 3) + (4, 5, 6)
print (t)
# Output: (2, 5, 0, 1, 3, 4, 5, 6)
C. Using "in" Keyword: We can check the existence of an element in a tuple using the "in"
keyword. If the element exists, the program will return 'True'; otherwise, it returns
'False'.
#Using "in" keyword
my_tuple = ('l', 'o', 'n', 'g', 'i', 't', 'u', 'd', 'e')
print('n' in my_tuple) # Output: True
print('a' in my_tuple) # Output: False
D. min() and max() Function: Using the min() and max() function, we can determine the
tuple's minimum and maximum values.
#Using min() and max() Function
my_tuple = (1,2,3,4,5,6)
print (max(my_tuple)) # Output: 6
print (min(my_tuple)) # Output: 1
E. Iterating in a Tuple: We can use the for loop to iterate through a tuple as follows:
# Using for loop to iterate through a tuple
for name in ('Joshua', 'Mike'):
print("Hello", name)
# Output
Hello Joshua
Hello Mike
Activity 1
Create a program that calculated the element-wise sum of three tuples. Assign the same
number of integer data type elements to three tuples. Your output should print the three
tuples used along with the sum of the elements that belong to the same index in each
tuple.
SELF-ASSESSMENT QUESTIONS – 1
3. SETS
Unlike a tuple, a Set is an unorganized and unindexed collection of objects. The items in a set
do not have a defined order and may appear in a different order every time we use them.
Hence, they cannot be accessed or referred to using a key or index.
3.1 Introduction
Every value in a set is unique and unchangeable. Set elements are unordered. That is, there
is no specific order in which the elements appear. Set features restrict duplicate values. In
addition, we can add additional elements to the existing set. Set hold its elements in curly
brackets "{...}".
different data types ( boolean, integer, string, etc.). You can check the datatype of a
variable using
However, a set cannot have a mutable element like lists print(type(<variable>)).
or dictionaries.
# Set with mixed data types
my_set = {5.0, "H1", (1, 2, 3)}
print(my_set)
set<iterable>
The "iterable" in the above syntax may be a list, a dictionary, a string, or a tuple. We can
create an empty set using the set() method if we do not specify any argument/iterable in it.
# Creating an empty set
a = set()
We can add a new item in a set using the add() method. The add() method is used with the
following syntax:
set.add(elem)
Where "elem" is the element that we want to add. We cannot get back a set if we use the
add() method while creating a new set.
noneValue = set().add(elem)
The above expression will return "none" as that is the return type of add().
#Output:
The letters are: {'p', 'c', 'r', 'e', 'o'}
# The order of the letters may be different.
3.5 Update()
The update() method is similar to the add() method. However, we can add multiple elements
at the same time using the update() method. The update() method can accept any iterable
like tuples, lists, strings, or other sets. It has the following syntax:
set.update(iterable1, iterable2, iterable3)
Similar to the add() method, update() does not return any value. Let us see how the update()
is used to add another set to an existing one.
letter = {'p', 'y', 't'}
let = {'t', 'h', 'o', 'n'}
# using update()
letter.update(let)
print ("The word is ", letter)
Output:
The word is {'p', 'y', 't', 'h', 'o', 'n' }
3.6 Discard()
In Python, the library function discard() is programmed to eliminate specific elements from
the set, given the elements are available in the set. Discard() function will not display error
if the element specified in the discard() function is not available in the iterable unlike
remove() function.
Syntax:
set.discard(x)
Where "x" is the element to be removed, the discard() method does not have a return value.
Method 1:
num = {2, 6, 4, 5, 3}
num.discard(3)
print('numbers = ', num)
# Output: numbers = {2, 6, 4, 5}
The output remains the same even if we use the code below:
num.discard(15)
print('numbers = ', num)
# Output: numbers = {2, 6, 4, 5}
Method 2:
num = {2, 6, 4, 5, 3}
print(num.discard(3))
# The above expression returns "None"
print('numbers = ', num)
# Output: numbers = {2, 6, 4, 5}
Activity 2
Create a set and a tuple with the names of your peers. Write a Python program to add
the tuple to the set to create a new set. Write a program to iterate through all the
elements of the set using the for a loop.
SELF-ASSESSMENT QUESTIONS – 2
9. ____________ method does not give an error on removing an element that does
not exist.
10. Set elements are enclose within _____________ brackets.
11. We can add multiple elements to a set using the ___________ method.
12. Sets are mutable, unorganized, and non-indexed collections. [True/False]
13. We cannot convert iterable elements into a set. [True/False]
14. We cannot use the add() method while creating a new set. [True/False]
15. The Python code “s = {2, 3, 4, [5, 6]}” will throw an error. [True/False]
16. What will be the result of the following code:
lett = set(['a','a','b','b','c','c','c','c'])
print(len(lett))
a) 7
b) Error, invalid syntax for formation of set
c) 3
d) 8
4. DICTIONARY
Dictionaries are central data structures in Python that store an ordered collection of items.
Each item in a dictionary is mutable and identified using a key name (or key) with an
associated value. Unlike an index, a key can be of any data type, such as string, float, integer,
etc., making it more flexible.
Dictionaries can store any number of items and are also referred to as maps, hashmaps,
lookup tables, or associative arrays. In the real world perspective, dictionaries can be
associated with phonebooks. They help you quickly retrieve information, such as a phone
number, with a specific key (person's name).
the desired key for elements. However, the key must be unique
and immutable data types such as string, number, or tuple. On the other hand, the item
associated with the key may be of any data type.
The key and its value are separated by a colon (:), the unit items are separated by commas,
and the whole sequence is enclosed within curly brackets.
Unlike other ordered data structures that use indexing, dictionaries use keys to access or
retrieve items. We can access the values in the dictionary by using the square bracket ("[...]")
or the get() method.
If a value does not exist in the dictionary and we use the square brackets, the program raises
a KeyError. In contrast, the get() method returns a "None" value.
Example:
# retrieving elements
my_dict = {'name': 'Phil', 'age': 50, 'country': 'America'}
# Accessing value using []
print(my_dict['name']) #Output: Phil
# Accessing value using get()
print(my_dict.get('country'))
#Output: America
We can delete the items from a dictionary using the del keyword with the key enclosed in
square brackets.
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus', 50 : 'marigold'}
# Deleting item using del keyword
If you wish to remove an item and return the value associated with it, you can use the pop()
method.
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus', 50 : 'marigold'}
# Deleting item using pop() method
print(my_dict.pop(40))
#Output:
lotus
The popitem() method is used to delete the last item in the dictionary and return its key and
value. Using the clear() method, delete all the items in a dictionary.
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus', 50 : 'marigold'}
# Deleting item using popitem() method
print(my_dict.popitem())
Output:
(50, 'marigold')
# Deleting all the items
print(my_dict.clear())
#Output:
None
#Output:
Key: name and Value: Phil
Key: country and Value: America
You cannot directly concatenate an integer with a string when using the for loop. However,
we can use the format() method in the following manner.
my_dict = {'name': 'Phil', 'age': 50, 'country': 'America'}
for i in my_dict:
print ("Key: {0} and Value: {1}".format(i, my_dict[i]));
#Output:
Key: name and Value: Phil
Key: age and Value: 50
Key: country and Value: America
• all():
The python library function ‘all()’ checks whether all entries or items in the iterable is true.
If the iterable contains completely true element, the any() function returns ‘true’ whereas it
returns a ‘false’ if there is any one false element in the iterable object, that is iterable contains
a 0 or false. If there is no element in the object, then the all() returns “true”.
Syntax: all(iterable).
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus', 50 : 'marigold'}
print(all(my_dict))
#Output :
True
# All keys are True
my_dict = {0 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus', 50 : 'marigold'}
print(all(my_dict))
#Output :
False
# 0 is False
• any(): The python library function ‘any()’ checks whether minimum one entry/item in
the iterable is true. If the iterable contains atleast one true element, the any() function
returns ‘true’ whereas it returns a ‘false’ if there is no true element in the iterable object.
That is the iterable contain only either 0 or false.
Syntax: any(iterable).
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus'}
print(any(my_dict))
#Output :
True
# All keys are True
my_dict = {}
print(any(my_dict))
Output :
False
# Empty dictionary
• cmp(): Compares the items of two dictionaries. However, this function is not available in
Python 3.
• sorted(): Python has the library function to easily sort any sequence, ‘sorted()’. Sorted()
function gives sorted output and it does not alter the original sequence.
The parameter ‘iterable’ is mandatory. Iterable disclose the object to be sorted. While key
and reverse parameters are optional. If the reverse parameter is given value true, then
reverse sorting takes place.
# Sorting the key as a list
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus'}
print(sorted(my_dict))
#Output:
[10, 20, 30, 40]
# Using the reverse parameter
my_dict = {10 : 'rose', 20 : 'lily', 30 : 'tulip', 40 : 'lotus'}
print(sorted(my_dict, reverse = True))
#Output:
[40, 30, 20, 10]
# Reverse key order
# Using the key function
my_dict = {'10' : 'rose', '2000' : 'lily', '30' : 'tulip', '400' : 'lotus'}
print(sorted(my_dict, key = len))
#Output:
['10', '30', '400', '2000']
# Thelen function sorts the keys based on their length
Activity 3
Create a dictionary for student marks of 10 students, where the student's name is the
"key," and the marks are the "value". Add a new item pair for "Priya," who got 75 marks
in her test. Then, sort the items in descending order, based on the student names.
SELF-ASSESSMENT QUESTIONS – 3
Tuples, Sets,
Tuples and Adding
Dictionary and
Basic Deleting
Dictionary
Operations Values in
of Tuple Dictionar
Indexin y
g and
Slicing Built in
Delete a Functions
Tuple of Iteration in
Negative Dictionary Dictionary
Indexing Sets
Introduction
Discard()
Creating
a set Update()
Add()
Set()
Method
5. SUMMARY
• Data structures are the basic constructs used by programmers to organize and access
data quickly. Data structures are often referred to as sequences. Also, they are a
collection of data objects or elements using which programs are executed.
• Data structures may be ordered (each element has a unique index or key using which
they are retrieved), or maybe unordered (the elements have no proper order and give
different outputs on retrieval).
• A tuple is an ordered data structure that has immutable elements enclosed in round
brackets. Each element in it is indexed. Programmers use index values to retrieve
individual or sequences of elements.
• Individual elements are retrieved through indexing, where the element index is
mentioned in '[]' brackets. Positive indexing starts from '0' and moves from left to right
in the sequence. Negative indexing gives the '-1' value to the last element and decreases
from right to left.
• Segments of a sequence are retrieved through slicing by using the slicing operator (':’).
• We can perform basic mathematical functions on a tuple, like addition, multiplication,
etc.
• A set is an unordered data structure whose elements cannot be indexed. The elements
are immutable, non-duplicated, and are enclosed in curly brackets.
• Python has built-in set methods like update(), discard(), set(), add(). These methods do
not return a value.
• The set () method is used to create a new set or convert another iterable into a set.
• Add() method, add single elements or iterables to an existing set.
• We add multiple elements or iterables by using the update() method.
• Discard() is used to remove elements or iterable from a set. Unlike remove() it does not
raise an error if an item does not exist in a set.
• A dictionary is an ordered data structure whose elements are defined as a (key: value)
pair. The key must be of an immutable data type, whereas the value can be of any data
type. The keys make item retrieval faster from dictionaries.
• The key-value pairs must be separated by (:), and a comma should separate each item.
We can access items from a dictionary by mentioning the key in '[]' brackets.
• The "=" operator can add item pairs. It enables the addition of new item pairs or the
updating of existing key values. Using the 'del' keyword, it deletes items in a dictionary.
• Using for loop Dictionary items can be iterated.
• Built-in functions like all(), any(), sorted() can be used to perform tasks on dictionaries.
6. GLOSSARY
Object: Any data that has a defined value and behaviour. Also called element or item.
Argument: A value passed to a function or a method when calling them.
Iterable: It is an object that can be iterated over. In sequences, it returns its members one
after the other.
Function: A series of statements that return a value to the caller.
Hashable: An object is said to be hashable if its value never changes during its lifetime.
Hashable objects are used as a dictionary key and a set member.
Immutable: An object that has a fixed value.
Key function: It is a callable that delivers a value used for sorting or ordering.
Object: Any data that has a defined value and behavior. Also called element or item.
Argument: A value passed to a function or a method when calling them.
Iterable: It is an object that can be iterated over. In sequences, it returns its members one
after the other.
Function - A series of statements that return a value to the caller.
Hashable - An object is said to be hashable if its value never changes during its lifetime.
Hashable objects are used as a dictionary key and a set member.
Immutable - An object that has a fixed value.
7. CASE STUDY
Robots: The Game
A version of the classic console game "Robot" was created, in which the programmer used a
subclass of dictionary called a box. The robot is a turn-based game in which the player tries
to stay alive by avoiding relentless robots. The game is set up so that the robots move one
square towards the player in every move. The player dies if the robot catches them. If the
robots collide with each other, they die and leave behind "junk," which also kills them.
The game's primary strategy is that the player has to position themselves so that the robots
colloid with each other or the junk piles every time they move towards the player. The player
also can teleport three times in the game.
The programmer used a subclass of the dictionary known as "box" to create the game grid
and move the game elements according to the player's actions. The box is a subclass that
overrides a few base functionalities to ensure everything stored in the dictionary can be
accessed as an attribute or key value. It acts as a replacement for dictionaries and can include
multiple dictionaries, lists, etc. Each dictionary or list added to the box object becomes a part
of the sub-class and is retrieved using unique keys assigned to it. The programmer used the
box as a collection of the grid dimensions and object coordinates that can be retrieved
whenever the box is called.
Source- www.openbookproject.net
Discussion Questions:
1. How is the box sub-class better than a normal dictionary?
2. Can you guess when the programmer used the box in the program code is?
3. Try to create a box sub-class that can create the game grid?
8. TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS
Q1. Which is faster for data retrieval, list, or dictionary?
Q2. Retrieve the first four numbers from the given tuple by using negative indexing:
tup = (3, 56, 23, 4, 55, 7, 1, 8, 532)
Q3. How are lists and tuples different in Python?
Q4. Determine the output of the code given below.
student = {'Student': 'Dave', 'mark': 100}
print(student['Student'])
print(student['DOB'])
Q5. Correct the code given below so that no KeyError will be thrown.
student = {'Student': 'Dave', 'mark': 100}
print(student['Student'])
print(student['DOB'])
8.1 Answers
SELF ASSESSMENT QUESTIONS
1. Tuple
2. Commas
3. Square brackets
4. Multiplication operator
5. False
6. False
7. False
8. B. A tuple is immutable. Hence, we cannot change the values of the elements.
9. Discard()
10. {} bracktes
11. update()
12. True
13. False
14. True
15. True. A set can only contain hashable/immutable data types. A list is a mutable data
type and hence shows an error.
16. C. A set does not allow duplicates
17. Dictionary
18. Key
19. “=” operator
20. False
21. True
22. B. Dictionaries are created by using the key: value format.
TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS
Answer 1: A list takes more time to retrieve or find data as the program filters through every
value in the list. On the other hand, a dictionary has a well-defined key: value item pairs that
allow you to quickly retrieve data as long as you have the right key.
The negative indexing starts from the end of the sequence and is placed in between the
elements.
LIST TUPLE
Answer 4: Output:
Dave
KeyError: 'DOB'
#The above code will give error because student dictionary do not have element 'DOB'.
Total of all the elements of each tuple filled in the said list of tuples:
[6, 7, 6, 12]
>
#output
{1: 1, 2: 4, 3: 9, 4: 16}
Answer 5:
word=’programming’
# Convert the word into set
unique_alphabets=set(word)
# Find the length of the set
length_of_set=len(unique_alphabets)
print(‘Unique alphabets:’,length_of_set)
E-REFERENCES:
• "Python 3" viewed on 28 March 2021,
<https://www.programiz.com/python-programming/tutorial>
• Dictionaries in Python, viewed on 28 March 2021,
<https://www.studytonight.com/python/dictionaries-in-python>
• Common Python Data Structures, viewed on 28 March 2021,
<https://realpython.com/python-data-structures/#dictionaries-maps-and-hash-
tables>
BACHELOR OF COMPUTER
APPLICATIONS
SEMESTER 5
DCA3104
PYTHON PROGRAMMING
Unit 10
Methods
Table of Contents
1. INTRODUCTION
Python is considered one of the easiest programming languages that can be used for software
development, web development, mathematics, data handling, etc. It is one of the widely used
programming languages globally on multiple platforms such as Windows, Linux, Mac,
Raspberry Pi, etc.
In the previous unit, we learned about tuple, sets, and dictionaries in Python. A tuple is a
collection of values assigned to an ordered variable and cannot be changed once formed.
Tuple can also contain duplicate values. An example of a tuple is given below.
On the other hand, a set is a collection of values of data types that is both unordered and
unindexed. It is also unchangeable but does not allows duplicate values like in a tuple, and if
present, it will simply ignore it. An example for a set is given below.
Note that the values will be displayed in the output at random positions every time because
a set is unordered. A dictionary stores values in pairs. It means it stores a key and a value for
that key together and not one at a time. It is ordered, can be changed and does not allows
duplicate values or pairs. An example for the same is given below.
In this unit, we will learn about functions in Python in detail. We will go through a brief
introduction to functions, then learn about the types of functions and benefits of functions in
Python. Furthermore, we will understand the process of creating a function and calling a
function to use in a code. Moving on, we will understand the return statement of functions
and parameters used in a function. Call by reference and variable-length functions will be
discussed and the unit will end with keyword arguments.
2. INTRODUCTION TO FUNCTIONS
Repetition in any type of code for any objective is very
problematic, both for the programmer and the reader. STUDY NOTE
Repetition of codes in any program makes the program Functions must be created at
the beginning of the program
unclear and rough. Even though the code works and and before using it. Otherwise,
Python will generate an error
completes the objective for which it was created, it still causes and display that no such
function has been defined.
many problems and errors due to its unclear structure.
A structured code not only takes less space but is also very easy to read and interpret and
generates fewer errors to deal with. Therefore, it was crucial to introduce a method that
eliminates the use of codes multiple times in any program. Functions are created for this
purpose. Once you understand something that has to be repeated multiple times in a
program, you can simply define a function and call it multiple times in a program whenever
you want that activity to be performed.
Efficient use of functions in a code can increase the effectiveness of that program. Whenever
we set activities to be executed from time to time in a program, we create a function and
assign that set of values to it along with a name. This way, whenever we need those sets of
actions to be executed, we have to call that function and let it do the work.
Python programming language already has numerous built-in functions in its huge standard
library such as sort(), title(), print(), range(), len(), and much more that makes programming
fun and easy. You can also create your functions using the keyword def and assign the set of
actions to it that you want to be executed.
The key to solving complex programs is to break them into smaller parts and tackle one part
at a time. This method allows the programmer to focus on one task at a time and organize
their code by creating small functions to carry out the tasks in an ordered manner. This
eliminates the possibility of having a complex and difficult solution to an already complex
problem. Functions make coding easier for programmers. This also ensures less error than
usual.
SELF-ASSESSMENT QUESTIONS – 1
3. TYPES OF FUNCTIONS
As we learned in the above section, functions are meant to carry out specific tasks in a given
program when called for execution. They might need or do not need input at all. The function
can either return a single value or multiple values. All this depends upon the type of function
used in the program. There are three types of functions in Python, which are as follows:
• Built-in functions: These types of functions are already STUDY NOTE
built into Python. There are numerous functions pre-
Functions are meant to carry
defined for the benefit of the programmers. Some out specific tasks. They can
return multiple values at
examples for built-in functions in Python are print(), once.
• `len()`: This function returns the number of items (length) in an object. The argument
can be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as
a dictionary, set, or frozen set).
print(len("Hello, World!"))
• `max()`: This function returns the largest item in an iterable or the largest of two or
more arguments.
print(max(1, 2, 3, 4, 5))
• `min()`: This function returns the smallest item in an iterable or the smallest of two or
more arguments.
print(min(1, 2, 3, 4, 5))
• `format()`: This function formats specified values and insert them inside the string's
placeholder. The placeholder is defined using curly braces: `{}`.
print("Hello, {}!".format("World"))
This program will ask for your name and then output `Hello, <Your Name>!`.
• `range()`: This function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (also by default), and stops before a specified number.
for i in range(5):
print(i)
print(type(123))
• `map()`: This function applies a given function to all items in an input list.
numbers = [1, 2, 3, 4, 5]
print(squared)
This will output `[1, 4, 9, 16, 25]`, which are the squares of the numbers in the original
list.
numbers = [1, 2, 3, 4, 5]
print(product)
This will output `120`, which is the product of the numbers in the list.
• `filter()`: This function constructs an iterator from elements of an iterable for which a
function returns true.
numbers = [1, 2, 3, 4, 5, 6]
print(even_numbers)
This will output `[2, 4, 6]`, which are the even numbers from the original list.
• User-Defined functions: These are the functions that the programmers create then
and there at the start of programming to solve the present problem or perform any
activity.
• Anonymous functions: Anonymous functions in Python are known as "lambda"
functions. They are called "anonymous" because they are functions that are defined
without a name. While normal functions are defined using the `def` keyword in Python,
anonymous functions are defined using the `lambda` keyword.
The `lambda` keyword is followed by one or more arguments, separated by commas, then a
colon `:`, and then an expression. The expression is what the function returns.
In this example, `x` and `y` are arguments to the function, and `x + y` is the expression. The
lambda function is assigned to the variable `add`, and it can be called just like a normal
function.
Lambda functions are used when you need a function for a short period of time, usually for
one-time usage. They are often used with functions like `map()`, `filter()`, and `reduce()`,
which take a function as an argument.
For instance, you can use a lambda function to square all numbers in a list:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
In this example, the `map()` function applies the lambda function to each element of the list
`numbers`, and returns a new list `squared` that contains the squares of the numbers.
SELF-ASSESSMENT QUESTIONS – 2
5. CREATING A FUNCTION
After knowing the concept, types, and benefits of the
STUDY NOTE
functions, let's move on to the next section. By creating a
function, we mean defining the function. To define a Note that indentation is very
important in Python. The body of
function, the def keyword is used. It marks the start of the the functions should be indented
properly or else Python will raise
function header. You have to take care of indentation while indentation error.
Whenever you create or define a function, you have to name it to call it in the program. The
name of the function has to be unique because this name will identify the function in the
program. The naming of the functions has some rules that you have to follow. It is easy to
remember once you get the hang of it.
• The keywords defined in Python cannot be used as a name for any function.
• Spaces are not allowed in naming a function.
• The first character can be the uppercase alphabet, lowercase alphabet, or “_” character.
• The next characters can be the combination of uppercase, lowercase alphabet,
numbers, or “_” character.
• Remember that special characters such as "$," "#," "%," "!", "@" are not allowed in the
naming of the function.
The next important thing in defining a function is the parameter or the input which is passed
or given to the function. This is optional. Then comes the “:” colon that marks the end of the
function header.
Even though you define the function, explaining what it does exactly is very much
appreciated in a single line. This you can do with the help of documented string (docstring)
which is optional too.
Now comes the body where you can write some python statements to allocate some action
to the function. Remember that all the statements inside the body of the function must have
the same indentation level. Python places heavy emphasis on indentation therefore, you
should take extra care on this part.
Source: ProgramBitz.com
Fig 1: Parts of function
A return statement to get a return value from the function is also optional but is very useful.
Example:
#def func_new1():
print(‘I am learning Python.’)
Activity 1
Define a function that can accept the name, marks, and roll numbers of 30 studenst in a
class and display the data of each student in a single line, one by one. Discuss the
parameters used in defining the function.
SELF-ASSESSMENT QUESTIONS – 3
6. CALLING OF FUNCTION
When the time of executing a function that you have created comes, you call it. Calling a
function is directly employed to carry out the tasks you have assigned or created in it. When
you call any function, you can say that the program's control has been transferred to the
function for that time being. It means that the execution of the program is in the hands of the
function. After executing the tasks assigned or defined in the function, it will return to the
next line after the function call.
To call any function, you must use the unique name used to define the function. Simply type
the name of the function and provide values of the parameters, if any. This will prompt the
function to take control of the program for that time and execute the commands given in the
body of the function.
Example:
#defining of function
def func_new():
print(‘I was invisible and now I am visible.’)
#calling of function
func_new()
Output is as follows:
I was invisible and now I am visible.
SELF-ASSESSMENT QUESTIONS – 4
21. To call any function, the _________________ name of the function should be written
that was used to define it.
22. Calling a function means accessing the built-in functions in the Python library.
[True/False]
23. Calling a function can be done by using the def keyword. [True/False]
24. Calling a function means accessing the lambda functions. [True/False]
25. Calling of a function does which of the following things?
a) Executes the commands defined in the function
b) Passes the arguments into the function for evaluation
c) Erases the function
d) Both a and b
The use of a return statement in defining a function is optional and depends on the tasks
required to be done.
Source: FunctionBits.com
Fig 2: Brief of Return statement
The return statement can be used several times depending on the complexity of the problem.
An example is given below for you to understand the use of the return statement better.
Example no.2:
#when return statement is present
def mod(number):
“”” this fuction returns the mod values of any number”””
if number >= 0:
return number
else :
return -number
print(mod(4))
print(mod(-5))
#calling the mod function
mod(4)
mod(-5)
SELF-ASSESSMENT QUESTIONS – 5
8. PARAMETERS IN FUNCTIONS
The parameter is the unbound variable used in defining the
STUDY NOTE
function. People often get confused about the difference
Note that all the commands
between the parameter and the argument. If you define a written after the return
statement in any function will
function like def func(name), then the name is the never get executed because the
execution of the function stops
parameter, whereas when you call the function, then the right after it executes the return
statement.
actual values used for the parameter is known as the
argument.
Parameters can appear in the function's body, whereas when the function is called, then the
argument or the specific value given by the programmer takes its place in processing for the
output.
There is no rule to limit the number of parameters to be present in a function. One can have
as many parameters in the function as required. The main function of parameter variables is
to transfer arguments in the function. There are two types of parameters in functions:
• Input parameter: They transfer the absolute values given by the user to the functions.
• Output/Return parameter: They return multiple values from the function but are not
used very frequently because they confuse.
Several parameters or a parameter list explain the types of values or arguments a function
will receive.
Example:
#defining a function
def func_new1(obj):
print(“I have a” + obj)
#calling the function
func_new1(“computer”)
SELF-ASSESSMENT QUESTIONS – 6
31. ______________________ type of parameter transfer the absolute values given by the
user to the functions.
32. _______________________ type of parameter return multiple values from the function
but are not used very frequently because they cause confusion.
33. Parameters are the absolute value passed into a function. [True/False]
34. Only one parameter can be introduced at a time. [True/False]
35. What is the main function of the parameter?
a) to pass the arguments into the functions.
b) to create memory space for the actual value
c) to help carry out the tasks assigned to the function
d) to give the function a unique name
9. CALL BY REFERENCE
The Python programming language uses the ‘Call by Object Reference’ or ‘Call by
Assignment’. When mutable arguments are passed into the functions, meaning that the
values can be changed in the functions and the change will be reflected in the output, then it
is called call by reference. Let us see an example for the same to get a clear idea of the concept.
Example:
STUDY NOTE
#demonstration of call by reference
When you pass arguments that
def add(list): are immutable, meaning that
the arguments cannot be
mylist.append(10) changed then it is called call by
value. executes the return
print("List inside functions:",list) statement.
mylist=[2,4,6,8]
add(mylist)
print("List outside the function:",mylist)
You already know that we can add items to a list after it is made. Thus we used to call by
reference to add the number. The changed list was reflected in the output.
SELF-ASSESSMENT QUESTIONS – 7
Let us talk about the first type here, and we can discuss the
STUDY NOTE
second type of parameter in the next section. In the first
Using the *args does not mean
type, we use to put the asterisk in front of the parameter or that you cannot use the regular
parameters alongside wth it. You
use the standard parameter *argsto accept variable amounts can use it and the preceding
of arguments. The syntax for this can be seen below. arguments will be evaluated first.
Example:
def func_name( *args ):
#body of the function
Let’s see an example to understand this concept.
def biggest_number(*num):
#this function returns the biggest number
return max(num)
#calling the function
print(biggest_number(33,66))
print(biggest_number(7,99,82,44))
print(biggest_number(55,93,30,65,72,32))
Activity 2
Create a list that includes marks obtained by a student in various subjects. In the list,
try accessing various elements through indexing and slicing. Use negative indices as
well and find if all combinations yield the desired result. Take note where you find that
the slicing does not work as expected.
SELF-ASSESSMENT QUESTIONS – 8
Example:
#using keyword argument
def func(name, activity):
“””this function tells which person is doing
what at the moment”””
print(name + “is” + activity) STUDY NOTE
#calling the function The position of the arguments
does not matter in Python as
func(name = “Arya”, activity = “dancing” ) long as the key is assigned to
the relevant parameter.
func(name = “Ananya”, activity = “singing” ) Python will use the
relvantvaluse according to to
func(name = “Aditya”, activity = “playing” ) the keys to which it is assigned.
SELF-ASSESSMENT QUESTIONS – 9
Creating a Introduction to
Function Functions
Benefits of
Functions
Call by
Reference
Calling of
function
Methods
Variable-length
Functions
Return Statement
of Function
Types of
Functions
Parameters in
Functions Keyword
Arguments
12. SUMMARY
• Python can be used for software development, web development, mathematics, data
handling, and so on.
• A tuple is a collection of values assigned to an ordered variable and cannot be changed
once formed.
• A set is a collection of values of data types that is both unordered and unindexed.
• A dictionary stores values in pairs, which means it stores a key and a value for that key
together and not one at a time.
• Functions make coding easier for programmers. This also ensures less error than usual.
• Functions must be created at the beginning of the program and before using it;
otherwise, Python will generate an error and display that no such function has been
defined.
• Built-in functions are the types of functions are already built into Python.
• User-Defined functions are the functions that the programmers create then and there
at the start of programming to solve the present problem or perform any activity.
• Anonymous functions are not declared outright with the standard keyword def and
therefore are called lambda functions.
• Functions make solving complex problems easy when divided and tackled in parts.
• Indentation is very important in functions.
• The name of the function has to be unique because this name will identify the function
in the program.
• The function defined by you will only work when it is defined before the function call
or before it is used in the program.
• Return statement in Python for the function is the way to exit the function when needed
and go back to the initial call line.
• When mutable arguments are passed into the functions, meaning that the values can be
changed in the functions and the change will be reflected in the output, then it is called
call by reference.
• The parameter is the unbound variable used in defining the function.
• The variable-length argument will accept the numerous variable arguments that will
be eventually stored in a list.
• The keyword arguments will accept not only the variable number of arguments, but
also the key to each argument.
13. GLOSSARY
Argument: Value passed to the function when it is called.
Call a Function: The method to access a function in Python language
Dictionary: An array where keys are mapped to their values.
Docstring: First expression in a function that explains what does the function do.
Expression: Something that can be evaluated to give an output.
Function: A set of actions that returns something to the programmer when called.
Indentation: Spaces at the start of the command line.
Keyword Arguments: A key and value are both passed to the function.
Lambda function: Anonymous function in python that does not have a unique name.
List: An ordered collection of items that can be changed.
Parameter: A variable that specifies an argument.
Return statement: The command that returns a value after evaluation.
Tuple: An ordered collection of items that cannot be changed.
You can approve and track your order while you sit back and relax. cancellation of the order
option is also present should the user does not want to place an order any more.
The app has two branches, one in which the delivery person could pick up delivery and the
second where the delivery person could purchase the groceries selected by the customer.
The apps for the user and the delivery guy were different. The user has the options to confirm
or cancel after the delivery guy makes clear which of the selected groceries are available and
which are not. The challenge was to relay the message in real-time and keeping the overall
navigation easy for the user to have the best experience.
Source: Indianic.com
Questions:
1. Discuss the number of screens required and create a wireframe for the same app.
2. What built-in functions are used in the placing of order section?
15.1 Answers
SELF ASSESSMENT QUESTIONS
1. Built-in
2. Clear
3. FALSE
4. TRUE
5. C. both a and b
6. User-defined
7. Lambda
8. TRUE
9. FALSE
10. C. maximum()
11. Repetition
12. Reusable
13. True
14. True
15. A. Code becomes structured and more manageable.
16. def
17. :
18. False
19. True
20. B
21. #define the action of the function(optional)
22. statement(s)
23. Unique
24. False
25. False
26. False
27. D. Both a and b
28. Return
29. Expression
30. False
31. False
32. C. Return [expression]
33. Input
34. Output/Return
35. False
36. False
37. A. to pass the arguments into the functions.
38. ‘Call by Object Reference’
39. Call by reference
40. False
41. False
42. A. all the arguments
43. *
44. True
45. False
46. False
47. Tuple
48. **kwargs
49. True
50. True
51. False
52. C. Both the arguments and their keys are given
TERMINAL QUESTIONS
SHORT ANSWER QUESTIONS
Answer 1:
def func(*args):
for x in args:
print(x)
func(3,5,6,7)
func(22,55,66,77,99)
Answer 2:
def cal(a, b):
return a+b, a-b
res = cal(98, 79)
print(res)
Answer 3:
List = [5,7,8,6]
print(max(List))
Answer 4: No need not to remember the order of the arguments while using this. We can
specify the values for the parameters which we want.
Answer 2:
def string_rev(str):
rstr = ‘’
index = len(str)
while index > 0:
rstr += str[ index - 1 ]
index = index - 1
return rstr
print(string_rev('language'))
Answer 3:
def range(n):
if n in range(1,10):
print( " %s is in the range"%str(n))
else :
print("The number is not in the given range.")
range(5)
Answer 4:
def multiply(num):
total = 1
for x in num:
total *= x
return total
l=[1, 2, 3, 4, 5]
print(multiply(l))
Answer 5:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n=int(input("Input a number: "))
print(fact(n))
E-REFERENCES:
• Python functions, last viewed on March 29, 2021 <
https://www.programiz.com/python-programming/function-argument \ >
• Python functions, last viewed on March 29, 2021 <
https://www.w3schools.com/python/python_functions.asp >
• Functions in Python, last viewed on March 29, 2021 <
https://www.geeksforgeeks.org/functions-in-python/ >
• Define your own Python Function, last viewed on March 29, 2021 <
https://realpython.com/defining-your-own-python-function/ >
• Creating functions, last viewed on March 29, 2021 <
https://swcarpentry.github.io/python-novice-inflammation/08-func/index.html >
BACHELOR OF COMPUTER
APPLICATIONS
SEMESTER 5
DCA3104
PYTHON PROGRAMMING
Unit 11
Exception Handling
Table of Contents
SL Fig No / SAQ /
Topic Page No
No Table / Graph Activity
1 Introduction - -
3
1.1 Learning Objectives - -
2 Exception handling introduction - 1 4
3 Common errors - 2,I
3.1 Nameerror - -
3.2 Indentationerror - - 5 - 14
3.3 IOerror - -
3.4 EOFerror - -
4 Try-except statement - 3, II
15 - 19
4.1 Try-except-else statement - -
5 Multiple exceptions - 4, III
20 - 23
5.1 Try and finally block - -
6 Raising exceptions - 5 , IV
24 - 28
6.1 Custom exceptions - -
7 Summary - -
29 - 30
8 Glossary 1 - 30 - 31
9 Case Study - - 32
10 Terminal Questions - - 33
11 Answers - - 34 - 38
12 Suggested Books and e-References - - 38
1. INTRODUCTION
In the previous units, you learned about variables and the parameters to define them. You
understood all the keywords reserved in Python for specific actions and the different data
types that store data in various forms, such as string, alphanumeric, integers, decimals, etc.
Conditional statements (branching) and looping are also a fundamental part of Python
programming. Conditional statements define the conditions or parameters that the program
has to evaluate before code execution in a sequential manner. On the other hand, loops are
used to execute code as long as the conditions are satisfied. Unlike other programming
languages, Python gives the programmer the flexibility to nest various conditionals and
loops within each other, without any restrictions.
In this unit, you will learn about errors or exceptions. You will get to know why these errors
arise and about the different types of errors. You will also learn about what to do when the
exceptions come up and how you can solve them.
In professional scenarios, programmers deal with vast amounts of codes that might be
difficult to handle. Due to errors in code, the code script may not work as expected, run
partially, abruptly end, or even "crash" and not run at all.
SELF-ASSESSMENT QUESTIONS - 1
3. Techniques and practices used to test and identify errors is known as error
handling. [True/False]
4. A programmer should always predict potential error and add code to deal with
them. [True/False]
5. In Python, when program errors are anticipated and rectified they are called:
3. COMMON ERRORS
In Python programming, an error may be caused due to several reasons and can be of
different types. A SyntaxError occurs when the rules or syntax for coding program
instructions are violated. They arise when a keyword is omitted or misspelt, the branching
or looping structure is incomplete, inconsistency in indenting and variables, improper use of
operators, functions, function arguments, and more.
Logical errors or bugs arise when a program seems to run properly, but produces
unexpected or wrong results. To avoid logical errors, the program must be tested repeatedly,
and the results should be thoroughly scrutinized, verified, and validated.
A NameError is one of the most common types of errors that arise in Python programming.
Python throws a name error if you try to use a variable or a function name that is not defined
or is not available in the local or global scope. There are a few instances when a NameError
arise.
#Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(boooks)
NameError: name 'boooks' is not defined
In the above example, the variable "books" has been misspelt as "boooks" in the print
statement. The error can be easily rectified by correcting the spelling:
#Output:
Sherlock Holmes
The Order
The Alchemist
(ii) When a function is called before it is declared
Python reads code in a sequential manner, i.e., from top to bottom. Hence, functions
must be declared before they are called in a program.
#Output:
Traceback (most recent call last):
File "<string>", line 3, in <module>
NameError: name 'get_books' is not defined
We try to call the get_books() in line three. However, we did not define it before using
it in the program.
Correct Code:
# Defining a function
def get_books(books):
for b in books:
print(b)
books = ["Sherlock Holmes", "The Order", "The Alchemist"]
get_books(books)
#Output:
Sherlock Holmes
The Order
The Alchemist
for b in books:
print(b)
#Output:
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'books' is not defined
Strings in Python should be enclosed in single or double quotation marks ('...' or "..."),
otherwise, it is considered a part of the program.
print(Order)
#Output:
Traceback (most recent call last):
print('Order')
#Output:
Order
(v) When a variable is declared out of scope
Variables have two scopes: local and global. Local variables are those that can only be
accessed within the class or function they are defined in. On the other hand, global
variables can be accessed throughout the program. If we try to access a local variable
outside its class or function, the program throws a NameError.
def get_books():
books = ["Sherlock Holmes", "The Order", "The Alchemist"]
for b in books:
print(b)
get_books()
print(len(books))
#Output:
Sherlock Holmes
The Order
The Alchemist
Traceback (most recent call last):
File "<string>", line 7, in <module>
NameError: name 'books' is not defined
Although the list of books is printed successfully, the last line throws an error. This is
because we have declared "books" inside the get_books() function as a local variable.
get_books()
print(len(books))
#Output:
Sherlock Holmes
The Order
The Alchemist
3
3.2. Indentation Error
• When you use both spaces and tabs in the written code.
• When code in compound statements like conditionals and loops are not indented
properly.
Example:
# Wrong indentation
site = 'pro'
if site == 'pro':
print('Using Python')
else:
print('Please use proper indents')
#Output:
Correct Code:
# Correct indentation
site = 'pro'
if site == 'pro':
print('Using Python')
else:
print('Please use proper indents')
#Output:
Using Python
3.3. Io Error
The IOError is associated with the input-output operations in Python. These exceptions
arise if you try to open a file that does not exist (by using the open() function) or when there
is an error in the print statement. The I/O reasons for failure may be: “Disk full” or “File not
found”.
Here the error name is followed by the error number ( that has occurred in a single program)
and the reason for the error. IOError shows the common reason as "No such file or
directory", which can mean that the file we have asked for does not exist or the file location
is incorrect. The exception ends with the file name so we can identify and correct the file we
have passed.
import sys
file = open('mefile.txt')
lines = file.readline()
slines = int(lines.strip())
#Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'myfile.txt'
In the above code, we try to perform three operations on a file. We first try to access the file.
Next, the readline() method should read the content of the file and at last strip() should
remove the characters that are at the start and end of the sentences. As expected, the above
code will throw an IOError as "mefile" does not exist.
The EOFError exception is raised in Python when the input() (or STUDY NOTE
We handle the IOError and
raw_input() in Python 2) return an end-of-file (EOF) without EOFError exceptions by
using
reading any input. This happens when we ask the user for input the try and except keyword
s in Python.
but it is not provided in the input box.
Example:
n = num(input())
print(n * 15)
#Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError: EOF when reading a line
Activity I
Correct the common errors in the following code:
print(nums)
print("\nSum of all the elements of each tuple stored inside the said list of
tuples:")
print(test(numms))
SELF-ASSESSMENT QUESTIONS - 2
6. ___________ errors arise when the rules of code formatting are not followed in
Python.
7. Logical errors are also known as ___________.
8. Variables have __________ and ____________ scope.
9. A NameError arises when a variable or function name is misspelt, or they
are used before declaration. [True/False]
10. Python follows the PEP8 whitespace ethics where there should be 3
whitespaces used between any alternative or iteration. [True/False]
11. Which of the following errors will arise if a file cannot be found?
a) EOFError b) IOError c) NameError d) ImportError
12. The following code will give which type of errors?
def get_flr():
flr = ["Rose", "Lily", "Tulip"]
for f in flr:
print(f)
get_flr()
print(len(flr))
4. TRY-EXCEPT STATEMENT
You are now familiar with the most common type of errors that occur in Python
programming. But how are these errors resolved in Python?
Many programming languages like Python have a construct to handle and deal with errors
automatically, known as Exception Handling. Errors are resolved by saving the state of the
code execution at the instance the error occurred and interrupting the normal flow of the
program to execute a piece of code known as the exception handler.
Example:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
#Output:
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'>occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In the above program, we use the for loop to loop through the values in the list " randomList".
As mentioned, the code that may raise an exception is placed under the try block.
The except block is skipped if no exception arises and the loop continues to the next value.
However, if an exception occurs it is caught by the except block and the mentioned action is
executed.
We use the exc_info() function to print the exception name. "a" causes a ValueError as it is
a character and 0 causes a ZeroDivisionError as it is mathematically invalid.
Sometimes you may wish to execute specific blocks of code if no exceptions arise when the
try clause runs. In such cases, you can use the else clause with the try statement. The
statement follows the syntax:
try:
<code>
except:
<code>
else:
<code>
Example:
# printing reciprocal of even numbers
try: STUDY NOTE
The preceding except
num = int(input("Enter a number: ")) clauses do not handle the
exceptions that may arise
assert num % 2 == 0 in the else clause.
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)
#Output:
# For an odd number
Enter a number: 1
Not an even number!
# For an even number
Enter a number: 6
0.16
# If 0 is passed
Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in <module>
reciprocal = 1/num
ZeroDivisionError: division by zero
In the above code, the code block inside else is not handled by the preceding except clause.
Hence, if 0 value is passed, the program throws a ZeroDivisionError.
Activity II
The given code has a few bugs. Add a try-except clause so the code runs without
any errors. If a blog post didn’t get any likes, a ‘Likes’ key should be added to that
dictionary with a value of 0.
total_likes = 0
SELF-ASSESSMENT QUESTIONS - 3
13. What is the minimum number of except statements a try-except block
should have?
A. more than zero
B. one
C. more than one
D. zero
16. If an exception arises in the else clause, it's preceding except clause will
handle it. [True/False]
17. Python has a construct to handle and deal with errors automatically, known
as _______________.
5. MULTIPLE EXCEPTIONS
A piece of code does not always throw only one exception. Multiple errors may arise while
coding and all of these have to be predicted and handled without making the code
complicated or lengthy. You can do this by using multiple except clauses with the try
statement.
Each exception needs to be handled in specific ways and each except clause should catch only
a particular exception. Although any number of except statements can be used in the code,
only one of them is executed if an exception occurs.
Example:
try:
<try block>
pass
except ValueError:
<handle ValueError exception>
pass
except (TypeError, ZeroDivisionError):
# handle multiple exceptions
<TypeError and ZeroDivisionError>
pass
except:
<handle all other exceptions>
pass
The above code is a pseudo-code where the first except block will handle any ValueError
exceptions, while the second except block will handle both TypeError and
ZeroDivisionError. The third block will handle all other exceptions.
We use the finally statement with the try clause to close a file or disconnect from a network.
try:
< try block >
except :
< except block >
:
:
:
finally :
< finally block >
Example:
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
The above finally block closes the "test.txt" file at the end of the program.
Activity III
Write a multiple exception code that will evaluate TypeError, KeyError, and
IndexError for a given list.
SELF-ASSESSMENT QUESTIONS - 4
18. The following syntax is that of the try-finally statement. [True/False]
try:
<block>
finally:
<block>
except:
<block>
19. Multiple exceptions be handled by only one block of statement. [True/False]
20. ________ clause is always executed in the program.
21. The output of the given code is _____________.
def a():
try:
print(1)
finally:
print(2)
a()
22. The output of the following code is:
def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
A. after f?
B. after f
C. no output
D. error
6. RAISING EXCEPTIONS
Generally in Python, exceptions are raised automatically when errors occur and are caught
during run-time. However, we can manually raise exceptions by using the raise keyword.
The raise keyword can be used in the following manner:
The third code will raise a ValueError with the sentence "Not a positive number!" is a number
less than 0 is entered.
The raise keyword can also be used in conjugation with the for and the while loops with the
syntax:
If the defined conditional statement returns a "True" value, the user-defined exception with
the custom statement is thrown at the user. The statement can include any data type and
variable.
Example:
def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(20)
#Output:
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "<string>", line 3, in getMonth
ValueError: Invalid
The above code throws the custom error as the value passed as an argument is greater than
12.
Programmers can define their own custom exceptions by creating a new class.
Example:
# define Python custom exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
# you need to guess this number
number = 10
# user guesses a number until he/she gets it right
while True:
try:
i_num = int(input("Enter a number: "))
if i_num< number:
raise ValueTooSmallError
elifi_num> number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")
#Output:
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
The above program asks users to guess a stored number till they get it right. To help them,
hints are provided to tell them if the number they have guessed is too small or too large.
The defined base class in the program is "Error". The exceptions "ValueTooSmallError" and
"ValueTooLargeError" are derived from "Error"
Activity IV
Define a custom exception class which takes a string message as attribute. Hint: To
define a custom exception, we need to define a class inherited from Exception.
SELF-ASSESSMENT QUESTIONS - 5
23. We use the ___________ keyword to create custom exceptions.
24. User-defined exception classes are derived from a ______________.
25. When using the raise keyword with a loop, the custom exception is raised if the
return value is "True". [True/False]
26. The given code throws a TypeError. [True/False]
2 + '5'
27. If the following code “t[23]” is given, the error will be:
A. NameError
B. ValueError
C. TypeError
D. IndexError
7. SUMMARY
• Error handling is the process of using practices to test and identify errors. When an
error arises, the program throws an exception. The process of rectifying errors is called
debugging.
• Potential errors should always be considered before code execution.
• A syntax error occurs when the rules of code formatting are not followed. Run-time
errors raise during run-time if a processed value is invalid.
• Logical errors are also called bugs. They raise when the program runs without throwing
an exception but gives unexpected or wrong results. These are the most difficult to
detect.
• NameError arises when a variable or function name is misspelt, a function is called
before it is declared; when we don't define a variable; when a string is not defined
properly; when a variable is declared out of scope.
• Variables have two scopes: local and global. Local variables can only be used within the
class they are defined in. Global variables can be used anywhere in the program.
• IndentationError arises when the code is not indented properly. Python follows the
PEP8 whitespace ethics where there should be 4 whitespaces used between any
alternative or iteration.
• IOError arises when there is an error in the input-output operations. If you try to open
a file that does not exist or the file location is wrong, an IOError exception is thrown.
• EOFError is raised when the input() or raw_input() function reaches its end-of-file
(EOF).
• We use the try-except statement to provide construct to handle exceptions. The
potential error code is placed in the try clause and the code that will handle the error
is placed in the except clause.
• We can use the else statement to execute specific blocks of code if no exceptions arise
when the try clause runs. We can use multiple except clauses to execute and deal with
specific errors.
• The finally clause is used to disconnect from external networks and close external files
or GUIs.
• We can manually raise exceptions by using the raise keyword. The keyword can also be
used in loops and is executed when the value is "True".
• Programmers can define their own custom exceptions by creating a new base class and
deriving exception classes from it.
8. GLOSSARY
• Class - An object constructor, or a "blueprint" for creating objects.
• Exception - A message thrown by the program when an error occurs.
• Debugging - The process of identifying and correcting errors.
• Bugs - Logical errors that give unexpected results.
• Local variable - Variable that can only be used in the class it is defined in.
• Global variable - Variable that can be used anywhere in the program.
• IndexError - Error rise when an index of a sequence is out of range.
• ValueError - Error rise when a function gets an argument of the correct data type but
improper value.
• TypeError - Error rise when an operation or function is applied to an incorrect data
type.
• ZeroDivisionError - Error rise when the divisor in a division or modulo is zero.
• MemoryError - Error rise when an operation runs out of memory.
Exception
Handling
Name Error
Raising
Exceptions
Common
Errors
Custom
Exceptions
Indentation
Error
EOF Error
Multiple
Exceptions
IO Error
Try-Except
Statement
Try and
Finally
Block
Try-Except-
Else
Statement
9. CASE STUDY
Error free library log recorder using Python
A library is upgrading its inventory system by making the complete process online. The store
owner decides that the best language to make software will be Python for its ease of learning,
light-weight structure, and various functions and methods integrated into the library. The
library attendant wants to create an app that records the list of books that are available in
the library without any duplication, to track the complete number of books received, rented
or damaged to return and books that should be available for use, such that new books can be
added, removed, and updated in the list in the future. There were many books which will be
already available so the tracking is bit though due to duplication.
Along with that, the library attendant needs a method through which the sales of all items
can be compared every month without any errors in numbers and registers. That is, there
should be an error handling involves the techniques and practices used to test and identify
errors. Identifying these errors and debugging them. Based on the results obtained from the
comparison of these lists, the library attendant plans to decide whether to continue receiving
the book in the library or not.
The program should also provide the complete activities of individual book that was used
the most in a month and one that was used at the least. It should also let the library attendant
to remove various items at a time as their availability and demand changes according to the
best seller.
Imagine yourself as a part of the team that has been tasked to create such a program. Discuss
and derive an answer for the following questions.
Questions:
1. What kind of exception handling are you going to use? To build such a program, discuss
the advantages and disadvantages of the type you are using.
2. What approaches would you use in the software to ensure that it meets all of the library
attendant's expectations?
Q2. Can we add other statements in between ‘try’, ‘except’, and ‘finally’ blocks?
Q3. Is it possible to use a ‘try’ block without the ‘except’ and ‘finally’ blocks?
Q1. Write a Python code to execute exception handling for the following code: (use the try-
except statement)
a = 10
b=0
Q2. Write a Python code that will ask the users to "Enter numerator number" and "Enter
denominator number", and use multiple except blocks to raise ZeroDivisionError and
ValueError. Another except block should handle other errors.
Q3. Write a Python exception handling code that will accept a float integer and inverse its
value. After program execution, it should print the message: "There may or may not have
been an exception." (use the try-finally statement)
Q4. What is the standard format of IO error exception along with an example?
11. ANSWERS
SELF-ASSESSMENTS QUESTIONS
1. Debugging
2. Exception
3. True
4. True
5. B. handled errors. When errors are predicted and addressed, they are known as handled
errors. Otherwise, they are referred to as unhandled errors.
6. Syntax
7. Bugs
8. Local, global
9. True
10. False
11. B. IOError. IOErrors are associated with input-output operations.
12. A. Name and Indentation.
13. 13) A. more than zero. There has to be at least one except statement.
14. False
15. True
16. False
17. Exception Handling
18. False
19. True
20. Finally
21. 1 2. No error occurs in the try block so 1 is printed. Then the finally block is executed
and 2 is printed.
22. D. error. 'f' is not defined.
23. Raise
24. base class
25. True
26. True
TERMINAL QUESTIONS
Answer 1: Exceptions are abnormal conditions or errors that are sometimes encountered in
a program. They disrupt the flow of the program and it is important to them. Not handling
the exceptions can result in unwanted or incomplete outputs and even termination of the
program.
Answer 2: Adding other statements like 'if', 'else', 'for', etc. is not recommended as the ‘try’,
‘catch’, and ‘finally’ blocks make up one exception handling unit. They follow the syntax:
try:
< try block >
except :
< except block >
:
:
:
finally :
< finally block >
Answer 3: Using a ‘try’ block without the ‘catch’ and ‘finally’ blocks will result in a
compilation error. It is necessary that a 'try' block is followed by an 'except' block or a 'finally'
block, if not both. The code that can potentially raise an exception is placed inside the try
clause. On the other hand, the code that can handle these exceptions are placed in the except
clause. If neither is present, the flow of exception handling is undisrupted.
• Name Error
• Indentation Error
• IO Error
• EOF error
• When you use both spaces and tabs in the written code.
• When code in compound statements like conditionals and loops are not indented
properly.
# try block
try:
a = 10
b=0
print("Result of Division: " + str(a/b))
except:
print("You have divided a number by zero, which is not allowed.")
Answer 2: Answer Code:
# try block
try:
a = int(input("Enter numerator number: "))
b = int(input("Enter denominator number: "))
try:
x = float(input("Your number: "))
inverse = 1.0 / x
finally:
print("There may or may not have been an exception.")
print("The inverse: ", inverse)
Answer 4: The IOError exception follows the standard format of:
Example:
import sys
file = open('mefile.txt')
lines = file.readline()
slines = int(lines.strip())
Output:
import sys
file = open('myfile.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• Sharma, P. (2017). Programming in Python. John Wiley & Sons. (Third ed.).
• Vashisht, R. (2013). Exception Handling in Python. Dover Publishing.
• Müller, A. C., Guido, Sarah (2016). Introduction to Machine Learning with Python: A
Guide for Data Scientists. O’Reilly Media, Inc.
E-REFERENCES:
Unit 12
Built-in Functions in Python
Table of Contents
12.1 Introduction
Learning Objectives
12.2 Date and Time
12.2.1 time.time()
12.2.2 time.localtime()
12.2.3 asctime()
12.2.4 sleep()
12.2.5 Creating date objects
12.2.6 Comparison of two dates
12.2.7 Calendar module
Self-Assessment Questions
12.3 Miscellaneous
12.3.1 abs()
12.3.2 all()
12.3.3 bin()
12.3.4 bool()
12.3.5 bytes()
12.3.6 callable()
12.3.7 compile()
12.3.8 exec()
12.3.9 sum()
12.3.10 any()
12.3.11 ascii()
12.3.12 help()
Self-Assessment Questions
12.4 Summary
12.5 Glossary
12.6 Case Study
12.7 Terminal Questions
Answer keys
A. Self-Assessment Questions
B. Terminal Questions
12.8 Suggested Books and e-References
Page | 1
Python Programming Unit 12
12.1 INTRODUCTION
Python programming is used widely around the globe on different softwares, development
and management of data. You learnt some of the basic blocks of the Python programming
language that can be used to code a program. In the previous section, you were introduced
to exception handling in Python. You may learn to write a code or a program to any
problem presented to you, but it is equally important to learn to handle the errors and
exceptions generated by Python itself.
These errors or exception can be related to anything in your code. The errors generated by
Python during the execution of the program refer to exception. An exception is due to some
internal issue in the program which obstructs its execution. Exception handling can be
done by using statements such as try, except, and so on. Using these statements you can
easily remove the barriers in your code and make the execution smooth and uninterrupted.
Python programming language comes with an impressive and huge standard library that
allows the programmers to use the built-in functions present in their program to carry out
the specific tasks. This makes programming in Python simple and straightforward. It saves
a lot of time, energy and data for the programmers.
The built-in functions in Python are those functions whose tasks are already pre-defined in
Python. The programmers have to need to define such functions. These functions can be
used directly in any program as deemed necessary by the programmers. Python has a total
of 67 built-in functions so far for the convenience of the programmers.
There are several advantages of built-in functions in the Python programming language,
some of which are given below.
Since there are so many built-in functions in the standard library of the Python
programming language, it is not possible to explain every one of them. You already know
some basic built-in functions like print(), max(), min(), etc. But we have assembled some
important built-in functions in this unit that might come in handy frequently.
Page | 2
Python Programming Unit 12
LEARNING OBJECTIVES
Page | 3
Python Programming Unit 12
Time is a complex and crucial factor. It is one of the foundations of a structured world and
universe. Without something like time to keep in check the events, the world will erupt into
chaos and disorder. Not a single platform, organisation or country could move forward
without order and structure. Therefore it is necessary to know how to implement date and
time in any software, or service that you would be working at.
Python programming language has many built-in libraries in which date and time module
are also present. Several built-in functions are present in the time module that are used to
carry out different operations using time. These functions can do the conversion,
representation and several other implementations that are necessary for life. Here are
some terms listed out that you need to understand before knowing the functions.
To carry out these operations, we must be aware of the starting point. Epoch in Python
corresponds to the measurement of time starting from January 1, 1970. Epoch is generally
known as the starting point of the time.
The total number of seconds passed since epoch is referred to as seconds since the epoch.
Leap seconds are not included in seconds since the epoch.
UTC is referred to as Coordinated Universal Time. This same term was known as
Greenwich Mean Time or GMT.
The times presented in the output by these functions are in floating numbers. Let us
discuss the functions from the time module one by one.
12.2.1 time.time()
The time.time() function returns the number of seconds passed after epoch. Suppose one
needs to finds out the number of seconds passed since epoch(the beginning of time), then
this function comes in handy. Simply apply the time.time() and get the results in a floating
number. The syntax for this particular function is given below.
time.time()
Page | 4
Python Programming Unit 12
In this particular example, the time module is imported from the built-in libraries of the
Python programming language. The return of the function is stored and then printed to
know the value of output. This is the most basic function of the time module.
12.2.2 time.localtime()
The function, time.localtime(), is used to convert the number of seconds elapsed since
epoch and returns the value in local time using the function struct_time(). The syntax for
the function is given below.
time,localtime([secs])
The parameter required for this function is optional. The parameter is in the form of
integer or floating value. If secs is not specified for the function, then the current time will
be calculated using the time.time() function. The return of this function is an object of class
time.struct_time. An example for the above function is given below.
In this particular example, after importing the time module to use its function, an object is
created to get the return in the localtime and the return is obtained by using the print
function.
Since we get the output in the form of values returned through time.struct_time, it is
important we know all the values of attributes used and know the terms more clearly. The
table given below presents all the values in order.
Page | 5
Python Programming Unit 12
One can use both the attributes and the indices to access the above values for programs.
12.2.3 asctime()
The time.struct_time and the time.localtime() return values in tuple form. The asctime()
function is used to convert the tuple returned from these functions to string form. The
syntax can be seen below.
time.asctime([t])
print(str)
This is a very good example to understand the function and working of this time function.
The values that we obtain through time.struct_time object can be easily converted by the
use of this simple function.
Page | 6
Python Programming Unit 12
12.2.4 sleep()
During the execution of the program on any device, sometimes the flow of the program
needs to stop for time being. The time is specified and for this purpose, the sleep() function
is used.
It is a flexible and convenient way of halting a program for specific needs for the desired
period. the syntax for this function is given below.
sleep(sec)
The parameter sec refers to the number of seconds the program has to be suspended. This
parameter is necessary because, without it, Python will not know how many seconds the
program has to be halted. The return for this function is nothing, void. It may seem like a
useless function but it has any uses that will get know by looking at the examples given
below.
#importing the time module
import time
#printing a sentence
print(“This sentence is printed right now.”)
In this program, the first sentence will be printed immediately. however, there will be a
delay of 10 secs before printing the second sentence. Let's look at some applications of this
built-in function.
What is a date? A date is simply a representation of a day, month and year. Creating a date
object means an object which represents a day, month and year. We can take the help of the
date class to create a date object. Take a look at the examples given below to understand
better.
#importing the time module
import time
Page | 7
Python Programming Unit 12
print(x)
2021-01-04
In this example, the date object is created from the date class and stored in a variable. The
date contains three arguments, that is, day, month, and year. you have to note that the
variable x here is the date object that is created using the date class and the date
constructor.
We can also import the date class from the DateTime module as demonstrated below.
There is also a second method you can use for creating the date objects to get the current
date. You can take the help of the classmethod named today() for that purpose. Let us take
a look at how can we do it.
t = date.today()
tstamp = date.timestamp(1374839227)
print(“The date required is =”, tstamp)
Page | 8
Python Programming Unit 12
The output will the date till which are the seconds measured from January 1, 1970.
You can create date objects with these methods as required in your program. You must not
forget to import the modules require or Python will generate an error because it will not
recognize the functions.
How do you compare two things? Obviously, by the help of comparison operators. We have
learnt about the comparison operators in unit 10. The comparison operators are <, >. =, <=,
>=, !=, and so on. Can you recall what the most basic condition to compare two objects is?
They should belong to the same group. For example, you
cannot compare a string and a number, or a list or a
number. Comparison is done between the elements of the STUDY NOTE
same group. The date objects can be
compared the same way the
Let us look through some examples to know more about the dates are compared.
comparison of the two dates.
The output of the above program will be the boolean values and is demonstrated below.
x is greater than y: TRUE
x is less than y: FALSE
x is not equal to y: TRUE
You can also sort the dates and put them into a list or tuple. Comparison operators make
this easy.
Page | 9
Python Programming Unit 12
This in-built calendar module includes all the functions and classes that take care of the
operations related to a calendar. The calendar is different in different regions, but the one
recognized by the Python programming language is the current Gregorian calendar in
which Monday is considered as the first day of the week and Sunday, the last day of the
week. The functions and classes included in the calendar module are essential for the
implementation of the functions on the calendars. There are three classes in total included
in the calendar module.
• Calendar
• TextCalendar
• HTMLCalendar
After going through the following examples, we will get a better understanding of how to
use the classes and functions in the calendar module. in this first example. We will write a
program to display a calendar of a particular month.
yy = 2021
mm = 04
You can print the calendar for the whole year in the same way.
You can create a calendar object from the calendar class. The process is the same only the
class and object is different. Several formatting methods can be used through the calendar
object. Some of the useful methods from the calendar class are given below.
• iterweekdays() Method
Page | 10
Python Programming Unit 12
A list of indexes is returned for the days of the week by this method. a simple example
given below will allow you to understand more easily.
cal = calendar.Calendar()
for i in c.iterweekdays():
print (i, end="")
The output is as follows.
0123456
• itermonthdates() Method
Two arguments are required for this method, namely, year and month. Iterator of all the
days of the month is returned by the use of this method. Look through the given example.
cal = calendar.Calendar()
for i in c.itermonthdates (2021, 3):
print (i, end="")
• itermonthdays() Method
This method returns the day numbers and is similar to the itermonthdates method.
cal = calendar.Calendar()
for i in c.itermonthdays (2021, 3):
print (i, end="")
• monthdatescalendar() Method
Two arguments, year and month, are required for this method. This method returns full
weeks in a month.
Page | 11
Python Programming Unit 12
cal = calendar.Calendar()
for i in c.monthdatescalendar (2021, 3):
print (i, end="")
• monthdayscalendar() Method
Two arguments, year and month, are required for this method. This returns a list of full
weeks and each week containing the list of days of a month.
• yeardatescalendar() Method
This method returns the list of weeks in the month of the year as full weeks.
This class is used to generate text calendars. It is very similar to the class calendar. Some of
the methods in TextCalendar Class are given below for a better understanding of the
concept.
• formatmonth() Method
Four arguments are required for this methods: year, month, the width of days(w), and the
number of lines used for each week(1). Multi-string is returned by this method. An example
of this method is presented below.
cal = calendar.TextCalendar()
print(c.formatmonth(2021, 1))
The output will be the calendar for the given month and the year.
• prmonth() Method
This method is used to avoid the use of the print() function and returns the month of the
calendar.
• formatyear() Method
Page | 12
Python Programming Unit 12
An "m" column calendar for the entire year is returned by this method in the form of a
multi-line string.
This class generates an HTML calendar. Some methods that are included in the
HTMLCalendar Class are presented below.
• formatmonth() method
The calendar of the month in HTML table format returned from this method. we can easily
display a calendar for a month for any year using this method.
• formatyear() method
This method prints the calendar for the entire year, whichever desired by the programmer
or the user, in the HTML table format. Year and number of months are taken in as the
argument for this method. The default width is set to 3.
• formatyearpage() method
This also printsthe calendar for the entire year, whichever desired by the programmer or
the user, in the HTML table format. The difference is that this method also takes CSS and
encoding as arguments which are optional as well. The default value of CSS and encoding is
set to none and width is set to 3.
ACTIVITY 1
Understand the above functions and use the sleep() function of the time module to
make a digital clock. Make sure to print the local time after each second. This
means after every print, a delay of 1 second has to be made.
Page | 13
Python Programming Unit 12
SELF-ASSESSMENT QUESTIONS
1) The built-in functions in Python are those functions whose tasks are already
-______________ in Python.
3) The date objects can be compared the same way the dates are compared.
(True/False)
A. formatmonth() method
B. formatyear () method
C. formatyearpage() method
D. All of these
12.3 MISCELLANEOUS
There are numerous built-in functions in various classes and methods, each one useful in
its way. Still some functions are used for several different tasks and they are discussed
below one by one.
12.3.1 abs()
This function is used to present the absolute value of the given number. The syntax for the
abs() function is given below.
abs(num)
For integers and floating-point numbers, the function displays the absolute value. In the
case of complex numbers, it returns the magnitude part of the complex number to the user.
Page | 14
Python Programming Unit 12
An example of the use of the function is presented below. We will present all the numbers
in the code for a better understanding of the function.
#enter an integer
integer = 67
12.3.2 all()
all(iterable)
As shown, the parameter used can be the elements of a list, tuple, dictionary, or string.
Page | 15
Python Programming Unit 12
#create a set
set1 = {1, 0, 0, 0 ,1}
a = all(set1)
print(a)
12.3.3 bin()
The num parameter can be any integer that has to be converted to a binary number for
some operation. The return value is in the type of a binary string of integer values. Error is
raised when a floating-point number is given in the argument. Let us look at an example for
this function.
Page | 16
Python Programming Unit 12
12.3.4 bool()
The bool() functions either return a boolean value or converts the given value to a boolean
value. The syntax for the boolean value is given below.
bool([x])
This function requires a single parameter that is evaluated to give the results awaited. If
nothing is passed as a parameter to the function then the default value, that is, FALSE is
printed. The function does one of the two things after receiving the parameter:
Some of the conditions for which this function returns FALSE is listed below. Other than
these, it returns the boolean value TRUE.
#create string
str = “I can code very well.”
print(bool(str))
12.3.5 bytes()
Interconversion of data types in Python can be done by using the bytes() function. It is
useful for converting data types using its coding schemes. it converts the given object into
an immutable object of the right size and data. The syntax for the bytes() function is given
below.
The parameter source is the object which is to be converted. Encoding is the parameter
that is required for the object in the string. The error provides the method to handle the
Page | 17
Python Programming Unit 12
#create a string
str = “Python is the best”
x = bytes(string, ‘utf-8’)
print (x)
12.3.6 callable()
Callable is a term that means something that can be called. In Python, the callable()
function returns the boolean value TRUE if the argument appears callable and FALSE if it
does not. The syntax for this function is given below.
callable(object)
The object passed into the function is checked whether it is callable or not and then the
corresponding boolean value is returned.
Check out the below example to know the task of this function.
def func():
return 10
# a test variable
num = 5 * 10
print(callable(num))
TRUE
FALSE
12.3.7 compile()
Can you remember when you used to compile the source code in C language and then the
code was executed? This function does the same thing. It takes in a source code and returns
Page | 18
Python Programming Unit 12
a code object which will be ready for execution. The syntax for this function is presented
below.
x = 20
12.3.8 exec()
This function in Python is responsible for the dynamic execution of the program for either
string or object code. the syntax for these functions is given below.
The object parameter can be a string or object code. Globals is optional and can be a
dictionary. Locals are also optional and can be a mapping object.
20
Page | 19
Python Programming Unit 12
12.3.9 sum()
This function is the most used and common. It returns the sum of the elements(numbers)
in a list, tuple, dictionary, or any set. the syntax is presented below.
sum(iterable, start)
The iterable refers to the elements present in the set, list, tuple, or dictionary. The tables
should be numbers only. The start is optional and is added to the sum of the iterables. The
default value is 0 if anything is not given. The example is given below.
numbers = [1,2,5]
Sum = sum(numbers)
print(Sum)
12.3.10 any()
The any() returns the boolean value TRUE for even a single true element in the iterable and
FALSE if all the elements in the iterable are false. The syntax for the given function is
presented below.
any(iterable)
The iterable can be a set, list, dictionary, or tuple. Let us look at the given example.
12.3.11 ascii()
This function returns a string of representation of the object and escapes the non-ASCII
characters in the string using \x, \u or \U escapes. The syntax of the function is given
below.
ascii(object)
Page | 20
Python Programming Unit 12
12.3.12 help()
This function is used to display the documentation of the functions, keywords, module, or
classes, etc. The syntax of the function is given below
help([object]
SELF-ASSESSMENT QUESTIONS
Page | 21
Python Programming Unit 12
12.4 SUMMARY
• The built-in functions in Python are those functions whose tasks are already pre-
defined in Python.
• These functions can be used directly in any program as deemed necessary by the
programmers.
• Several built-in functions are present in the time module that are used to carry out
different operations using time.
• Epoch in Python corresponds to the measurement of time starting from January 1,
1970.
• The time.time() function returns the number of seconds passed after epoch.
• The function, time.localtime(), is used to convert the number of seconds elapsed
since epoch and returns the value in local time using the function struct_time().
• The asctime() function is used to convert the tuple returned to string form.
• sleep() is a convenient way of halting a program for specific needs for the desired
period.
• By creating a date object means an object which represents a day, month and year.
• Comparison is done between the elements of the same group.
• The calendar module is an in-built module that includes all the functions and classes
that take care of the operations related to a calendar.
• A list of indexes is returned for the days of the week by iterweekdays() method.
• Iterator of all the days of the month is returned by the use of itermonthdates()
method.
• itermonthdays() method returns the day numbers and is similar to the
itermonthdates method.
• monthdatescalendar() methods return full weeks in a month.
• monthdayscalendar() returns a list of full weeks and each week containing the list of
days of a month.
• TextCalendar class is used to generate text calendars.
• HTMLCalendar class generates an HTML calendar.
• abs() function is used to present the absolute value of the given number.
• The bin() function converts the decimal number into a binary number.
• Interconversion of data types in Python can be done by using the bytes() function.
Page | 22
Python Programming Unit 12
12.5 GLOSSARY
Page | 23
Python Programming Unit 12
sleep()
time.loc asctime()
altime() Creating date
objects
time.time()
Comparison
of two dates
Built-in Functions
in Python
Miscellaneous
abs()
all()
ascii()
bin()
help()
bool()
sum()
bytes() callabl compile() exec()
e() any()
Page | 24
Python Programming Unit 12
Package Delivery App was made to ease the process of shipping and
receiving parcels. The delivery app was developed to ensure smooth
tracking of parcel till delivery. One can create a new shipment and
track it until it is delivered. The UX designs were unique and still up to
market standards.
The first challenge was to take up all the shipping information to start
the delivery. The tracking screen and tracking screen shows detailed
information with a presentable layout.
Even the graphic designs were made keeping the company’s brand in
mind.
This app has a unique chat and review feature which makes it popular
among the growing number of users.
Source: www.inianic.com
Questions:
Page | 25
Python Programming Unit 12
ANSWERS
1) pre-defined
2) time.localtime()
3) TRUE
4) TRUE
5) D. All of these
6) asctime()
7) bin()
8) FALSE
9) TRUE
10) C. minimum()
TERMINAL QUESTIONS:
Answer 1:
Epoch in Python corresponds to the measurement of time starting from January 1, 1970.
Answer 2:
A list of indexes is returned for the days of the week by iterweekdays() method.
Answer 3:
from datetime import date
Page | 26
Python Programming Unit 12
Answer 4:
import datetime
print(datetime.date(2021, 3, 15).isocalendar()[1])
Answer 5:
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)
print('Yesterday was : ',yesterday)
print('Today is : ',today)
print('Tomorrow will be : ',tomorrow)
Answer 1:
import datetime
print(datetime.datetime.now().time())
Answer 2:
def leap(y):
if y % 400 == 0:
return True
if y % 100 == 0:
return False
if y % 4 == 0:
return True
else:
return False
print(leap(1921))
print(leap(2004))
Answer 3:
l = [1, 2, 3, 0]
print(any(l))
l = [0, True]
print(any(l))
Page | 27
Python Programming Unit 12
l = [0, False, 4]
print(any(l))
l = []
print(any(l))
Answer 4:
x = False
print(bool(x))
x = True
print(bool(x))
x=4
y=5
print(bool(x==y))
x = None
print(bool(x))
x = ()
print(bool(x))
x = {}
print(bool(x))
x = 0.0
print(bool(x))
x = 'Python'
print(bool(x))
Answer 5:
str1 = 'HelloWorld'
Page | 28
Python Programming Unit 12
BOOKS:
E-REFERENCES:
• Python Built-in functions with syntaxs and exmaples, last viewed on April 2, 2021 <
https://www.w3schools.com/python/python_functions.asp >
• Python programming and function argument, last viewed on March 29, 2021
https://www.programiz.com/python-programming/function-argument \
Page | 29
Python Programming
Unit 13
Database Connectivity
Table of Contents
13.1 Introduction
Learning Objectives
13.2 Python SQL
13.2.1 Environmental Setup
13.2.2 Install mysql.connector
Self-Assessment Questions
13.3 Creating the Connection
13.3.1 Creating Cursor Object
Self-Assessment Questions
13.4 Fetching the Data
13.4.1 Creating the Table
13.4.2 Alter Table
Self-Assessment Questions
13.5 Insert Operations
13.5.1 Read Operation
13.5.2 Update Operation
13.5.3 Join Operation
Self-Assessment Questions
13.6 Summary
13.7 Glossary
13.8 Case study
13.9 Terminal Questions
Answer Keys
A. Self Assessments Questions
B. Terminal Questions
13.10 Suggested Books and e-References
Page | 1
Python Programming Unit-13
13.1 INTRODUCTION
In the past units of the book, you learned how to work with Python and its basic
concepts. You learned how to solve different problems using Python and how to use the
various features and functions offered by Python. However, to ensure that the immense
capability of Python is completely utilized, you need to use it for website development.
Programmers find Python a handy and powerful tool when they require a strong base
for web development.
To make use of Python in real life, you will need to learn to manage data in Python. The
code that you program using the language should be able to accept a large amount of
data, process it and show the result in a comprehensible and dynamic form. When it
comes to the web, a programmer needs to manage data to offer any service. Take an
example of an emailing website. When users access the website, they will have to
provide their User ID or Email ID along with a unique password. The code should be
able to verify if the credentials match the ones that were recorded previously.
This previously recorded data should be arranged in the form of a database. The
database ensures that the entire information essential for the working of the website is
well-arranged and formatted. This increases the accessibility of the data stored in it as
well as the functionality of the website.
What is data? Data is arranged information. It eases the computation and efficiency of
the computer. A database is an organized collection of data, usually arranged in rows
and columns that can be easily accessed, assessed, and managed. Its primary function is
to store large data, retrieve it as per instructions, and manage it. There are various
software available which helps you create and maintain data such as MySQL, Sybase,
Oracle, Informix and more.
Here are some of the terms that you should be aware of before diving deeper into the
unit. These are common terms used when referencing data and database.
SQL: Structured Query Language comprises commands that are used to manipulate and
operate the data stored in the database. It depends upon relational algebra and tuple
relational calculus.
Python Database API: It is the standard way through which you can define how
different Python modules can be used to access databases.
Page | 2
Python Programming Unit-13
Through Python Database API, you can easily understand the working of the modules,
how to port code across different databases and simplify the process of database
connectivity in Python. Here is a list of sections that comprise the Python Database API
interface.
STUDY NOTE
• Module Interface
• Connection Objects There are various database
• Cursor Objects servers supported by Python.
MySQL is used more commonly
• Type Objects and Constructors for its varied advantages.
• Implementation Hints
Table: When working with a database, a table looks like a spreadsheet and acts as a
matrix with data.
Column: A column contains the same kind of data. It is also called a data element.
Row: It is a group of related data. One can refer to it as a tuple, entry, or data.
Primary key: A key value is something that does not occur twice in the table. It is
unique.
Compound Key: A compound key consists of multiple columns as defining one column
is not unique.
Index: An index is the list of all data and topics present in the database.
Referential integrity: It ensures that a foreign key always points to an existing row.
Page | 3
Python Programming Unit-13
LEARNING OBJECTIVES
After studying the chapter, you will be able to:
Page | 4
Python Programming Unit-13
What is MySQL?
It is an RDBMS with a multitude of features. You can create multiple related tables in a
database using MySQL. Being open-source software, it
can be downloaded freely and customised as per your
needs. It has built-in support for languages such as STUDY NOTE
Python and PHP. It offers an efficient security system and MySQL is developed and
consists of a thread-based memory allocation system. maintained by a company
There is no risk of memory leakage with MySQL. It can called MySQL DB.
also hold large databases with efficiency.
You can integrate MySQL database in Python using the module names MySQL Connector
Python. Using the MySQL database server, you can develop and integrate Python
applications. There are various other modules that one can choose as per their
requirements such as PyMySQL, MySQL DB, OurSQL, and more. Among the various
available options, we will choose to continue with MySQL Connector. Note that the
syntax, method, and ways of accessing the database are some of the factors that are the
same for all the modules. This is because they are designed to adhere to the regulations
of Python Database AP V2.0.
There are various benefits of choosing the module MySQL Connector Python over
others for its better support and efficiency. These benefits are listed below.
• MySQL Connector Python is coded in Python and can execute queries through
Python seamlessly.
• MySQL Connector Python and frequently updated and maintained for the best
experience and result.
The system requirements for Python MySQL are similar to that of Python. By now, you
must have set up Python on your system. To access the MySQL database, the first
requirement for Python is to download a MySQL driver. Here, we are using MySQL
Connector as the driver. To download it, you will need PIP.
PIP is pre-installed with the Python package and will be readily available for use. You
will need root or administrative access to begin the installation process. MySQL
Connector needs to be in the system’s path. Unless it can find Python on your system, it
will not install.
Page | 5
Python Programming Unit-13
The steps that are provided below to install Python MySQL Connector are applicable for
the following specifications.
MySQL Connector can be installed in various ways and methods. These are explained in
detail below.
You can also mention the version of the module in the command line if you are facing
any issues while downloading the module. The command with version will be as
provided below.
Once the command is run, you will need to verify that MySQL Connector Python has
been successfully installed. You can do this by checking the following messages that
appear on the command window.
STUDY NOTE
Connecting mysql – connector – python.
Downloading packages. Oracle acquired Sun
Microsystems and MySQL in
Requirement already satisfied: setup tools in D: 2010. MariaDB was created
python\python 37-32\lib\site – packages with MySQL code after its
acquisition to keep it free.
Installing collected packages: mysql – connector – python.
Successfully installed mysql – connector – python – 8.0.13.
Page | 6
Python Programming Unit-13
You can also download older versions that are compatible with your device from the
website at which you land when you click on the link provided below.
Click on the download button to save the ZIP file on your system.
Unzip the zip archive in the directory of your choice. You can use any tool for this
process.
Start a console window and change the location to the folder or directory where you
unzipped the Zip archive.
Use the command provided below to begin installation inside the MySQL Connector
Python folder.
Here, we have considered that the zip file is saved in the C drive of the system. Now,
your screen should look like the one shown in the image below.
Source: Pynative
Page | 7
Python Programming Unit-13
You can choose the version of the TAR archive as per the specifications of your system.
Once the download is complete, you will need to follow the steps provided below to
install the module.
Now, execute the command provided below to install the module on Linux.
Firstly, download the source code for macOS from the link
https://dev.mysql.com/downloads/connector/python/.
Install the module by opening the downloaded file and double-clicking on the .pkg file.
If the above code does not work, then you can proceed by downloading the Source Code
form https://dev.mysql.com/downloads/connector/python/ link.
You will get two DEB packages. Download them both and unpack them. To install them,
use the code provided below.
Page | 8
Python Programming Unit-13
When you run both these commands one after the other, the MySQL Connector Python
will install on Ubuntu.
To test if the installation was successful, you can run the command provided below.
Import mysql.connector
If the code runs without any errors, then you have the module installed on your system.
ACTIVITY 1
Try installing the MySQL Connector Python Module in different environments.
Compare their user interface and other surficial features. Note how changing the
environment can affect the working of the module.
SELF-ASSESSMENT QUESTIONS
1. For the Ubuntu environment, you will need to download the source code having
the extension __________.
2. __________ command can be used to verify that the MySQL Connector Python
module is successfully installed in the system.
3. Which of the following is the easiest way to download the module for MySQL
Connector Python?
4. 5. The MySQL Connector Python module is usually already available with the
Python package. (True/False)
You cannot download MySQL Connector Python without Python already installed
in the environment. (True/False)
Page | 9
Python Programming Unit-13
The first step after downloading the module is to establish the connection between the
database. You can create the database using the create command in the command
prompt. This command comes with the MySQL module and is built-in. Here is an
example.
#mysqladmin create Employee
You can also create a database using Python with the help of the code provided below.
import mysql.connector
db1 = mysql.connector.connect (
host = “localhost”,
user = “myusername”,
password = “mypassword”
)
mycursor = db1.cursor ()
mycursor.execute (“CREATE DATABASE mydatabase”)
In this code, you will find a cursor method. This will be explained in detail later in the
unit.
To create a connection with an existing database, here is the code that you will need to
type on your Python window.
import mysql-connector
mydatabase = mysql.connector.connect (
host = “localhost”,
user = “myname”,
password = “mypassword”
)
print (mydatabase)
Here, the name of the database is mydatabase. The username is myusername and the
password is mypassword. We are using the constructor connect () that accepts
username, password, host, and the name of the password. It will return an object of the
MySQL Connection class.
You can disconnect the database using the exit command in the mysql prompt. This is
applied as follows.
mysql> exit
Page | 10
Python Programming Unit-13
Or, you can close the connection through the Python window by adding the code
provided below.
mydatabase.close ()
You can create a cursor object using the cursor () method that is built-in in the MySQL
Connector Python module. The cursor objects are used to process and analyse
individual rows returned by database system queries. Through the cursor, you can
manipulate the whole result set at once. The code to create a cursor object using Python
is provided below.
import mysql.connector
conn = mysql.connector.connect (
host = “localhost”,
user = “myusername”
password = “mypassword”
database = “db1”
)
cursor = conn.cursor ()
Page | 11
Python Programming Unit-13
SELF-ASSESSMENT QUESTIONS
In this section, we will learn the basics of manipulating with database in MySQL using
Python. If a database already exists, using few code lines, you can fetch the data present
in the database. This can be done by either retrieving rows or columns of the table. You
can also specify the data that you want to retrieve using queries such as WHERE.
Go through the code provided below. This code fetches the data present in a table using
the query SELECT. Note that all the queries are written in all caps. The code uses the
method fetchall () to retrieve all the rows from a MySQL table.
import mysql.connector
conn = mysql.connector.connect (
host = “localhost”,
user = “myusername”,
password = “mypassword”,
database = “db1”
)
my_database = conn.cursor ()
sql_table = “SELECT * FROM EMPLOYEE”
my_database.execute (sql_table)
output = my_database.fetchall ()
Page | 12
Python Programming Unit-13
for x in output:
print (x)
Here, the execute () method is used to execute the MySQL query. The variables retrieved
by the SELECT query have been saved in the variable sql_table. The result set is saved as
a list of tuples with the help of fetchall ().
To create a table in MySQL, you use the CREATE query. Through Python, we will use this
query and create a new table in our database. The code to form a new table in the
database is provided below. Ensure that the name of the database has been defined
while forming the connection with it.
import mysql.connector
db1 = mysql.connector.connect (
host = “localhost”,
user = “myusername”,
password = “mypassword”,
database = “my_database”
)
mycursor = db1.cursor()
mycursor.execute (“ CREATE TABLE employee (name VARCHAR (200), address
VARCHAR (200))”)
The code creates a table called employee in the database named db1. The table contains
two columns, one will store the names of the employees and the other will store the
address. Note that the data type for these two columns is set to be VARCHAR, which is a
character string with a length of 200 bits.
You should also create a primary key while creating a table. The primary key is a
column with a unique key for each record. The example to create a primary key has
been provided with the code below.
import mysql.connector
db1 = mysql.connector.connect (
host = “localhost”,
user = “myusername”,
password = “mypassword”,
database = “my_database”
)
mycursor = db1.cursor()
mycursor.execute (“ CREATE TABLE employee (id INT AUTO_INCREMENT PRIMARY
KEY, name VARCHAR (200), address VARCHAR (200))”)
Here is a list of data types available in MySQL that can help you create various tables
that can store different type of data.
Page | 13
Python Programming Unit-13
Page | 14
Python Programming Unit-13
ALTER query is used to change an existing table. When working in MySQL, you can
simply apply the query and add a column to the table. An example is shown below.
ALTER TABLE employee MODIFY COLUMN address VARCHAR (255).
Thus, the length of the string that could be stored in the address column is changed
from 200 to 255. In Python, this code will be as shown below.
import mysql.connector
db1 = mysql.connector.connect (
host = “localhost”,
user = “myusername”,
password = “mypassword”,
database = “my_database”
)
mycursor = db1.cursor()
mycursor.execute (“ ALTER TABLE employee ADD COLUMN id INT AUTO_INCREMENT
PRIMARY KEY”)
The program above will add a column for the primary key in the table employee.
STUDY NOTE
rollback () method is used to
roll back a database to a
pending transaction and start
again.
Page | 15
Python Programming Unit-13
SELF-ASSESSMENT QUESTIONS
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
Page | 16
Python Programming Unit-13
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print (mycursor.rowcount, "record inserted.")
You can insert multiple rows into a table using the method executemany(). You will
need to provide parameters such as a list of tuples with the method. The list should
contain the data that you want to insert.
To read values saved in the database, the SELECT query is used. There are various
methods in Python that return the data stored in the table. These methods include
fetchall () and fetchone (). These methods are already discussed above. You can use the
SELECT query to select a complete table, some columns from the table, or only a row.
Here is an example using the fetchone() method to return only one row.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
To select data from a table, one can apply the filter using the WHERE filter. Here is what
the command will be like when using the query.
Page | 17
Python Programming Unit-13
Through UPDATE operation, the databases can be updated. You can update specific
rows using the WHERE clause.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
To retrieve data that has been divided into two tables, the JOIN operation is used. The
working of the operation has been depicted through the program provided below.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
INNER JOIN only retrieves values that match in both the tables. If you need to retrieve
all the values, then you can use LEFT JOIN and RIGHT JOIN statement.
Page | 18
Python Programming Unit-13
SELF-ASSESSMENT QUESTIONS
16. ___________ clause is used to specify the row from where a data is to be
manipulated.
18. Which of the following operation is used to retrieve data from more than one
table at a time?
A. JOIN
B. SELECT
C. FIND
D. ALL TABLES
19. To add a new row into an existing table, which operation is used?
A. ADD
B. UPDATE
C. INSERT
D. JOIN
20. Data from two separate tables can be combined using MySQL Connector
Python. (True/False)
Page | 19
Python Programming Unit-13
13.6 SUMMARY
• Databases are a way one can manage, structure, and organise a large amount of
data.
• When a DBMS retrieves information by using the data in the table, then it is
called a relational database management system (RDBMS).
• Python Database API is the process through which different modules can access
databases.
• MySQL comes with the Python package. However, it can be installed separately
as well.
• Various other commands can be used to access, modify, and manage the tables in
the database. These include creating, select, insert, update, delete, and others.
• One can use various data types in MySQL. These are Numeric, Decimal, Int,
Smallint, Float, Real, Double Precision, DateTime, Date, TimeStamp, Time, Year,
Char, Varchar, and Text.
• cursor () method returns a new cursor object and represents a database cursor.
• Various methods can be used in Python to extract records from the result set.
These are execute (), executemany (), fetchone (), and fetchall ().
13.7. GLOSSARY
MySQL: An RDBMS that can be integrated with Python to manage and create a database.
Page | 20
Python Programming Unit-13
Query: Commands used in MySQL to manipulate and manage the data in the database.
Creating the
Alter table
table
Fetching the
data
Environmen Install
tal Setup mysql.conn
ector
Creating a
Database
cursor object
Connectivity
Python SQL
Creating a
Operations in connection
MySQL Python
Page | 21
Python Programming Unit-13
A school is set to begin an online registration process to keep track of all the
students that are or will be enrolled in the school. The students will be able
to access an online registration form that receives their basic information
such as name, date of birth, name of guardians, permanent address, current
address, enrolment number, blood group, etc.
New students can fill in all this information. The form is created such that
students can update and alter the details that they previously entered. Such
that, someone’s current address has changed, so they can change the address
in the form and update their information in the database.
Consider yourself a part of the technical team that has been set to code the
registration form. You will need to create identify the elements of the table
that are needed to be stored as registration details. Next, you will need to
connect to the database and create a table. The code created should be able
to store the information entered by the students in the respective columns of
the tables. Also, alterations and modifications should be allowed in the table.
The primary key for each student will be their enrolment number. It is
unique for each student admitted into the school. Once the table has been
coded and created, you need to verify the data stored in the database.
Based on the information provided and the tasks needed to execute the
project, answer the questions provided below.
Source: IndiaNic.com
Questions:
1. What will be the columns that you will use as different keys needed in
a database?
2. How will you proceed with the verification of data stored in the
database?
Page | 22
Python Programming Unit-13
Q1. Write the steps to install mysql.connector using source code in a Windows
environment.
Q2. How can you modify the rows of an existing table using MySQL Connector
Python?
Q3. Write a Python program to delete a row from a table.
Q4. What are the data types available in MySQL? Describe them.
Q5. Write a Python program to retrieve required data from a table.
Q1. Write a Python program to connect to the database driver and print its version.
Q2. Write a Python program to create a database connection to a database that
already resides in the memory.
Q3. Write a Python program that fetches information regarding the name of the
hospital and doctor using hospital ID and doctor ID in a table containing such
information.
Q4. Write a Python program that gives a list of doctors as per their speciality.
Q5. Write a Python program that updates the number of years of experience of a
doctor in the table.
ANSWERS
1. DEB
2. import mysql.connector
3. B. pip method
4. True
5. True
6. cursor ()
7. Host, username, and password.
8. Statement
9. True
10. False
11. Query
12. Primary Key
13. B. ALTER
14. A. TEXT
15. True
16. WHERE
17. commit ()
18. A. JOIN
Page | 23
Python Programming Unit-13
19. C. INSERT
20. True
TERMINAL QUESTIONS
Answer 1: Here are the steps to install MySQL Connector Python to Windows.
Download the ZIP file of the source code on your system.
Unzip the zip archive in the directory of your choice.
Start a console window and change the location to the folder or directory where you
unzipped the Zip archive.
Use the command provided below to begin installation inside the MySQL Connector
Python folder.
C:\> python setup.py install.
Answer 2: To modify the rows in the table of a database, one can use the ALTER query.
One will need to define the name of the table, the name of the row, and the data that
needs to be changed.
Answer 4: There are various data types one can use in MySQL for variables. These are
explained in the table below.
Page | 24
Python Programming Unit-13
Answer 1:
import mysql.connector
def get_connection():
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')
return connection
def close_connection(connection):
if connection:
connection.close()
def read_database_version():
try:
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT version();")
db_version = cursor.fetchone()
print ("You are connected to MySQL version: ", db_version)
close_connection(connection)
except (Exception, mysql.connector.Error) as error:
print ("Error while getting data", error)
Answer 2:
import mysql.connector
try:
mysql_Connection = mysql.connector.connect('temp.db')
Page | 25
Python Programming Unit-13
Answer 3:
import mysql.connector
def get_connection():
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')
return connection
def close_connection(connection):
if connection:
connection.close()
def get_hospital_detail(hospital_id):
try:
connection = get_connection()
cursor = connection.cursor()
select_query = """select * from Hospital where Hospital_Id = %s"""
cursor.execute(select_query, (hospital_id,))
records = cursor.fetchall()
print ("Printing Hospital record")
for row in records:
print ("Hospital Id:", row [0], )
print ("Hospital Name:", row [1])
print ("Bed Count:", row [2])
close_connection(connection)
except (Exception, mysql.connector.Error) as error:
print ("Error while getting data", error)
def get_doctor_detail(doctor_id):
try:
connection = get_connection()
Page | 26
Python Programming Unit-13
cursor = connection.cursor()
select_query = """select * from Doctor where Doctor_Id = %s"""
cursor.execute(select_query, (doctor_id,))
records = cursor.fetchall()
print ("Printing Doctor record")
for row in records:
print ("Doctor Id:", row [0])
print ("Doctor Name:", row [1])
print ("Hospital Id:", row [2])
print ("Joining Date:", row [3])
print ("Specialty:", row [4])
print ("Salary:", row [5])
print ("Experience:", row [6])
close_connection(connection)
except (Exception, mysql.connector.Error) as error:
print ("Error while getting data", error)
Answer 4:
import mysql.connector
def get_connection():
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')
return connection
def close_connection(connection):
if connection:
connection.close()
Page | 27
Python Programming Unit-13
Answer 5:
import mysql.connector
import datetime
from dateutil.relativedelta import relativedelta
def get_connection():
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')
return connection
def close_connection(connection):
if connection:
connection.close()
def update_doctor_experience(doctor_id):
try:
connection = get_connection()
cursor = connection.cursor()
select_query = """select Joining_Date from Doctor where Doctor_Id = %s"""
cursor.execute(select_query, (doctor_id,))
joining_date = cursor.fetchone()
joining_date_1 = datetime.datetime.strptime(''.join(map(str, joining_date)), '%Y-
%m-%d')
today_date = datetime.datetime.now()
experience = relativedelta(today_date, joining_date_1).years
connection = get_connection()
cursor = connection.cursor()
sql_select_query = """update Doctor set Experience = %s where Doctor_Id =%s"""
cursor.execute(sql_select_query, (experience, doctor_id))
connection.commit()
print ("Doctor Id:", doctor_id, " Experience updated to ", experience, " years")
close_connection(connection)
Page | 28
Python Programming Unit-13
Books:
• Python Tutorials and Sample Programs, last viewed on March 25, 2021, <
https://www.w3schools.com/python/ >
Page | 29
Python Programming
Unit 14
Packages in Python
Table of Contents
14.1. Introduction
Learning Objectives
14.2. Pandas Package
14.2.1. Use Of Pandas Package
14.2.2. Import Into Python
14.2.3. Pandas.Series
14.2.4. Pandas.Dataframe
14.2.5. Pandas.Panel
14.2.6. Descriptive Statistics
Self-Assessment Questions
14.3. Matplotlib Package
14.3.1. Use Of Matplotlib Package
14.3.2. Import Into Python
14.3.3. Simple Plot
14.3.4. Bar Plot
14.3.5. Histogram
Self-Assessment Questions
14.4. Django Package
14.4.1. Use Of Django Package
14.4.2. Import Into Python
14.4.3. Apache In Django
14.4.4. Django Form Processing
14.4.5. Cookies
14.4.6. Sessions
Self-Assessment Questions
14.5. Summary
14.6. Glossary
14.7. Case Study
14.8. Terminal Questions
Answer Keys
A. Self-Assessments Questions
B. Short Answers Questions
14.9. Suggested Books And E-References
Page | 1
Python Programming Unit 9
9.1. INTRODUCTION
In Python programming so far, you have been introduced to the basics of the
programming language. You have learned how to define and use variables and functions,
the various operations and coding parameters applicable in programming, and how to use
conditions to direct the program flow. The conditional statements (if and else) and loops
(for and while) are used to set parameters to perform specific functions based on the
given conditions. You learned about the various data types that provide a construct to
store data and make accessing them more efficient. These data structures may be mutable
(list, dictionary, set) or immutable (string, tuple, range, etc.).
In the more recent units, you also learned about the different types of errors that arise
during programming. If there is an error during program execution, Python throws a
message known as an exception. Common errors like NameError or IndentationError
can be resolved through simple changes in the code. However, logical or run-time errors
are more difficult to detect. Programmers use the process of exception handling to test
potential error and provide code to handle them.
In this unit, you will learn about the packages used in Python. As an application program
size grows, it becomes more difficult to manage all the files we need to access. For
efficient file organisation, we use packages in Python. A Python package can be
understood as a set of directories and modules of files.
A module is any file that contains Python statements and definitions. We use modules to
divide large programs into small manageable and organized files. Saving code in modules
also allows a programmer to reuse them in different programs. Defined functions that are
used often can simply be store in modules and imported into a program by using the
import keyword. In packaging, similar modules are placed under one package and
different modules are placed under different packages.
Page | 2
Python Programming Unit 9
LEARNING OBJECTIVES
At the end of this unit, you will be able to:
❖ Use and import the Pandas package in Python. Use the pandas.Series, pandas.Dataframe,
pandas.Panel classes. Use Pandas in descriptive statistics.
❖ Use and import the Matplotlib package in python. Use Matplotlib package in making a
simple plot, bar plot, and histogram.
❖ Use and import the Django package in python. Use Apache, Sessions and Cooking, along
with form processing inDjango.
Page | 3
Python Programming Unit 9
Pandas is an open-source Python package or library that provides fast, flexible, and
expressive data structures that help in efficient data manipulation and analysis. Before
Pandas, Python was mostly used for data munging and preparation. It had nothing to do
with data analysis. In 2008, Wes McKinney started developing
Pandas with the intention to provide high performance, flexible STUDY NOTE
tools for data analysis.
A directory must have a
file with the name
Packages contain modules that are used to simplify and divide
"__init__.py".
large programs into small manageable files. The Pandas library
architecture consists of the following modules:
Another open-source package that is similar to Pandas is the NumPy package. Unlike
Pandas which works on tabular data, NumPy provides multi-dimensional array-oriented
computing functionalities designed for high-level mathematical functions and scientific
computation. NumPy stores similar data (integers) in the form of homogeneous
multidimensional arrays.
The five typical steps in the processing and analysis of data--load, prepare, manipulate,
model, and analyze--can be achieved through Pandas. Data
analysis is a crucial part of many industries. Python with
STUDY NOTE
Pandas is used in a wide range of academic and commercial
fields like finance, economics, statistics, analytics, etc. The word “Pandas” is
derived from the term
One of the most essential uses of Pandas is in data analysis. “panel data” which is a
The Pandas library can handle huge sets of data. It helps users econometrics term for
analyse them easily by providing the tools to clean and filter data sets.
data. Some of the sectors that use Pandas for data analysis
include--economics ( to find trends and similarities), statistics
( to perform various statistical operations), web analysis (to read and analyze the traffic
of a website), etc.
Page | 4
Python Programming Unit 9
The Pandas library is also used in Machine Learning as it helps to provide data for a
model to learn and predict results. In financing, machine learning is used to predict stocks
(Pandas is used to handle data of previous stock market dealings). Machine learning also
contributes to Natural Language Processing (NLP) that is used to understand the human
language and its intricacies.). Using the functions and features in Pandas, programmers
can also manipulate data that are present in datasets. Other features of Pandas package
include:
As Pandas is a third-party library, the standard Python distribution does not come with
an in-built Pandas package. To use the Pandas package, users have to install it into the
Python directory.
Handling ImportError
Users may sometimes encounter an ImportError when trying to access the Pandas library.
Python internally has a list of directories it searches through, to find packages. However,
if users have multiple Python installations on their system, they may need to check if they
are using the installation with the Pandas library installed in it. Users can do this by
running "which python" on their terminal.
14.2.3. PANDAS.SERIES
Series is defined as a one-dimensional array that is capable of storing data of any data
type (integer, float, string, etc.). The elements or values of a Pandas series are mutable
(can be changed), however, the size of a series cannot be changed. All the elements in a
Page | 5
Python Programming Unit 9
series are indexed, where the first element has the index "0". A Pandas series is created
using the following syntax and parameters:
Output:
Series([], dtype: float64)
If a data is of type ndarray, the index passed must be of the same length as the data. If no
index is passed, the default index will be range(n), where n is the length of the array.
Output:
0p
1b
2q
3d
dtype: object
The NumPy library is often used along with the Pandas library as they are both very
useful for scientific computing with Python.
Page | 6
Python Programming Unit 9
We can access the data in a series based on the in-built index as follows:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5],index = ['a','b','c','d','e'])
Output:
4
# Range of elements
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5],index = ['a','b','c','d','e'])
Output:
c3
d4
dtype: int64
The index labels given to the series elements can be used as follows:
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
Output:
4
# multiple elements
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
Output:
a1
c3
d4
dtype: int64
Page | 7
Python Programming Unit 9
14.2.4. PANDAS.DATAFRAME
A pandas DataFrame is
pandas.DataFrame( data, index, columns, dtype, copy) created by using Lists, dict,
Series, Numpy ndarrays, or
• data - Can be of various forms like ndarray, series, map, another DataFrame as input.
lists, dict, constants and also another DataFrame.
• index - For the row labels, "np.arrange(n)" is passed by
default if no index is passed.
• columns - For column labels, "np.arrange(n)" is passed by default if no index is
passed.
• dtype - The data type of each column.
• copy - Command used for copying data. It is "False" by default.
import pandas as pd
df = pd.DataFrame()
print (df)
Output:
Empty DataFrame
Columns: []
Index: []
>
To create this type of Dataframe, all the arrays must be of the same length and the index
(if passes) should be the same length as arrays.
Output:
Name Age
0 Tommy 28
1 Jill 34
2 Stone 29
3 Nicky 42
Page | 8
Python Programming Unit 9
# by passing index
import pandas as pd
d = {'Name':['Tommy', 'Jill', 'Stone', 'Nicky'],'Age':[28,34,29,42]}
df = pd.DataFrame(d, index=['rank1','rank2','rank3','rank4'])
print (df)
Output:
Name Age
rank 1 Tommy 28
rank 2 Jill 34
rank 3 Stone 29
rank 4 Nicky 42
Selecting a Column
import pandas as pd
Output:
a 1.0
b 2.0
c 3.0
d NaN
Name: One, dtype: float64
>
# adding a column
import pandas as pd
df = pd.DataFrame(d)
# Adding a new column to an existing DataFrame object with a column label by passing
new series
Page | 9
Python Programming Unit 9
print (df)
Output:
Adding a new column by passing a Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
# deleting a column
# delete a column using the del function
import pandas as pd
df = pd.DataFrame(d)
print ("Our dataframe is:")
print (df)
Output:
Our dataframe is:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Page | 10
Python Programming Unit 9
c 3 30.0
d 4 NaN
df = pd.DataFrame(d)
print (df.loc['c'])
Output:
one 3.0
two 3.0
Name: c, dtype: float64
The iloc() function can be used to pass an integer location to select a row.
Example:
print (df.iloc[2])
The ':' operator is used to select multiple rows where the index values are passed.
Example:
print (df[2:4])
The append() function can be used to add new rows to the Dataframe. The row is
appended at the end.
Example:
df = df.append(df2)
print (df)
The drop() function is used to delete rows by using the label index. If multiple rows have
the same label index, all these rows are deleted.
Example:
df = df.drop(0)
print (df)
14.2.5. PANDAS.PANEL
A Panel is a three-dimensional data structure. The 3 axes that are used to give a Panel a
semantic meaning to describing operations are:
Page | 11
Python Programming Unit 9
# from ndarray
import pandas as pd
import numpy as np
data = np.random.rand(2,4,5)
p = pd.Panel(data)
print (p)
Output:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
By Using Item
import pandas as pd
import numpy as np
Output:
0 1 2
0 0.488224 -0.128637 0.930817
1 0.417497 0.896681 0.576657
2 -2.775266 0.571668 0.290082
3 -0.400538 -0.144234 1.110535
Page | 12
Python Programming Unit 9
In the above code, we have two items and we retrieved one of them. The result is a
DataFrame with 4 rows and 3 columns, which are
the Major_axis and Minor_axis dimensions.
By Using major_axis
import pandas as pd
import numpy as np
p = pd.Panel(data)
print (p.major_xs(1))
Output:
Item1 Item2
0 0.417497 0.748412
1 0.896681 -0.557322
2 0.576657 NaN
By Using minor_axis
import pandas as pd
import numpy as np
p = pd.Panel(data)
print (p.minor_xs(1))
Output:
Item1 Item2
0 -0.128637 -1.047032
1 0.896681 -0.557322
2 0.571668 0.431953
3 -0.144234 1.302466
Page | 13
Python Programming Unit 9
take an axis argument, similar to ndarray.{sum, std, ...}, however, the axis can be specified
by name or integer.
For this section, we will be using the descriptive statistics methods on the following
Dataframe:
import pandas as pd
import numpy as np
#Create a DataFrame
df = pd.DataFrame(d)
print (df)
Sum() - Returns the sum of the values for the requested axis.
print df.sum(1)
STUDY NOTE
Output:
'include' is the argument
0 29.23 used to pass information
1 29.24 regarding what columns need
2 28.98 to be considered for
3 25.56 summarizing (object, number,
4 33.20 all).
5 33.60
6 26.80
7 37.78
8 42.98
9 34.80
10 55.10
11 49.65
dtype: float64
Column 2 is added.
print df.mean()
Output:
Age 31.833333
Rating 3.743333
dtype: float64
Page | 14
Python Programming Unit 9
The describe() function gives a summary of the statistics related to the Dataframe
columns. It gives the mean, std and IQR values.
Other Functions:
Function Description
count() Number of non-null observations
median() Median of Values
mode() Mode of values
std() Standard Deviation of the Values
min() Minimum Value
max() Maximum Value
abs() Absolute Value
prod() Product of Values
cumsum() Cumulative Sum
cumprod() Cumulative Product
SELF-ASSESSMENT QUESTIONS
3) The ____________ library is often used along with the Pandas library as they
are both very useful for scientific computing with Python.
Page | 15
Python Programming Unit 9
ACTIVITY 1
Create a Dataframe that have the following attributes of diamonds: price, carat,
cut, colour, clarity, length, width, and depth. Write a Python program to rename
two of the columns and remove the second column of the diamonds Dataframe.
The matplotlib is one of the most famous Python packages used for data visualisation. It is
a cross-platform library used to make 2D plots from array data. Matplotlib has an
interface known as Pylab that has been designed to resemble the MATLAB programming
language.
Matplotlib was originally written by John D. Hunter in 2003 and offers an object-oriented
API that helps to embed plots in applications that use Python GUI toolkits, such as PyQt,
and WxPythonotTkinter.
Matplotlib and its related packages (available in the form of wheel packages) can be
installed into Python by using the pip package manager.
STUDY NOTE
pip install matplotlib
If a single list or array is
provided to the plot()
Once it is installed, it can be imported into Python as shown: command, matplotlib
automatically assigns it to the
import matplotlib.pyplot as pt y-axis.
The module we wish to import can be specified by appending ".pyploy" to matplotlib. The
library is abbreviated to "pt" for easier use.
Page | 16
Python Programming Unit 9
The matplotlib.pyplot is a collection of functions that help matplotlib work like MATLAB.
Each function in the pyplot brings changes in the plot. Let us see how a simple plot is
created using matplotlib through an example.
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
Output:
Source:geeksforgeeks.org
The lines in a simple plot have many attributes that can be changed such as line width,
colour, shape, etc. The easiest way to do this is by using keyword arguments as shown:
Page | 17
Python Programming Unit 9
You can set multiple properties of a line by using the MATLAB style set() command.
Method Description
plot() Creates a plot in the background but does not display it.
show() displays the created plot
xlabel() labels x-axis
ylabel() labels y-axis
title() gives title to the plot.
gca() helps to get access over all the four axes.
gca().spines[‘right/left/top/bottom’]. helps to access the individual boundaries and helps to
set_visible(True/False) change their visibility.
xticks() decides how marking should be made on the x-axis.
yticks() decides how marking should be made on the y-axis.
annotate() used to write commands at specified positions on the
graph.
subplot(r, c, i) used to create multiple plots in the same figure with 'r'
signifies the no of rows in the figure, 'c' signifies no of
columns in a figure and 'i' specifies the positioning of the
particular plot.
A bar graph or plot is used to present and compare data in discrete categories. The
matplotlib API provides the bar() function that can be used in MATLAB as well as the
object-oriented API format. The bar() function is used in the format and parameters:
Example:
Page | 18
Python Programming Unit 9
import numpy as np
import matplotlib.pyplot as plt
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
plt.show()
Output:
Source: geeksforgeeks.org
Fig 2: Simple Bar Plot
import numpy as np
import matplotlib.pyplot as plt
Page | 19
Python Programming Unit 9
X = np.arange(4)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25)
ax.bar(X + 0.25, data[1], color = 'g', width = 0.25)
ax.bar(X + 0.50, data[2], color = 'r', width = 0.25)
Output:
Source: tutorialspoint.com
Fig 3: Multiple Bar Plots in One
The above example shows a series of four bar plots with three values each. Each bar has a
thickness of 0.25 units and each bar chart is shifted 0.25 units away from the previous
one. The plot has bars of one color for one quantity value.
14.3.5. HISTOGRAM
A histogram is a type of bar graph that presents an accurate
STUDY NOTE
representation of numerical data. It is used to show an
estimate of the probability distribution of a continuous The bins are usually
variable. specified as consecutive,
non-overlapping intervals of
To build a histogram, first, you need to Bin the range of a variable.
values. Divide the range into a series of intervals, and then
count how many values fall into each interval. A histogram is plotted with the help of
Page | 20
Python Programming Unit 9
the matplotlib.pyplot.hist() function. The function computes and draws the histogram
of x.
Parameter of a histogram:
x - Array(s)
bins - integer or sequence or ‘auto’, optional
Example of a histogram:
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
a = np.array([22, 87, 5, 43, 56,
73, 55, 54, 11,
20, 51, 5, 79, 31,
27])
# Creating histogram
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 25, 50, 75, 100])
# Show plot
plt.show()
Output:
Source: geekforheeks.com
Fig 4: A Histogram
Page | 21
Python Programming Unit 9
ACTIVITY 2:
Create a bar plot that shows scores by group and gender. Use different x values for
men and women in the same chart.
SELF-ASSESSMENT QUESTIONS
11) ________ function offers a patches object which gives us access to the
properties of the created objects.
12) Matplotlib and its related packages can be installed into Python by
using the ________ package manager.
14) The pyplot.bar() function allows you to specify a starting value for a
bar. [True/False]
15) Which parameter in a bar plot represent the y-coordinate of the bars.
Page | 22
Python Programming Unit 9
Django's basic role is to ease the process of creating complex database-driven websites. It
provides a bridge between the data model and the database engine. It supports a vast
collection of database systems like MySQL, Postgres, Oracle, etc. Its built-in
internationalization system also supports multilingual websites.
STUDY NOTE
Django has a built-in for frameworks like Ajax, RSS, Caching, etc.
The hist() function offers and also provide an easy-to-use user interface for
a patches object which administrative activities. Users can also develop and test their
gives us access to the applications as Django comes with a lightweight web server.
properties of the created
objects.
easy_install pip
Page | 23
Python Programming Unit 9
This will create a project named "myproject" with the following structure:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
The Django dev web server is used only for testing and is not suitable for a production
environment. For this, you will need to use a real server like Apache.
To be able to share our project "myproject" with Apache, we The wsgi.py in the project
need to set Apache to access our folder. If we place our project structure takes care of
the link between Django
in the default "/var/www/html", the project will be accessed via and Apache.
127.0.0.1/myproject. In this case, Apache will simply list the
folder as shown:
Page | 24
Python Programming Unit 9
Source: tutorialspoint.com
Fig 5: Project Access Via 127.0.0.1/myproject
For Apache to handle Django the way we want, we need to configure Apache in httpd.conf.
To do this open the httpd.conf and add the following command:
WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py
WSGIPythonPath /var/www/html/myproject/
<Directory /var/www/html/myproject/>
<Files wsgi.py>
Order deny,allow
</Files>
</Directory>
This will give you the following output when the page is accessed through
127.0.0.1/myapp/connection.
Source: tutorialspoint.com
Page | 25
Python Programming Unit 9
We can create forms by using Django by inheriting the from Django class. The class
attributes will become the form fields. To get started, we need to create a forms.py file in
the main project folder ("myapp" for this example) that will contain all our app forms.
You can create the login page in the following manner.
class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput())
We want the password to be hidden and hence the password field can take "widget"
arguments for html rendering.
GET and POST are the two HTTP methods used when dealing with forms in Django. The
login form is returned using the POST method. In this, the browser bundles up the form
data; encodes it for transmission, sends it to the server, and then receives its response.
On the other hand, GET bundles the data into a string, and uses this to create a URL. The
URL contains the address where the data must be sent, as well as the data keys and
values.
def login(request):
username = "not logged in"
if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
else:
MyLoginForm = Loginform()
return render(request, 'loggedin.html', {"username" : username})
The above code will display the result of the login form posted through
the loggedin.html. However, to test this, we first need the login form template
( "login.html" in this example).
<html>
Page | 26
Python Programming Unit 9
<body>
<form name = "form" action = "{% url "myapp.views.login" %}"
method = "POST">{% csrf_token %}
<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Identifiant" name = "username" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<input type = "password" style = "margin-left:20%;"
placeholder = "password" name = "password" />
</center>
</div>
<br>
</center>
</div>
</form>
</body>
</html>
The above template will display a login form and post the STUDY NOTE
result to our login view.
Now that we have the login template, we need the The {% csrf_token %} tag is
loggedin.html template that will be given after form used to prevent a Cross-site
treatment. Request Forgery (CSRF)
attack on a website.
<html>
<body>
</body>
</html>
Page | 27
Python Programming Unit 9
urlpatterns = patterns('myapp.views',
url(r'^connection/',TemplateView.as_view(template_name = 'login.html')),
The following login template is rendered, when you try to access "/myapp/connection"
Source: tutorialspoint.com
When you fill the two fields in the login form, you will get the following result:
Page | 28
Python Programming Unit 9
Source: tutorialspoint.com
Source: tutorialspoint.com
14.4.5. COOKIES
Sometimes we wish to save data on a per-site-visitor basis on our website. They are
stored in the form of HTTP cookies that are stored locally by a browser.
Page | 29
Python Programming Unit 9
Creating a cookie
def setcookie(request):
html = HttpResponse("<h1>Dataflair Django Tutorial</h1>")
html.set_cookie('dataflair', 'Hello this is your Cookies', max_age = None)
return html
request.COOKIES[‘cookie_name’]
Example:
def showcookie(request):
show = request.COOKIES['dataflair']
html = "<center> New Page <br>{0}</center>".format(show)
return HttpResponse(html)
COOKIES.get(‘cookie_name’, ‘value’)
Example:
def setcookie(request):
html = HttpResponse("<h1>Dataflair Django Tutorial</h1>")
if request.COOKIES.get('visits'):
html.set_cookie('dataflair', 'Welcome Back')
value = int(request.COOKIES.get('visits'))
html.set_cookie('visits', value + 1)
else:
value = 1
text = "Welcome for the first time"
Page | 30
Python Programming Unit 9
html.set_cookie('visits', value)
html.set_cookie('dataflair', text)
return html
# it will check whether the request has cookies or not, then set the cookies according to
that
14.4.6. SESSIONS
'django.contrib.sessions.middleware.SessionMiddleware'
'django.contrib.sessions'
Let us look at an example where we save the username in a cookie and if not signed out,
you won’t see the login form when you try to access the login page.
def login(request):
username = 'not logged in'
if request.method == 'POST':
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
request.session['username'] = username
else:
MyLoginForm = LoginForm()
return render(request, 'loggedin.html', {"username" : username}
def formView(request):
if request.session.has_key('username'):
username = request.session['username']
return render(request, 'loggedin.html', {"username" : username})
else:
Page | 31
Python Programming Unit 9
# change the url.py file to change the url so it pairs with the new view
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns('myapp.views',
url(r'^connection/','formView', name = 'loginform'),
url(r'^login/', 'login', name = 'login'))
ACTIVITY 3
Create a Django template that automates the process of sending emails.You can have
a list of email addresses and their respective names. The massages can be modified
and sent to the target audience automatically.
Page | 32
Python Programming Unit 9
SELF-ASSESSMENT QUESTIONS
18) The ____________ file in a project structure takes care of the link between
Django and Apache.
19) ______ and __________are the two HTTP methods used when dealing with
forms in Django.
20) POST bundles the data into a string, and uses this to create a URL.
[True/False]
22) Which attribute of the set_cookie() method helps to set the time period
of a cookie.
A. value
B. name
C. max_age
D. age
A. database
B. Cache
C. file
D. all
Page | 33
Python Programming Unit 9
14.5. SUMMARY
• A module is any file that contains Python statements and definitions. They are
used to divide a huge code into small manageable and organized files.
• A Python package is a set of directories and modules of files.
• Pandas package is used to efficiently manipulate data and analyse it.
• Anaconda distribution is a cross-platform distribution for data analysis and
scientific computing. It contains the NumPy and Pandas packages along with
others.
• Series is a Pandas module and is a one-dimensional array that is capable of storing
data of any data type.
• The elements or values of a Pandas series are mutable and indexed.
• A series can be created by using an array, dictionary, scalar value or a constant.
• Pandas Dataframe is used to organise data in a tabular form. Users can perform
various arithmetic operations on the rows and columns.
• Pandas Panel represents data in a 3D structure. Three axes are used to describing
operations--items, major_axis, and minor_axis. These can be used to select data
from a panel.
• Descriptive Statistics is used to study data analysis and describe, show or
summarize data in a meaningful manner.
• The Matplotlib package of Python is used to visually represent data as plots.
• We can create simple plots, bar graphs, animations, histograms, etc. using
matplotlib. The bar() function is used to create bar plots.
• Django is a web development framework that helps users develop and maintain
web applications.
• Django works based on the Model-View-Template (MVT) pattern of the web
framework. Apache is a server that offers a production environment.
• We can create forms in Django and save user data in the form of cookies. Sessions
are used to provide a layer of security to the cookies.
Page | 34
Python Programming Unit 9
14.6. GLOSSARY
Page | 35
Python Programming Unit 9
Packages in
Python
Matplotlib
Pandas Package
Package
Use and
Use and Import
Descriptive
Import Statistics Bar Plot
Simple Plot
Series
Panel
Histogram
Dataframe
Django
Package
Cookies
Use and
Import
Form Sessions
Apache Processing
Page | 36
Python Programming Unit 9
Moccu Digital Agency was assigned the task of creating a website to help
L’Oreal relaunch the Men Expert project digitally. The agency decided to use the
Django CMS to create the website. A Content Management System (CMS) helps
users add, modify and delete the content as per their will.
The web pages were not based on set templates and were made using the freely
combinable elements in Django CMS. The CMS interface lets the content writers
work directly on the pages where media can directly be inserted from a media
database (with provisions for different formats and resolutions).
Source: django-cms.org
Discussion Questions
2) Which possible tools did the company use in Django CMS to create their
website?
Page | 37
Python Programming Unit 9
ANSWERS
SELF-ASSESSMENT QUESTIONS:
1) Dataframe
2) Module
3) NumPy
4) True
5) False
6) A. drop(). drop() function is used to delete rows by using the label index.
7) C. minor_axis. axis 2, the columns of each of the DataFrames.
8) B. std(). Standard Deviation of the Values
9) Matplotlib
10) NumPy
11) hist()
12) Pip
13) False
14) True
15) B. bottom. scalar or array-like sequences that represent the y coordinate of the bars
16) B. bar is the default histogram.
17) Model-View-Template (MVT)
18) wsgi.py
19) GET, POST
20) False
21) True
22) C. max_age. The time period of a cookie in seconds, after which it will expire.
23) D. all. We can save sessions information as a database, a file or a cache.
Page | 38
Python Programming Unit 9
TERMINAL QUESTIONS
Answer 1:
PANDAS NUMPY
Used to work with tabular data Used to work with numerical data
tools of pandas are Data frame and Series. tool of numpy is Arrays.
Shows better performance when number Shows better performance when number
of rows is 500K or more. of rows is 50K or less.
Answer 2: Subplots are grids of plots within a single figure. Subplots can be plotted
using the subplots() function from the matplotlib.pyplot module.
Answer 4: Descriptive statistics is defined as the study of data analysis to describe, show
or summarize data in a meaningful manner. A vast number of methods and operations
collectively help us compute descriptive statistics on a Dataframe.
These methods usually take an axis argument, similar to ndarray.{sum, std, ...}, however,
the axis can be specified by name or integer
Answer 5: The matplotlib is one of the most famous Python packages used for data
visualisation. It is a cross-platform library used to make 2D plots from array data.
Matplotlib has an interface known as Pylab that has been designed to resemble the
MATLAB programming language.
Page | 39
Python Programming Unit 9
Views: The view layer is the user interface. It controls what a user sees and retrieves data
from appropriate models to execute any calculation made to the data and pass it to the
template.
Templates: It determines how the user sees. It describes how the data received from the
views should be changed or formatted for display on the page.
Controller: Controller is the heart of the system. It handles requests and responses, sets
up database connections and loads add-ons. It specifies the Django framework and URL
parsing.
Answer 2: To set up a database in Django, you can use the command edit
mysite/setting.py.
By default, Django uses SQLite database. It is easy for Django users because it doesn’t
require any other type of installation. In the case of another database, you can use the
following keys in the DATABASE ‘default’ item to match your database connection
settings.
Name: The name of your database. In case you are using SQLite as your database, it will
be a file on your computer. The name should be a full path, including the file name.
Note: You have to add setting like Password, Host, User, etc. in your database if you are
not using SQLite as your database.
Output:
0
0 Python
1 Pandas
# from dict
Page | 40
Python Programming Unit 9
import pandas as pd
info = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]}
info = pd.DataFrame(info)
print (info)
Output:
ID Department
0 101 B.Sc
1 102 B.Tech
2 103 M.Tech
import pandas as pd
df = pd.DataFrame(d)
# Adding a new column to an existing DataFrame object with a column label by passing
new series
print (df)
Output:
Adding a new column by passing a Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Page | 41
Python Programming Unit 9
BOOKS:
E-REFERENCES:
Page | 42