You are on page 1of 254

LECTURE NOTES

on

PYTHON PROGRAMMING

I B. Tech II Semester

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN


(Autonomous Institution-UGC, Govt. of India)
Accredited by NBA & NAAC with ‘A’ Grade, UGC, Govt. of India
NIRF Indian Ranking, Accepted by MHRD, Govt. of India
Band A (6th to 25th) National Ranking by ARIIA, MHRD, Govt. of India
Approved by AICTE, ISO 9001:2015 Certified Institution
AAAA+ Rated by Digital Learning Magazine, AAA+ Rated by Careers 360 Magazine
3rd Rank CSR, Platinum Rated by AICTE-CII Survey, 141 National Ranking by India Today Magazine
National Ranking-Top 100 Rank band by Outlook Magazine, National Ranking-Top 100 Rank band by Times News Magazine

2020-2021
UNIT I
PYTHON Programming

1.1 INTRODUCTION TO PYTHON:


Python is a high-level, interpreted, interactive and object-oriented
scripting language. Python is designed to be highly readable. It uses English
keywords frequently whereas the other languages use punctuations. It has fewer
syntactical constructions than other languages.
1. Python is Interpreted − Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is
similar to PERL and PHP.
2. Python is Interactive − You can actually sit at a Python prompt and
interact with the interpreter directly to write yourprograms.
3. Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code withinobjects.
4. Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers
togames.

1.2 History of Python:


Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer Science
in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages.
 Python is copyrighted. Like Perl, Python source code is now available
under the GNU General Public License (GPL).
 Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing itsprogress.
 Python 1.0 was released in November 1994. In 2000, Python 2.0 was
released.Python
2.7.11 is the latest edition of Python 2.
 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the
removal of duplicate programming constructs and modules so that "There
should be one -- and preferably only one -- obvious way to do it." Python
3.5.1 is the latest version of Python3.

1.3 Python is derived from?

Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).

Python is now maintained by a core development team at the institute, although


Guido van Rossum still holds a vital role in directing its progress.

1.4 Python Features:

Python provides many useful features which make it popular and valuable from
the other programming languages. It supports object-oriented programming, procedural
programming approaches and provides dynamic memory allocation. We have listed
below a few essential features.

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward and much the same as the English language. There is no use of the
semicolon or curly-bracket, the indentation defines the code block. It is the
recommended programming language for beginners.
2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the
hello world program you simply type print("Hello World"). It will take only one line
to execute, while Java or C takes multiple lines.

3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line
at a time. The advantage of being interpreted language, it makes debugging easy
and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and
Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a
program only once.

5) Free and Open Source

Python is freely available for everyone. It is freely available on its official


website www.python.org. It has a large community across the world that is
dedicatedly working towards make new python modules and functions. Anyone can
contribute to the Python community. The open-source means, "Anyone can
download its source code without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come
into existence. It supports inheritance, polymorphism, and encapsulation, etc. The
object-oriented procedure helps to programmer to write reusable code and develop
applications in less code.
7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our Python code. It converts the program into byte
code, and any platform can use that byte code.

8) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning,
web developer, and also for the scripting. There are various machine learning
libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django,
flask, pyramids are the popular framework for Python web development.

9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5,
Tkinter, Kivy are the libraries which are used for developing the web application.

10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs
code line by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable

The code of the other programming language can use in the Python source code.
We can use Python source code in another programming language as well. It can
embed other language into our code.
12. Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we assign
some value to the variable, it automatically allocates the memory to the variable at
run time. Suppose we are assigned integer value 15 to x, then we don't need to
write int x = 15. Just write x = 15.

1.5 Python Applications:

Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any application.
Here, we are specifying application areas where Python can be applied.

1) Web Applications

We can use Python to develop web applications. It provides libraries to handle


internet protocols such as HTML and XML, JSON, Email processing, request,
beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used
on Instagram. Python provides many useful frameworks, and these are given below:

 Django and Pyramid framework(Use for heavy applications)

 Flask and Bottle (Micro-framework)

 Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications

The GUI stands for the Graphical User Interface, which provides a smooth interaction
to any application. Python provides a Tk GUI library to develop a user interface.
Some popular GUI libraries are given below.

 Tkinter or Tk

 wxWidgetM

 Kivy (used for writing multitouch applications )

 PyQt or Pyside

3) Console-based Application

Console-based applications run from the command-line or shell. These


applications are computer program which are used commands to execute. This kind of
application was more popular in the old generation of computers. Python can develop this
kind of application very effectively. It is famous for having REPL, which means the
Read-Eval-Print Loop that makes it the most suitable language for the command-line
applications.

Python provides many free library or module which helps to build the command-line
apps. The necessary IO libraries are used to read and write. It helps to parse argument
and create console help text out-of-the-box. There are also advance libraries that can
develop independent console apps.
4) Software Development

Python is useful for the software development process. It works as a support language
and can be used to build control and management, testing, etc.

 SCons is used to build control.

 Buildbot and Apache Gumps are used for automated continuous compilation and
testing.

 Round or Trac for bug tracking and project management.

5) Scientific and Numeric

This is the era of Artificial intelligence where the machine can perform the task
the same as the human. Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations.

Implementing machine learning algorithms require complex mathematical calculation.


Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy,
Scikit-learn, etc. If you have some basic knowledge of Python, you need to import
libraries on the top of the code. Few popular frameworks of machine libraries are given
below.

 SciPy

 Scikit-learn

 NumPy

 Pandas

 Matplotlib
6) Business Applications

Business Applications differ from standard applications. E-commerce and ERP


are an example of a business application. This kind of application requires extensively,
scalability and readability, and Python provides all these features.

Oddo is an example of the all-in-one Python-based application which offers a range of


business applications. Python provides a Tryton platform which is used to develop the
business application.

7) Audio or Video-based Applications

Python is flexible to perform multiple tasks and can be used to create multimedia
applications. Some multimedia applications which are made by using Python
are TimPlayer, cplay, etc. The few multimedia libraries are given below.

 Gstreamer

 Pyglet

 QT Phonon

8) 3D CAD Applications

The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by using
the following functionalities.

 Fandango (Popular )

 CAMVOX

 HeeksCNC

 AnyCAD

 RCAM
9) Enterprise Applications

Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.

10) Image Processing Application

Python contains many libraries that are used to work with the image. The image can
be manipulated according to our requirements. Some libraries of image processing are
given below.

 OpenCV

 Pillow

 SimpleITK

1.6 Why Python is becoming popular now a days?

Python is one of the languages that is witnessing incredible growth and


popularity year by year. In 2017, Stack overflow calculated that python would beat all
other programming languages by 2020 as it has become the fastest-growing programming
language in the world.
It is also considered one of the best programming languages for machine
learning. So why is Python so popular?

1) Easy to Learn and Use:


One of the main reasons for the popularity of python would be its simplicity
in syntax so that it could be easily read and understood even by amateur
developers also. Due to its ease of learning and usage, python codes can be
easily written and executed much faster than other programming languages.

2) Mature and Supportive Python Community:


Python was created more than 30 years ago, which is a lot of time for any
community of programming language to grow and mature adequately to support
developers ranging from beginner to expert levels. There are plenty of
documentation, guides and Video Tutorials for Python language are available that
learner and developer of any skill level or ages can use and receive the support
required to enhance their knowledge in python programming language.

Many students get introduced to computer science only through Python language,
which is the same language used for in-depth research projects.

3) Support from Renowned Corporate Sponsors:


Programming languages grows faster when a corporate sponsor backs it. For
example, PHP is backed by Facebook, Java by Oracle and Sun, Visual Basic & C# by
Microsoft. Python Programming language is heavily backed by Facebook, Amazon
Web Services, and especially Google.
Google adopted python language way back in 2006 and have used it for many
applications and platforms since then. Lots of Institutional effort and money have
been devoted to the training and success of the python language by Google. They
have even created a dedicated portal only for python.

4) Hundreds of Python Libraries and Frameworks


Due to its corporate sponsorship and big supportive community of python, python
has excellent libraries that you can use to select and save your time and effort on the
initial cycle of development. There are also lots of cloud media services that offer cross-
platform support through library-like tools, which can be extremely beneficial.
There are many frameworks and libraries are available for python language, such
as:
 matplotib for plotting charts and graphs
 SciPy for engineering applications, science, and mathematics
 BeautifulSoup for HTML parsing and XML
 NumPy for scientific computing
 Django for server-side web development

5) Versatility, Efficiency, Reliability, and Speed


Ask any python developer, and they will wholeheartedly agree that the python
language is efficient, reliable, and much faster than most modern languages. Python can
be used in nearly any kind of environment, and one will not face any kind of
performance loss issue irrespective of the platform one is working. One more best thing
about versatility of python language is that it can be used in many varieties of
environments such as mobile applications, desktop applications, web development,
hardware programming, and many more. The versatility of python makes it more
attractive to use due to its high number of applications.

6) Big data, Machine Learning and Cloud Computing


Cloud Computing, Machine Learning, and Big Data are some of the hottest trends in
the computer science world right now, which helps lots of organizations to transform and
improve their processes and workflows.
Python language is the second most popular used tool after R language for data
science and analytics. Lots of many data processing workloads in the organization are
powered by python language only. Most of the research and development takes place in
python language due to its many applications, including ease of analysing and organizing
the usable data.
Not only this, but hundreds of python libraries are being used in thousands of
machine learning projects every day, such as TensorFlow for neural networks and
OpenCV for computer vision, etc.

7) First-choice Language
Python language is the first choice for many programmers and students due to the
main reason for python being in high demand in the development market. Students and
developers always look forward to learning a language that is in high demand. Python is
undoubtedly the hottest cake in the market now.
Many programmers and data science students are using python language for their
development projects. Learning python is one of the important section in data science
certification courses. In this way, the python language can provide plenty of fantastic
career opportunities for students. Due to the variety of applications of python, one can
pursue different career options and will not remain stuck to one.

8) The Flexibility of Python Language


The python language is so flexible that it gives the developer the chance to try
something new. The person who is an expert in python language is not just limited to
build similar kinds of things but can also go on to try to make something different than
before.
Python doesn’t restrict developers from developing any sort of application. This
kind of freedom and flexibility by just learning one language is not available in other
programming languages.

9) Use of python in academics


Now python language is being treated as the core programming language in
schools and colleges due to its countless uses in Artificial Intelligence, Deep Learning,
Data Science, etc. It has now become a fundamental part of the development world that
schools and colleges cannot afford not to teach python language.
In this way, it is increasing more python Developers and Programmers and thus
further expanding its growth and popularity.

10) Automation
Python language can help a lot in automation of tasks as there are lots of tools and
modules available, which makes things much more comfortable. It is incredible to know
that one can reach an advanced level of automation easily by just using necessary python
codes.
Python is the best performance booster in the automation of software testing also.
One will be amazed at how much less time and few numbers of lines are required to write
codes for automation tools.

1.7 Existing program vs Python program:


Python is often compared to other interpreted languages such as Java, JavaScript,
Perl, Tcl, or Smalltalk. Comparisons to C++, Common Lisp and Scheme can also be
enlightening. In this section I will briefly compare Python to each of these languages.
These comparisons concentrate on language issues only. In practice, the choice of a
programming language is often dictated by other real-world constraints such as cost,
availability, training, and prior investment, or even emotional attachment. Since these
aspects are highly variable, it seems a waste of time to consider them much for this
comparison.

Java:

Python programs are generally expected to run slower than Java programs, but
they also take much less time to develop. Python programs are typically 3-5 times shorter
than equivalent Java programs. This difference can be attributed to Python's built-in high-
level data types and its dynamic typing. For example, a Python programmer wastes no
time declaring the types of arguments or variables, and Python's powerful polymorphic
list and dictionary types, for which rich syntactic support is built straight into the
language, find a use in almost every Python program. Because of the run-time typing,
Python's run time must work harder than Java's. For example, when evaluating the
expression a+b, it must first inspect the objects a and b to find out their type, which is not
known at compile time. It then invokes the appropriate addition operation, which may be
an overloaded user-defined method. Java, on the other hand, can perform an efficient
integer or floating point addition, but requires variable declarations for a and b, and does
not allow overloading of the + operator for instances of user-defined classes.

For these reasons, Python is much better suited as a "glue" language, while Java is
better characterized as a low-level implementation language. In fact, the two together
make an excellent combination. Components can be developed in Java and combined to
form applications in Python; Python can also be used to prototype components until their
design can be "hardened" in a Java implementation. To support this type of development,
a Python implementation written in Java is under development, which allows calling
Python code from Java and vice versa. In this implementation, Python source code is
translated to Java bytecode (with help from a run-time library to support Python's
dynamic semantics).

Javascript:

Python's "object-based" subset is roughly equivalent to JavaScript. Like


JavaScript (and unlike Java), Python supports a programming style that uses simple
functions and variables without engaging in class definitions. However, for JavaScript,
that's all there is. Python, on the other hand, supports writing much larger programs and
better code reuse through a true object-oriented programming style, where classes and
inheritance play an important role.

Perl :

Python and Perl come from a similar background (Unix scripting, which both
have long outgrown), and sport many similar features, but have a different philosophy.
Perl emphasizes support for common application-oriented tasks, e.g. by having built-in
regular expressions, file scanning and report generating features. Python emphasizes
support for common programming methodologies such as data structure design and
object-oriented programming, and encourages programmers to write readable (and thus
maintainable) code by providing an elegant but not overly cryptic notation. As a
consequence, Python comes close to Perl but rarely beats it in its original application
domain; however Python has an applicability well beyond Perl's niche.

Tcl:

Like Python, Tcl is usable as an application extension language, as well as a


stand-alone programming language. However, Tcl, which traditionally stores all data as
strings, is weak on data structures, and executes typical code much slower than Python.
Tcl also lacks features needed for writing large programs, such as modular namespaces.
Thus, while a "typical" large application using Tcl usually contains Tcl extensions
written in C or C++ that are specific to that application, an equivalent Python application
can often be written in "pure Python". Of course, pure Python development is much
quicker than having to write and debug a C or C++ component. It has been said that Tcl's
one redeeming quality is the Tk toolkit. Python has adopted an interface to Tk as its
standard GUI component library.

Tcl 8.0 addresses the speed issuse by providing a bytecode compiler with limited
data type support, and adds namespaces. However, it is still a much more cumbersome
programming language.

Smalltalk:

Perhaps the biggest difference between Python and Smalltalk is Python's more
"mainstream" syntax, which gives it a leg up on programmer training. Like Smalltalk,
Python has dynamic typing and binding, and everything in Python is an object. However,
Python distinguishes built-in object types from user-defined classes, and currently doesn't
allow inheritance from built-in types. Smalltalk's standard library of collection data types
is more refined, while Python's library has more facilities for dealing with Internet and
WWW realities such as email, HTML and FTP.
Python has a different philosophy regarding the development environment and
distribution of code. Where Smalltalk traditionally has a monolithic "system image"
which comprises both the environment and the user's program, Python stores both
standard modules and user modules in individual files which can easily be rearranged or
distributed outside the system. One consequence is that there is more than one option for
attaching a Graphical User Interface (GUI) to a Python program, since the GUI is not
built into the system.

C++:

Almost everything said for Java also applies for C++, just more so: where Python
code is typically 3-5 times shorter than equivalent Java code, it is often 5-10 times shorter
than equivalent C++ code! Anecdotal evidence suggests that one Python programmer can
finish in two months what two C++ programmers can't complete in a year. Python shines
as a glue language, used to combine components written in C++.

Common Lisp and Scheme:

These languages are close to Python in their dynamic semantics, but so different in
their approach to syntax that a comparison becomes almost a religious argument: is Lisp's
lack of syntax an advantage or a disadvantage? It should be noted that Python has
introspective capabilities similar to those of Lisp, and Python programs can construct and
execute program fragments on the fly. Usually, real-world properties are decisive:
Common Lisp is big (in every sense), and the Scheme world is fragmented between many
incompatible versions, where Python has a single, free, compact implementation.

1.8 Writing programs in Python:


When learning a new programming language, it’s traditional for the first program
to be the “Hello World” program. This program prints out the outputs the words “Hello
World” into Terminal. With Python, we can either write a program in a text editor and
then run it on Terminal or we can use Python’s Interactive Interpreter and type commands
directly in Terminal. First, we will write in the Python Interpreter.
python3Python 3.6.5 (default, Apr 1 2018, 05:46:30)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

We can now write directly into the Python Interpreter and if used properly, it
should be able to run code one line at a time and in the order, we write them. For example,
let’s try the “Hello World” program.

>>> print ("Hello World")


Hello World

Here we see the print () function. Anything inside the parentheses and between the
quotes will display in the Terminal. If we leave it blank, it won’t print anything.

1.9 Top Companies Using Python:


1. Google
2. Facebook
3. Instagram
4. Spotify
5. Quora
6. Netflix
7. Dropbox
8. Reddit

1.10 Python Programming Modes:


Python provides us the two ways to run a program:

 Using Interactive interpreter prompt


 Using a script file

1.10.1 Interactive Mode Programming

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at
the interactive prompt. It is preferable in the case where we are concerned about the
output of each line of our Python program.

To open the interactive mode, open the terminal (or command prompt) and type
python (python3 in case if you have Python2 and Python3 both installed on your
system).

It will open the following prompt where we can execute the Python statement and
check their impact on the console.
Here, we get the message "Hello World !" printed on the console.
1.10.2 Scripting Mode Programming

Using a script file

Interpreter prompt is good to run the individual statements of the code. However, we
cannot write the code every-time on the terminal.

We need to write our code into a file which can be executed later. For this purpose, open
an editor like notepad, create a file named first.py (Python used .py extension) and write
the following code in it.

1. print ("hello world"); #here, we have used print() function to print the message on the c
onsole.

To run this file named as first.py, we need to run the following command on the terminal.
$ python3 first.py

1.11 Flavors of Python:

Types of Python compilers are referred as flavors of Python. They help to


integrate various types of programming languages in Python some of them are:

1. CPython:

It is a Python compiler that was implemented in C language. Even C++ code can be
execute using CPython.

2. JPython:

It is enables Python implementation to be run on Java platform. It runs on JVM.

3. IronPython:

It is compiler designed for .NET framework, but it is written in C#. It can run on
CLR(Common Language Run time).

4. PyPy:

It is a Python implemented by using Python language itself. It runs fast since JIT is
incorporated to PVM.

5. Ruby Python:
It acts as a bridge from Ruby to Python interpreter. It embeds the Python interpreter
inside the Ruby application.

6. Pythonxy:

It is written in the form of Python(X,Y). It is designed by adding scientific and


engineering related packages.

7.Anaconda Python:

The name Anaconda Python is obtained after redeveloping it to handle large scale data
processing, predictive analytics and scientific computing. It handles huge amount of
data.

8. Stackless Python:

Tasklets are the small tasks that are run independently. The communication is
done with each by using channels. They schedule, control and suspend the tasklets.
Hundreds of tasklets can run by a thread. The thread and tasklets can be created in
stackless python. It is a re-implementation of python.

1.12 Python versions:

Python programming language is being updated regularly with new features and
supports. There are lots of update in Python versions, started from 1994 to current
release.

A list of Python versions with its released date is given below.

Python Version Released Date


Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012


Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

1.13 Downloading and Installing Python:

1.13.1 Installation on Windows:

Visit the link https://www.python.org/downloads/ to download the latest release of


Python. In this process, we will install Python 3.6.7 on our Windows operating system.
Double-click the executable file, which is downloaded; the following window will open. Select
Customize installation and proceed.
The following window shows all the optional features. All the features need to be installed
and are checked by default; we need to click next to continue .

The following window shows a list of advanced options. Check all the options which you want to install
and click next. Here, we must notice that the first check-box (install for all users) must be
checked.

Now, we are ready to install python-3.6.7. Let's install it.


1.13.2 Installing in Linux:

Python is a high level, dynamic and general purpose programming language. It


was designed and developed by Python Software Foundation.Python is a cross-platform
language and was first released on 20, February 1991.Although Python 2.7 is installed by
default in Ubuntu, but we can install other Python versions like python3.To install
python3, just type the following command in the terminal and it will be installed
automatically.

Python Installation:

1) Update the APT Repository

$ apt-get update

2) Install Python

$ apt-get install python3.6


3) Verify Python

When we type python it shows default installed python that is 2.7.

$ python

For Python3 type the following command, then it will show the other version as
well.

$ python3

Well, on the basis of these commands, we can test application for both Python versions.

1.14 How to set Python Environment in system?


Now, try to run python on the command prompt. Type the command python in
case of python2 or python3 in case of python3. It will show an error as given in the below
image. It is because we haven't set the path.

To set the path of python, we need to the right click on "my computer" and go to
Properties → Advanced → Environment Variables.
Type PATH as the variable name and set the path to the installation directory of the python
shown in the below image.
Now, the path is set; we are ready to run python on our local system. Restart CMD, and
type python again. It will open the python interpreter shell where we can execute the python
statements.

1.15 Anaconda-Data science Distributor:

Anaconda is a free and open-sourcedistribution of the Python and R programming


languages for scientific computing (data science, machine learning applications, large-
scale data processing, predictive analytics, etc.), that aims to simplify package
management and deployment. The distribution includes data-science packages suitable for
Windows, Linux, and macOS. It is developed and maintained by Anaconda, Inc., which
was founded by Peter Wang and Travis Oliphant in 2012. As an Anaconda, Inc. product,
it is also known as Anaconda Distribution or Anaconda Individual Edition, while other
products from the company are Anaconda Team Edition and Anaconda Enterprise
Edition, which are both not free.

Package versions in Anaconda are managed by the package management


system conda. This package manager was spun out as a separate open-source package as
it ended up being useful on its own and for other things than Python. There is also a
small, bootstrap version of Anaconda called Miniconda, which includes only conda,
Python, the packages they depend on, and a small number of other packages.

Anaconda Navigator is a desktop graphical user interface (GUI) included in


Anaconda distribution that allows users to launch applications and manage conda
packages, environments and channels without using command-line commands. Navigator
can search for packages on Anaconda Cloud or in a local Anaconda Repository, install
them in an environment, run the packages and update them. It is available
for Windows, macOS and Linux.

The following applications are available by default in Navigator.

 JupyterLab
 Jupyter Notebook
 QtConsole
 Spyder
 Glue
 Orange
 RStudio
 Visual Studio Code
Anaconda distribution comes with over 250 packages automatically installed, and
over 7,500 additional open-source packages can be installed from PyPI as well as
the conda package and virtual environment manager. It also includes a GUI, Anaconda
Navigator, as a graphical alternative to the command line interface (CLI).

The big difference between conda and the pip package manager is in how package
dependencies are managed, which is a significant challenge for Python data science and
the reason conda exists.

1.16 Anaconda Installing on Windows:

1. Download anaconda from https://www.anaconda.com/products/individual#windows

2. Double click the installer to launch.

3. Click Next.

4. Read the licensing terms and click “I Agree”.

5. Select an install for “Just Me” unless you’re installing for all users (which requires
Windows Administrator privileges) and click Next.

6. Select a destination folder to install Anaconda and click the Next button.
Choose whether to add Anaconda to your PATH environment variable. We recommend
not adding Anaconda to the PATH environment variable, since this can interfere with
other software. Instead, use Anaconda software by opening Anaconda Navigator or the
Anaconda Prompt from the Start Menu.
Choose whether to register Anaconda as your default Python. Unless you plan on
installing and running multiple versions of Anaconda or multiple versions of Python,
accept the default and leave this box checked.

 Click the Install button. If you want to watch the packages Anaconda is installing,
click Show Details
 Click the Next button
 Optional: To install PyCharm for Anaconda, click on the link
to https://www.anaconda.com/pycharm.
 After a successful installation you will see the “Thanks for installing Anaconda”
dialog box:
1.17 JUPYTER Notebook:

For new users, we highly recommend installing Anaconda. Anaconda


conveniently installs Python, the Jupyter Notebook, and other commonly used packages
for scientific computing and data science.

Use the following installation steps:

1. Download Anaconda. We recommend downloading Anaconda’s latest Python 3 version


(currently Python 3.5).

2. Install the version of Anaconda which you downloaded, following the instructions on the
download page.

3. Congratulations, you have installed Jupyter Notebook. To run the notebook:


jupyter notebook

Alternative for experienced Python users: Installing Jupyter with pip

Important

Jupyter installation requires Python 3.3 or greater, or Python 2.7. IPython 1.x, which included the
parts that later became Jupyter, was the last version to support Python 3.2 and 2.6.
As an existing Python user, you may wish to install Jupyter using Python’s
package manager, pip, instead of Anaconda.

First, ensure that you have the latest pip; older versions may have trouble with
some dependencies:

pip3 install --upgrade pip

Then install the Jupyter Notebook using:

pip3 install jupyter

(Use pip if using legacy Python 2.)

With this you have installed Jupyter

1.18 SPYDER:

To install Spyder IDE on Windows, we are going to need PIP


Open a command prompt and type the following command to install Spyder:
Spyder has multiple dependencies that you can check on the official Spyder
documentation. However, PIP will automatically install any not satisfied dependencies
making the process very straight-forward.

Once you install Spyder through this method, it will be added to your system as a
Python module. Therefore, it will not appear on your Control Panel. If you need to
uninstall Spyder, you'll have to use the following command:pip uninstall spyder
To run Spyder on Windows, you can either type the command "spyder3" in a
command prompt or search for spyder3 in the start menu.
1.19 Python IDE- JUPYTER Notebook Environment:

IDE stands for Integrated Development Environment. It’s a coding tool which
allows you to write, test, and debug your code in an easier way, as they typically offer
code completion or code insight by highlighting, resource management, debugging tools
and even though the IDE is a strictly defined concept, it’s starting to be redefined as other
tools such as notebooks start gaining more and more features that traditionally belong to
IDEs. For example, debugging your code is also possible in Jupyter Notebook.

1.20 Python IDE-SPYDER Environment:

It is always necessary to have interactive environments to create software applications


and this fact becomes very important when you work in the fields of Data Science,
engineering, and scientific research. The Python Spyder IDE has been created for the
same purpose. In this article, you will be learning how to install and make use of Spyder
or the Scientific Python and Development ID

Spyder is an open-source cross-platform IDE. The Python Spyder IDE is written


completely in Python. It is designed by scientists and is exclusively for scientists, data
analysts, and engineers. It is also known as the Scientific Python Development IDE and
has a huge set of remarkable features which are discussed below.

Features of Spyder:
Some of the remarkable features of Spyder are:

 Customizable Syntax Highlighting


 Availability of breakpoints (debugging and conditional breakpoints)
 Interactive execution which allows you to run line, file, cell, etc.
 Run configurations for working directory selections, command-line options,
current/ dedicated/ external console, etc
 Can clear variables automatically ( or enter debugging )
 Navigation through cells, functions, blocks, etc can be achieved through the
Outline Explorer
 It provides real-time code introspection (The ability to examine what functions,
keywords, and classes are, what they are doing and what information they
contain)
 Automatic colon insertion after if, while, etc
 Supports all the IPython magic commands
 Inline display for graphics produced using Matplotlib
 Also provides features such as help, file explorer, find files, etc

Python Spyder IDE Installation ( Installing with Anaconda – Recommended)


The Python Spyder IDE comes as a default implementation along with Anaconda
Python distribution. This is not just the recommended method but also the easiest one.
Follow the steps given below to install the Python Spyder IDE:
 Go to the official Anaconda website using the following
link: https://www.anaconda.com

 Choose the version that is suitable for your OS and click on Download.

 Once the installer is downloaded, you can see a dialog box for the Setup. Complete the
Setup and click on Finish.
 Then, search for Anaconda Navigator in the search bar of your system and launch
Spyder. Once launched, you will see a screen similar to the one below:
Creating a file/ Starting a Project:

 To start a new file, navigate through as follows:

File–>New File

 For creating a new project:

Projects–>New Project

Writing the code:


Writing code in Spyder becomes very easy with its multi-language code editor
and a number of powerful tools. As mentioned earlier, the editor has features such as
syntax highlighting, real-time analysis of code, style analysis, on-demand completion,
etc. When you write your code, you will also notice that it gives a clear call stack for
methods suggesting all the arguments that can be used along with that method.

Take a look at the example below:

In the above example, you can notice that the editor is showing the complete syntax of
the print function.

1.21 PYTHON IDENTIFIERS (literals):

A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or
more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are two
different identifiers in Python.

Python identifier naming rules:

 Class names should start with capital letters. For example, Person, Employee, etc.
 If the class name has multiple words, use Uppercase for the first character of each word.
For example, EmployeeData StringUtils, etc.
 You should use small letters for variables, functions, and module names. For
example, collections, foo (), etc.
 If variables, functions, and module names have multiple words then separate them with
an underscore. For example, is empty (), employee_object, etc.
 For private variables, you can start their names with an underscore.
 Avoid underscore as the first and last character in the identifier name. It’s used by python
built-in types.
 If the identifier starts and ends with two underscores, then it means that the identifier is a
language-defined special name. So, you should avoid having two underscores at the start
and the end of the identifier name.
 Keep identifier names meaningful to clarify their intent. For
example, phone_number, is_uppercase, etc.
 If a function returns boolean value, it’s better to start its name with “is”. For
example, isidentifier, iskeyword, etc.
 There is no limit on the length of the identifier name. But, keep it small and to the point.
For example, the_employee_object_first_name can be better named
as emp_first_name.

Examples of identifiers:

Valid Identifiers Invalid Identifiers


1. Ab10c 1. 99
2. Abc_DE 2. 9abc
3. _abc 3. x+y
4. ‘_’: it is also a valid identifier 4. For: as it is a reserved keyword it is
invalid
1.22 RESERVED KEYWORDS:

Keywords are the reserved words in Python. We cannot use them as constant or
variable or any other identifier names. They are used to define the syntax and the structure of
the Python program. All the Python keywords contain lowercase letters only.

There are 33 keywords in Python 3. This number can vary slightly over the course of
time. All the keywords except True, False and None are in lowercase and they must be written
as they are. The list of all the keywords is given below.

False Await Else Import pass


None Break Except In raise
True Class Finally Is return
And Continue For Lambda try
As Def From Nonlocal while
Assert Del Global Not with
Async Elif If Or yield

The above keywords may get altered in different versions of Python. Some extra might
get added or some might be removed. You can always get the list of keywords in your current
version by typing the following in the prompt.
1.23 VARIABLES:

Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.

In Python, variables need not be declared or defined in advance, as is the case in many
other programming languages. To create a variable, you just assign it a value and then start
using it.

Rules for naming the variables in Python:

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume , etc)

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
 Variable names are case-sensitive (age, Age and AGE are three different variables)

1.24 COMMENTS:

Comments are descriptions that help programmers better understand the intent and
functionality of the program. They are completely ignored by the Python interpreter.

Advantages of Using Comments:


Using comments in programs makes our code more understandable. It makes the program
more readable which helps us remember why certain blocks of code were written.

Other than that, comments can also be used to ignore some code while testing other
blocks of code. This offers a simple way to prevent the execution of some lines or write a quick
pseudo-code for the program.

A hash sign (#) that is not inside a string literal begins a comment. All characters after
the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.

Single-Line Comments:

we use the hash symbol (#) to write a single-line comment.

Example:

# printing a string

Print(“hello world”)

Ouput is : hello world

Multi-Line Comments:

Python doesn't offer a separate way to write multiline comments. However, there are
other ways to get around this issue.

Example-1:

# it is a

# multiline

#comment

Example-2:

‘‘‘
It is a

Multiline comment

’’’

1.25 Lines and Indentation:

Most of the programming languages like c, c++, and java use braces {} to define a block
of code. Python uses indentation

Code blocks are identified by the indentation rather than using symbols like curly
braces. Without extra symbols, programs are easier to read. Also, indentation clearly identifies
which block of code a statement belongs to. Of course, code block can consists of single
statement too.

Python doesn’t support braces to indicate block of codes for class and function,
definitions or flow control. Block of codes are denoted by line indentation. All the continuous
lines indented with same number of spaces would form a block. Python strictly follows
indentation rules to indicate the blocks.

Incorrect indentation will results indentation error.

Example:

if (5>3):

print (“five is greater than three”)

output shows an error as indentation is missing


if (5>3):

print (“five is greater than three”)

output: five is greater than three

1.26 Quotation in Python:

The most common use of single and double quotes is to represent strings by enclosing
a series of characters.

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string. As shown in the code below, we
create these two strings using single and double quotes, respectively.

The triple quotes are used to span the string across multiple lines. For example, all the
following are legal:

word = 'word'

sentence = "This is a sentence."

paragraph = """This is a paragraph. It is

made up of multiple lines and sentences."""


The strings created by using single and double quotes are the same. In other words, we
can use single and double quotes interchangeably when we declare a string. However, it should
be noted that we don’t want to mix them as it’s a syntax error.

If the string contains double quotes, we can use single quotes to represent the string
such that we don’t have to escape the double quotes. However, if there are both single and
double quotes in the string, it’s a syntactical error if you don’t escape the quotes that are the
same as the enclosing ones used by the entire string. So, a backslash is placed before single
quote so that there will be a continuation in the statements as shown in below example

It should be noted that when a string starts or ends with a single or double quote and we
want to use the triple quote for the string, we need to use the ones that differ from the starting
or ending one.
Another use case of the triple quotes is to represent a multi-line string. An example is
given below. You can use either triple single or double quotes in Assigning Values to Variables.

1.27 ASSIGNED VALUES TO VARIABLES:

Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable.

The equal sign (=) is used to assign values to variables.

This is read or interpreted as “n is assigned the value 300.” Once this is done, n can be used in
a statement or expression, and its value will be substituted.

>>>

Just as a literal value can be displayed directly from the interpreter prompt in a REPL session
without the need for print().

Later, if you change the value of n and use it again, the new value will be substituted instead
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.

Example:

Counter =100 # An integer

Miles = 1000.0 # A floating point

Name =” john” # A string

Print counter

Print miles

Print name

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively.

This produces the following result −

100

1000.0
John

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously. For

Example:

a = b = c = 300

Here, an integer object is created with the value 300, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables. For

Example:

a, b, c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Rules for naming the variables in Python:

A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume , etc)

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
 Variable names are case-sensitive (age, Age and AGE are three different variables)
Examples of valid variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Examples of invalid variable names:


2myvar = "John"
my-var = "John"
my var = "John"
UNIT II –DATA TYPES IN PYTHON
2.1 DATATYPES IN PYTHON:

The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.

Every value in Python has a datatype. Since everything is an object in Python


programming, data types are actually classes and variables are instance (object) of these classes.
Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.

1. Numbers

2. Sequence Type

3. Dictionary

4. Boolean

5. Set
2.1.1 Numbers:

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable.

For example;
Output:

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int

2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.

3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

2.1.2Sequence Type:

String:
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.

 In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
 The operator * is known as a repetition operator as the operation "Python" *2 returns
'Python Python'.

The following example illustrates the string in Python.

Output:

Example of string handling:


Output:

List:

Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.


Output:

Tuple:

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

Output:
Dictionary:

Dictionary is an unordered set of a key-value pair of items. It is like an associative array


or a hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.


Output:

it

Boolean:

Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.

Consider the following example.

Output:

it

Set:

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values.

Consider the following example.

Output:

2.2 MUTABLE vs IMMUTABLE OBJECTS IN PYTHON:

Python is an object-oriented programming language i.e., everything in Python is an


object. Every variable in Python holds an instance of an object. Objects are abstraction for data,
and Python has an amazing variety of data structures that you can use to represent data, or
combine them to create own custom data.
There are two types of objects in Python i.e. Mutable and Immutable objects.A first
fundamental distinction that Python makes on data is about whether or not the value of an object
changes. If the value can change, the object is called mutable, while if the value cannot change,
the object is called immutable.

Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be
changed if it is a mutable object.
To summarize the difference, mutable objects can change their state or contents and
immutable objects can’t change their state or content.

 Immutable Objects: These are of in-built types like int, float, bool, string, unicode, tuple.
In simple words, an immutable object can’t be changed after it is created.
 Mutable Objects : These are of type list, dict, set . Custom classes are generally mutable.
Mutable and immutable objects are handled differently in python. Immutable objects are
quicker to access and are expensive to change because it involves the creation of a copy.
Whereas mutable objects are easy to change. Use of mutable objects is recommended when
there is a need to change the size or content of the object

It is important to understand that every object in Python has an ID (identity), and type and
a value. Once created, the ID of an object never changes. It is a unique identifier for it, and it is
used behind the scenes by Python to retrieve the object when we want to use it.

The type also never changes. The type tells what operations are supported by the object and
the possible values that can be assigned to it.

The value can either change or not. If it can, the object is said to be mutable, while when it
cannot, the object is said to be immutable.

2.2.1Mutable Data Types:


Mutable sequences can be changed after creation. Some of Python’s mutable data types
are: lists, byte arrays, sets, and dictionaries.

Lists: lists are mutable.

Here is an example of list:

Output is:

Byte Arrays:

Byte arrays represent the mutable version of bytes objects. They expose most of the
usual methods of mutable sequences as well as most of the methods of the bytes type. Items
are integers in the range [0, 256).
Sets

Python provides two set types, set and frozenset. They are unordered collections of immutable
objects.

2.2.2 Immutable Data Types:


Immutable data types differ from their mutable counterparts in that they cannot be
changed after creation. Some immutable types include numeric data
types, strings, bytes, frozen sets, and tuples.

Numeric Data Types:


You have already seen that integers are immutable; similarly, Python’s other built-in numeric data
types such as booleans, floats, complex numbers, fractions, and decimals are also immutable!

Strings and Bytes:


Textual data in Python is handled with str objects, more commonly known as strings. They are
immutable sequences of Unicode code points. Unicode code points can represent a character.
When it comes to storing textual data though, or sending it on the network, you may want to
encode it, using an appropriate encoding for the medium you’re using. The result of an encoding
produces a byte’s object, whose syntax and behavior is similar to that of strings.
Both strings and bytes are immutable.

Frozen Sets:

As discussed in the previous section, frozensets are similar to sets. However, frozenset objects are
quite limited in respect of their mutable counterpart since they cannot be changed. Nevertheless,
they still prove very effective for membership test, union, intersection, and difference operations,
and for performance reasons.

Tuples:

The last immutable sequence type we’re going to see is the tuple. A tuple is a sequence of
arbitrary Python objects. In a tuple, items are separated by commas. These, too, are immutable, as
shown in the following example:
2.3 FUNDAMENTAL DATA TYPES:

Data type is a collection of data or items. The basic fundamental data types are numeric data
type which consists of the following:
 INT
 FLOAT
 COMPLEX
 BOOLEAN
 STRING.

2.3.1 INT data type:

These represent numbers in the range -2147483648 through 2147483647. (The range
may be larger on machines with a larger natural word size, but not smaller.) When the result of
an operation would fall outside this range, the result is normally returned as a long integer (in
some cases, the exception OverflowError is raised instead). For the purpose of shift and mask
operations, integers are assumed to have a binary, 2’s complement notation using 32 or more
bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to
different values).

Plain integers (also just called integers) are implemented using long in C, which gives
them at least 32 bits of precision (sys.maxint is always set to the maximum plain integer value
for the current platform; the minimum value is -sys.maxint - 1). Long integers have unlimited
precision.

Numbers are created by numeric literals or as the result of built-in functions and
operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain
integers unless the value they denote is too large to be represented as a plain integer, in which
case they yield a long integer. Integer literals with an ‘L’ or ‘l’ suffix yield long integers (‘L’ is
preferred because 1l looks too much like eleven!).

2.3.2 FLOAT data type:

These represent machine-level double precision floating point numbers. You are at the
mercy of the underlying machine architecture (and C or Java implementation) for the accepted
range and handling of overflow. Python does not support single-precision floating point
numbers; the savings in processor and memory usage that are usually the reason for using these
is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.
Floating point numbers are usually implemented using double in C; information about the
precision and internal representation of floating point numbers for the machine on which your
program is running is available in sys.float_info.

2.3.3 COMPLEX datatype:


Complex numbers are an extension of the familiar real number system in which all
numbers are expressed as a sum of a real part and an imaginary part. Imaginary numbers are real
multiples of the imaginary unit (the square root of -1), often written i in mathematics or j in
engineering. Python has built-in support for complex numbers, which are written with this latter
notation; the imaginary part is written with a j suffix, e.g., 3+1j. To get access to complex
equivalents of the math module, use cmath. Use of complex numbers is a fairly advanced
mathematical feature. If you’re not aware of a need for them, it’s almost certain you can safely
ignore them.
Complex numbers are stored as a pair of machine-level double precision floating point numbers.

2.3.4 BOOLEAN datatypes:


These represent the truth values False and True. The two objects representing the
values False and True are the only Boolean objects. The Boolean type is a subtype of plain
integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts,
the exception being that when converted to a string, the strings “False” or “True” are returned,
respectively.

2.3.5 STRING datatype:


The items of a string are characters. There is no separate character type; a character is
represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in
functions chr() and ord() convert between characters and nonnegative integers representing
the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values,
but the interpretation of values is up to the program. The string data type is also used to
represent arrays of bytes, e.g., to hold data read from a file.

2.4 NUMBER DATATYPES:


Binary, Octal and Hexadecimal numbers

In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the
following built-in functions.

 bin() : used to return the binary representation of a specified integer.

Eg: x = 10
y = bin(x)

print (y)

 hex(): used to generate hex value of an integer argument.

Eg: result = hex(1)

result2 = hex(342)

print(result)

print(result2)

 oct() :is used to get an octal value of an integer number.

Eg: val = oct(10)

print("Octal value of 10:",val)

2.5 INBULT FUNCTIONS IN PYTHON:

The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present for use.
These functions are known as Built-in Functions. There are several built-in functions in Python
which are listed below:

S.NO FUNCTION & ITS EXAMPLE


DESCRIPTION
1. abs() : used to return the
1. integer = -20
absolute value of 2.
a print('Absolute value of -40 is:', abs(integer))
number. 3.
OUTPUT: Absolute value of -20 is: 20
2. all() : accepts an iterable
1. k = [0, False]
object (such as list,
2. print(all(k))
dictionary, etc.)
OUTPUT: False
3. bin() : used to return the
1. x = 10
binary representation of 2.
a y = bin(x)
specified integer. 3. print (y)
4.
OUTPUT: 0b1010

4. bool(): converts a value


1. test1 = [0]
to boolean(True or False)
2. print(test1,'is',bool(test1))
using the standard truth
testing procedure. OUTPUT: [0] is True

5. bytes() : used for


1. string = "Hello World."
returning a bytes object. 2. array = bytes(string, 'utf-8')
3. print(array)

OUTPUT: b ' Hello World.'

6. callable() : is something
1. x = 8
that can be called. This
2. print(callable(x))
built-in function checks
and returns true if the OUTPUT: False
object passed appears to
be callable, otherwise
false.
7. compile() : takes source
1. code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code as input and returns
2. code = compile(code_str, 'sum.py', 'exec')
a code object which can
3. print(type(code))
later be executed by
4. exec(code)
exec() function. 5. exec(x)
OUTPUT: <class 'code'>
sum = 15

8. exec() : used for the


dynamic execution of
1. x = 8
Python program which
2. exec('print(x==8)')
can either be a string or
3. exec('print(x+4)')
object code and it accepts
large blocks of code, OUTPUT: True
unlike the eval() function 12
which only accepts a
single expression.
9. sum() : used to get the
1. s = sum([1, 2, 4], 10)
sum of numbers of an
2. print(s)
iterable, i.e., list.
OUTPUT: 17

10. any() function returns true1. l = [0, False, 5]


if any item in an iterable is2. print(any(l))
true. Otherwise, it returns
False. OUTPUT: True

11. ascii() : returns a string 1. otherText = 'Pythön is interesting'


containing a printable 2. print(ascii(otherText
representation of an
object and escapes the OUTPUT: 'Pyth\xf6n is interesting'
non-ASCII characters in
the string using \x, \u or
\U escapes
12. bytearray(): returns 1.
a string = "Python is a programming language."
bytearray object and can
2.
convert objects into
3. # string with encoding 'utf-8'
bytearray objects, or
4. arr = bytearray(string, 'utf-8')
create an empty bytearray
5. print(arr)
object of the specified OUTPUT: bytearray(b'Python is a programming
size. language.')

13. eval() :parses the


1. x = 8
expression passed to 2.
it print(eval('x + 1'))
and runs python
expression(code) within OUTPUT: 9
the program.
14. float() :returns a floating- print(float(8.19))
point number from a
number or string. OUTPUT: 8.19

15. format() :returns a print(format(12, "b"))


formatted representation
of the given value. OUTPUT: 1100
16. frozenset():returns an
1. letters = ('m', 'r', 'o', 't', 's')
immutable frozenset
2. fSet = frozenset(letters)
object initialized with
3. print('Frozen set is:', fSet)
elements from the given
4. print('Empty frozen set is:', frozenset())
iterable. OUTPUT: Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()

17. getattr() :returns the


1. class Details:
value of a named attribute
2. age = 22
of an object. If it is not
3. name = "Phill"
found, it returns the
4. details = Details()
default value. 5. print('The age is:', getattr(details, "age"))
6. print('The age is:', details.age)
OUTPUT: The age is: 22
The age is: 22
18. globals() :returns the
1. age = 22
dictionary of the current
2. globals()['age'] = 22
global symbol table. 3. print('The age is:', age)
OUTPUT: The age is: 22
19. iter() : used to return an
1. list = [1,2,3,4,5]
iterator object. It creates
2. listIter = iter(list)
an object which can be
3. # prints '1'
iterated one element at 4.
a print(next(listIter))
time. OUTPUT: 1
20. len() :used to return the
1. strA = 'Python'
length (the number of
2. print(len(strA))
items) of an object. OUTPUT: 6
21. list(): creates a list in
1. String = 'abcde'
python. 2. print(list(String))
OUTPUT: ['a', 'b', 'c', 'd', 'e']

22. locals() :updates and


1. def localsPresent():
returns the dictionary of
2. present = True
the current local symbol
3. return locals()
table. 4. print('localsPresent:', localsPresent())
OUTPUT: localsPresent: {'present': True}

23. map() : used to return 1.


a numbers = (1, 2, 3, 4)
list of results after
2. result = map(calculateAddition, numbers)
applying a given function
3. print(result)
to each item of an OUTPUT: {8, 2, 4, 6}
iterable(list, tuple etc.).
24. memoryview() :returns 1.
a randomByteArray = bytearray('ABC', 'utf-8')
memoryview object of the
2.
given argument. 3. mv = memoryview(randomByteArray)
4.
5. # access the memory view's zeroth index
6. print(mv[0])
OUTPUT: 65

25. object() : returns an


1. python = object()
empty object. It is a base
2.
for all the classes and
3. print(type(python))
holds the built-in
4. print(dir(python))
properties and methods OUTPUT: <class 'object'>
which are default for all ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__',
the classes. '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__',
'__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__',
'__str__', '__subclasshook__']
26. open() :opens the file and
1. f = open("python.txt")
returns a corresponding
2. # specifying full path
file object. 3. f = open("C:/Python33/README.txt")
OUTPUT: Since the mode is omitted, the file is opened
in 'r' mode; opens for reading.

27. chr() :used to get a string result = chr(102) # It returns string representation of a c
representing a character har
which points to a Unicode print(result)
code integer. For example, print("is it string type:", type(result) is str)
chr(97) returns the string OUTPUT: ValueError: chr() arg not in range(0x110000)
'a'.
28. complex() :used to a = complex(1) # Passing single parameter
convert numbers or string b = complex(1,2) # Passing both parameters
print(a)
into a complex number
print(b)
OUTPUT: (1.5+0j)
(1.5+2.2j)

29. delattr() : used to delete an class Student:


attribute from a class. id = 101
name = "Pranshu"
def getinfo(self):
print(self.id, self.name)
1. s = Student()
2. s.getinfo()
3. delattr(Student,'course')
4. s.getinfo()

OUTPUT: 101 Pranshu


AttributeError: course
30. dir() : returns the list of names
1. att = dir()
in the current local scope. 2. print(att)
OUTPUT: ['__annotations__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__']

31. divmod() : used to get


1. result = divmod(10,2)
remainder and quotient of two
2. print(result)
numbers. OUTPUT: (5, 0)

32. enumerate() function returns


1. result = enumerate([1,2,3])
an enumerated object 2. print(result)
3. print(list(result))
OUTPUT: <enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]

33. dict() :is a constructor which


1. result = dict()
creates a dictionary. 2. result2 = dict(a=1,b=2)
3. print(result)
4. print(result2)
OUTPUT: {}
{'a': 1, 'b': 2}

34. filter() :used to get filtered


1. def filterdata(x):
elements. 2. if x>5:
3. return x
4. result = filter(filterdata,(1,2,6))
5. print(list(result))
OUTPUT: [6]

35. hash() :used to get the hash


1. result = hash(21)
value of an object 2. result2 = hash(22.2)
3. print(result)
4. print(result2)
OUTPUT: 21
461168601842737174

36. help() :used to get help related


1. info = help()
to the object passed during the
2. print(info)
call OUTPUT: Welcome to Python 3.5's help utility!

37. min() :used to get the smallest small = min(2225,325,2025)


element from the collection. print(small)
OUTPUT: 325

38. Set(): is a built-in class, and this result = set() # empty set
function is a constructor of this result2 = set('12')
class. print(result)
print(result2)
OUTPUT: set()
{'1', '2'}

39. hex(): used to generate hex result = hex(1)


value of an integer argument result2 = hex(342)
1. print(result)
2. print(result2)
OUTPUT: 0x1
0x156

40. id(): function returns the val2 = id(1200)


identity of an object val3 = id([25,336,95,236,92,3225])
print(val2)
print(val3)
OUTPUT: 139963805666864
139963781994504
41. setattr() : is used to set a value student = Student(102,"Sohan")
to the object's attribute print(student.id)
print(student.name)
setattr(student, 'email','sohan@abc.com')
print(student.email)
OUTPUT: 102
Sohan
sohan@abc.com

42. slice() : used to get a slice of


1. result = slice(5)
elements from the collection of
2. result2 = slice(0,5,3)
elements. 3. print(result)
4. print(result2)
OUTPUT: slice(None, 5, None)
slice(0, 5, 3)

43. sorted() :is used to sort str = "mrecw"


elements. sorted1 = sorted(str)
print(sorted1)

OUTPUT: [‘c’,’e’,’m’,’r’,’w’]
44. next() :is used to fetch next number = iter([256, 32, 82])
item from the collection. item = next(number)
print(item)
1. item = next(number)
2. print(item)
OUTPUT: 256
32

45. input() :is used to get an input val = input("Enter a value: ")
from the user. print("You entered:",val)
OUTPUT: Enter a value: 45
You entered: 45
46. int() :is used to get an integer
1. val = int(10)
value 2. val2 = int(10.52)
3. val3 = int('10')
4. print("integer values :",val, val2, val3)
OUTPUT: integer values: 10 10 10

47. isinstance() :is used to check student = Student(1010,"John")


whether the given object is an lst = [12,34,5,6,767]
instance of that class. print(isinstance(student, Student))
print(isinstance(lst, Student))
OUTPUT: True
False

48. oct() :is used to get an octal val = oct(10)


value of an integer number. print("Octal value of 10:",val)
OUTPUT: Octal value of 10: 0o12

49. ord() function returns an print(ord('8'))


integer representing Unicode print(ord('R'))
code point for the given
Unicode character. OUTPUT: 56
82

50. pow() : is used to compute the


1. print(pow(4, 2))
power of a number. It returns2.x print(pow(-4, 2))
to the power of y. If the third print(pow(4, -2))
argument(z) is given, it returns OUTPUT: 16
x to the power of y modulus z, 16
i.e. (x, y) % z. 0.0625

51. print() : prints the given object


1. print("Python is programming language.")
to the screen or other standard
2. x=7
output devices. 3. print("x =", x)
4. y=x
5. print('x =', x, '= y')
OUTPUT: Python is programming language.
x=7
x=7=y

52. range() :returns an immutable print(list(range(0)))


sequence of numbers starting print(list(range(4)))
from 0 by default, increments print(list(range(1,7 )))
by 1 (by default) and ends at a OUTPUT: []
specified number. [0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]

53. reversed() :returns the String = 'Java'


reversed iterator of the given print(list(reversed(String)))
sequence. Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
OUTPUT: ['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']

54. round() :rounds off the digits of print(round(10))


a number and returns the print(round(10.8))

floating point number. print(round(6.6))

OUTPUT: 10
11
7

55. issubclass() :returns true if class Rectangle:


object argument(first def __init__(rectangleType):
print('Rectangle is a ', rectangleType)
argument) is a subclass of
class Square(Rectangle):
second class(second def __init__(self):
argument). Rectangle.__init__('square')
print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))

OUTPUT: True
False
True
True

56. str(): converts a specified str('4')


value into a string. OUTPUT: '4'

57. tuple() :is used to create a tuple


1. t2 = tuple([1, 6, 9])
object. 2. print('t2=', t2)
OUTPUT: t2= (1, 6, 9)

58. type() :returns the type of the


1. List = [4, 5]
specified object if a single
2. print(type(List))
argument is passed to the
3.
type() built in function. If three
4. Dict = {4: 'four', 5: 'five'}
arguments are passed, then 5.
it print(type(Dict))
returns a new type object. 6.
7. class Python:
8. a=0
9.
10. InstanceOfPython = Python()
11. print(type(InstanceOfPython))
OUTPUT:<class 'list'>
<class 'dict'>
<class '__main__.Python'>

59. vars() : returns the __dict__


1. class Python:
attribute of the given object. 2. def __init__(self, x = 7, y = 9):
3. self.x = x
4. self.y = y
5.
6. InstanceOfPython = Python()
7. print(vars(InstanceOfPython))

OUTPUT: {'y': 9, 'x': 7}


60. zip() :returns a zip object, which numList = [4,5, 6]
maps a similar index of multiple strList = ['four', 'five', 'six']

containers. result = zip()


resultList = list(result)
print(resultList)
result = zip(numList, strList)
resultSet = set(result)
print(resultSet)
OUTPUT: []
{(5, 'five'), (4, 'four'), (6, 'six')}
8.

2.6 DATATYPE CONVERSIONS:

Sometimes, you may need to perform conversions between the built-in types. To convert
between types, you simply use the type name as a function.

There are several built-in functions to perform conversion from one data type to another. These
functions return a new object representing the converted value.

Sr.No. Function & Description


1 int(x [,base])

Converts x to an integer. base specifies the base if x is a string.

2 long(x [,base] )

Converts x to a long integer. base specifies the base if x is a string.

3 float(x)

Converts x to a floating-point number.

4 complex(real [,imag])

Creates a complex number.

5 str(x)

Converts object x to a string representation.

6 repr(x)

Converts object x to an expression string.

7 eval(str)

Evaluates a string and returns an object.

8 tuple(s)

Converts s to a tuple.

9 list(s)
Converts s to a list.

10 set(s)

Converts s to a set.

11 dict(d)

Creates a dictionary. d must be a sequence of (key,value) tuples.

12 frozenset(s)

Converts s to a frozen set.

13 chr(x)

Converts an integer to a character.

14 unichr(x)

Converts an integer to a Unicode character.

15 ord(x)

Converts a single character to its integer value.

16 hex(x)

Converts an integer to a hexadecimal string.

17 oct(x)

Converts an integer to an octal string.


2.7 PRIORITIES OF DATATYPES IN PYTHON:
2.8 PYTHON OPERATORS:

The operator can be defined as a symbol which is responsible for a particular operation
between two operands. Operators are the pillars of a program on which the logic is built in a
specific programming language. Python provides a variety of operators, which are described as
follows.

 Arithmetic operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

2.8.1 Arithmetic Operators:

Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.

Consider the following table for a detailed explanation of arithmetic operators.


2.8.2 Comparison operators:

Comparison operators are used to comparing the value of the two operands and
returns Boolean true or false accordingly. The comparison operators are described in the
following table.

2.8.3 Assignment Operators:

The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.
2.8.4 Bitwise Operators:

The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.

For example,
2.8.5 Logical Operators:

The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.
2.8.6 Membership Operators:

Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

2.8.7 Identity Operators:

The identity operators are used to decide whether an element certain class or type
2.9 Slicing and Indexing:
What is Python Slice?

On our way up the learning curve for Python, we only need to deal with Python
iterables not so huge. But when building an application with it, not always do we need to
retrieve the entire iterable. In such cases, slicing is useful as it lets us choose what to see and
focus on. This aids readability and implements abstraction.

about Copy in Python

To slice a iterable, we use the slicing operator, that is [ ]. To separate the start, stop, and step
values, we use the colon ( : ).
Say you want to declare a list with the values 1,2,3,4,5, and only want to see values 2,3, and 4.
You can slice the list for that.

1. >>> list=[1,2,3,4,5]

2. >>> list[1:4]

[2, 3, 4]

3. The Python Slice() Function

slice() is a constructor that creates a Python Slice object to represent the set of indices that
range(start, stop, step) specifies. With this, we can slice a sequence like a string, a tuple, a list, a
range object, or a bytes object. These are all objects that support sequence protocols and
implement __getitem__() and __len__().
The slice() function returns a Python Slice Object.

different Python Functions


a. The Syntax of Python Slice

Let’s talk about the syntax of Slicing in Python first:

1. slice(stop)

1. slice(start, stop, step)

What are these parameters? Let’s see:

 start- Where to begin slicing (Optional)

 stop- Where to stop slicing+1

 step- How much to increment between each index (Optional)

You’ll see that we have two syntaxes. When we provide only one parameter value, it takes it to
be the stop value. This means to start and step are set to None.

b. Python Slice Example

Let’s take a simple example of Python Slicing.

1. >>>slice(3)

slice(None, 3, None)

We can index this as:

1. >>> l=[1,2,3,4,5]

2. >>> l[slice(3)]

[1, 2, 3]
Note that it displays values at the indices 0, 1, and 2. It stops at index 3.

4. Python String Slice

We can slice a string in Python using the Python slice() method.


2.9.1 Forward Direction Slicing with +ve Step

We can also specify the interval. Slicing a string may give us a substring when the step size is 1.
You must learn about Python String

1. >>> s='helloworld'

2. >>> s[slice(1,6,2)]

‘elw’

 With positive indices-

Like in the previous example, we use positive indices here.

1. >>> s='helloworld'

2. >>> s[slice(1,6)]

‘ellow’

2.9.2 Backward Direction Slicing with -ve Step:

 With negative indices-

But like we’ve seen with lists earlier, we can pass negative indices too. These are what it
traverses from the right.
To read the same value right to left, we do:

1. >>> s='helloworld'

2. >>> s[slice(-5,-10,-1)]

‘wolle’
Here’s how we traverse right to left:
Python String Slice

We index everything from letters to digits and from spaces to characters.

5. Python Slicing Tuples

Now let’s take a look at performing Python Slicing on tuples. Check the following code:

 Positive Indices-

1. >>> t=(1,2,3,4,5)

2. >>> t[slice(2,4)]

(3, 4)

 Negative Indices-

Let’s traverse right to left.

1. >>> t[slice(-1,-5,-2)]

(5, 3)

6. Indexing to Create Python Slice

We have often sliced lists using [ : ]. Let’s try that one more time.

Remember the previous Python Slicing example? Now take a look at this-

1. >>> t[-1:-5:-2]
(5, 3)
So we concur that slicing is a way to choose indices for elements to show. What slice() really
does is give us indices for those. We can use the slice() function as a subscript.

When indexing, what happens when we do not pass one or more of the values?

1. >>> t[:3]#From 0 to 2

(1, 2, 3)

1. >>> t[3:]#From 3 to end

(4, 5)

1. >>> t[:]#From beginning to end

(1, 2, 3, 4, 5)

a. Extended Python Slices with a step value

1. >>> t[::-1]#Reverse

(5, 4, 3, 2, 1)

1. >>> t[::-2]#Reverse with step=2

(5, 3, 1)

1. >>> t[:5:2]#Upto index 5, with step=2

(1, 3, 5)

1. >>> t[:5:-1]#Index 5 to end (already ahead of that), right to left; results in empty tuple

()

know about Methods in Python

1. >>> t
(1, 2, 3, 4, 5)

1. >>> t[len(t)::-3]#End to front, step=3 right to left

(5, 2)

b. Resizing Lists in Python Slices

1. >>> l=[1,2,3,4,5]

2. >>> l[1:4]

[2, 3, 4]

1. >>> l[1:4]=[2,3,3.5,4]

2. >>> l

[1, 2, 3, 3.5, 4, 5]
The length of the slice on the right should be equal to that on the left.

c. Deleting Python Slices

We can also use the del keyword to delete a slice.

1. >>> del l[::4]

2. >>> l

[2, 3, 3.5, 5]

2.10 Decision Making Statements:

Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.


Indentation in Python

For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.

2.10.1 The if statement

The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.

1. if expression:

2. statement

Example 1

1. num = int(input("enter the number?"))

2. if num%2 == 0:

3. print("Number is even")

Output:

enter the number?10

Number is even

Example 2 : Program to print the largest of the three numbers.


1. a = int(input("Enter a? "));

2. b = int(input("Enter b? "));

3. c = int(input("Enter c? "));

4. if a>b and a>c:

5. print("a is largest");

6. if b>a and b>c:

7. print("b is largest");

8. if c>a and c>b:

9. print("c is largest");

Output:

Enter a? 100

Enter b? 120

Enter c? 130

c is largest

2.10.2 The if-else statement

The if-else statement provides an else block combined with the if statement which is executed
in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
The syntax of the if-else statement is given below.

1. if condition:

2. #block of statements

3. else:

4. #another block of statements (else-block)

Example 1 : Program to check whether a person is eligible to vote or not.

1. age = int (input("Enter your age? "))

2. if age>=18:

3. print("You are eligible to vote !!");

4. else:

5. print("Sorry! you have to wait !!");

Output:
Enter your age? 90

You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

1. num = int(input("enter the number?"))

2. if num%2 == 0:

3. print("Number is even...")

4. else:

5. print("Number is odd...")

Output:

enter the number?10

Number is even

2.10.3 The elif statement

The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

1. if expression 1:

2. # block of statements

3.

4. elif expression 2:
5. # block of statements

6.

7. elif expression 3:

8. # block of statements

9.

10. else:

11. # block of statements

Example 1
1. number = int(input("Enter the number?"))

2. if number==10:

3. print("number is equals to 10")

4. elif number==50:

5. print("number is equal to 50");

6. elif number==100:

7. print("number is equal to 100");

8. else:

9. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15

number is not equal to 10, 50 or 100

Example 2

1. marks = int(input("Enter the marks? "))

2. f marks > 85 and marks <= 100:

3. print("Congrats ! you scored grade A ...")

4. lif marks > 60 and marks <= 85:

5. print("You scored grade B + ...")

6. lif marks > 40 and marks <= 60:

7. print("You scored grade B ...")

8. lif (marks > 30 and marks <= 40):

9. print("You scored grade C ...")

10. lse:

11. print("Sorry you are fail ?")


2.11 Looping Statements

The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.

For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.

2.11.1 Why we use loops in python?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the
same code for a finite number of times. For example, if we need to print the first 10 natural
numbers then, instead of using the print statement 10 times, we can print inside a loop which
runs up to 10 iterations.

2.11.2 Advantages of loops

There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).
There are the following loop statements in Python.

2.12 Python for loop

The for loop in Python is used to iterate the statements or a part of the program several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:

2. statement(s)

The for loop flowchart


For loop Using Sequence

Example-1: Iterating string using for loop

1. str = "Python"

2. for i in str:

3. print(i)

Output:

n
Example- 2: Program to print the table of the given number .

1. list = [1,2,3,4,5,6,7,8,9,10]

2. n = 5

3. for i in list:

4. c = n*i

5. print(c)

Output:

10

15

20

25

30

35

40

45

50s

Example-4: Program to print the sum of the given list.

1. list = [10,30,23,43,65,12]

2. sum = 0

3. for i in list:

4. sum = sum+i

5. print("The sum is:",sum)

Output:
The sum is: 183

For loop Using range() function

The range() function

The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

Syntax:

1. range(start,stop,step size)

o The start represents the beginning of the iteration.


o The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to use.
By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

1. for i in range(10):

2. print(i,end = ' ')

Output:

0123456789

Example - 2: Program to print table of given number.

1. n = int(input("Enter the number "))

2. for i in range(1,11):

3. c = n*i

4. print(n,"*",i,"=",c)

Output:
Enter the number 10

10 * 1 = 10

10 * 2 = 20

10 * 3 = 30

10 * 4 = 40

10 * 5 = 50

10 * 6 = 60

10 * 7 = 70

10 * 8 = 80

10 * 9 = 90

10 * 10 = 100

Example-3: Program to print even number using step size in range().

1. n = int(input("Enter the number "))

2. for i in range(2,n,2):

3. print(i)

Output:

Enter the number 20

10

12

14
16

18

We can also use the range() function with sequence of numbers. The len() function is combined
with range() function which iterate through a sequence using indexing. Consider the following
example.

1. list = ['Peter','Joseph','Ricky','Devansh']

2. for i in range(len(list)):

3. print("Hello",list[i])

Output:

Hello Peter

Hello Joseph

Hello Ricky

Hello Devansh

2.12.1 Nested for loop in python

Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n
number of times for every iteration of the outer loop. The syntax is given below.

Syntax

1. for iterating_var1 in sequence: #outer loop

2. for iterating_var2 in sequence: #inner loop

3. #block of statements

4. #Other statements

Example- 1: Nested for loop

1. # User input for number of rows

2. rows = int(input("Enter the rows:"))


3. # Outer loop will print number of rows

4. for i in range(0,rows+1):

5. # Inner loop will print number of Astrisk

6. for j in range(i):

7. print("*",end = '')

8. print()

Output:

Enter the rows:5

**

***

****

*****

Example-2: Program to number pyramid.

1. rows = int(input("Enter the rows"))

2. for i in range(0,rows+1):

3. for j in range(i):

4. print(i,end = '')

5. print()

Output:

22

333

4444
55555

2.12.2 Using else statement with for loop

Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the
for loop which can be executed only when all the iterations are exhausted. Here, we must
notice that if the loop contains any of the break statement then the else statement will not be
executed.

Example 1

1. for i in range(0,5):

2. print(i)

3. else:

4. print("for loop completely exhausted, since there is no break.")

Output:

for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2

1. for i in range(0,5):

2. print(i)

3. break;

4. else:print("for loop is exhausted");


5. print("The loop is broken due to break statement...came out of the loop")

In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.

Output:

2.13 Python While loop

The Python while loop allows a part of the code to be executed until the given condition returns
false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of iterations
then the while loop is most effective to use.

The syntax is given below

1. while expression:

2. statements

Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero value
and false is 0.

While loop Flowchart


Example-1: Program to print 1 to 10 using while loop

1. i=1

2. #The while loop will iterate until condition becomes false.

3. While(i<=10):

4. print(i)

5. i=i+1

Output:

7
8

10

Example -2: Program to print table of given numbers.

1. i=1

2. number=0

3. b=9

4. number = int(input("Enter the number:"))

5. while i<=10:

6. print("%d X %d = %d \n"%(number,i,number*i))

7. i = i+1

Output:

Enter the number:10

10 X 1 = 10

10 X 2 = 20

10 X 3 = 30

10 X 4 = 40

10 X 5 = 50

10 X 6 = 60
10 X 7 = 70

10 X 8 = 80

10 X 9 = 90

10 X 10 = 100

2.13.1 Infinite while loop

If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program to
run continuously in the loop without any disturbance.

Example 1

1. while (1):

2. print("Hi! we are inside the infinite while loop")

Output:

Hi! we are inside the infinite while loop

Hi! we are inside the infinite while loop

Example 2

1. var = 1

2. while(var != 2):

3. i = int(input("Enter the number:"))


4. print("Entered value is %d"%(i))

Output:

Enter the number:10

Entered value is 10

Enter the number:10

Entered value is 10

Enter the number:10

Entered value is 10

Infinite time

2.13.2 Using else with while loop

Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop
is broken using break statement, then the else block will not be executed, and the statement
present after else block will be executed. The else statement is optional to use with the while
loop. Consider the following example.

Example 1

1. i=1

2. while(i<=5):

3. print(i)

4. i=i+1

5. else:

6. print("The while loop exhausted")

Example 2

1. i=1
2. while(i<=5):

3. print(i)

4. i=i+1

5. if(i==3):

6. break

7. else:

8. print("The while loop exhausted")

Output:

In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given limit

1. terms = int(input("Enter the terms "))

2. # first two intial terms

3. a = 0

4. b = 1

5. count = 0

6.

7. # check if the number of terms is Zero or negative

8. if (terms <= 0):

9. print("Please enter a valid integer")

10. elif (terms == 1):

11. print("Fibonacci sequence upto",limit,":")


12. print(a)

13. else:

14. print("Fibonacci sequence:")

15. while (count < terms) :

16. print(a, end = ' ')

17. c=a+b

18. # updateing values

19. a=b

20. b=c

21.

22. count += 1

Output:

Enter the terms 10

Fibonacci sequence:

0 1 1 2 3 5 8 13 21 34

2.14 Conditional Statements

2.14.1 Python break statement

The break is a keyword in python which is used to bring the program control out of the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the
inner loop first and then proceeds to outer loops. In other words, we can say that break is used
to abort the current execution of the program and the control goes to the next line after the
loop.

The break is commonly used in the cases where we need to break the loop for a given
condition.
The syntax of the break is given below.

1. #loop statements

2. break;

Example 1

1. list =[1,2,3,4]

2. count = 1;

3. for i in list:

4. if i == 4:

5. print("item matched")

6. count = count + 1;

7. break

8. print("found at",count,"location");

Output:

item matched

found at 2 location

Example 2

1. str = "python"

2. for i in str:

3. if i == 'o':

4. break

5. print(i);

Output:
p

Example 3: break statement with while loop

1. i = 0;

2. while 1:

3. print(i," ",end=""),

4. i=i+1;

5. if i == 10:

6. break;

7. print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

Example 3

1. n=2

2. while 1:

3. i=1;

4. while i<=10:

5. print("%d X %d = %d\n"%(n,i,n*i));

6. i = i+1;

7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))

8. if choice == 0:
9. break;

10. n=n+1

Output:

2X1=2

2X2=4

2X3=6

2X4=8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?1


3X1=3

3X2=6

3X3=9

3 X 4 = 12

3 X 5 = 15

3 X 6 = 18

3 X 7 = 21

3 X 8 = 24

3 X 9 = 27

3 X 10 = 30

Do you want to continue printing the table, press 0 for no?0


2.14.2 Python continue Statement

The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.

Syntax

1. #loop statements

2. continue

3. #the code to be skipped

Flow Diagram
Consider the following examples.

Example 1

1. i = 0

2. while(i < 10):

3. i = i+1

4. if(i == 5):

5. continue

6. print(i)

Output:

10

Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.

Let's have a look at another example:

Example 2
1. str = "JavaTpoint"

2. for i in str:

3. if(i == 'T'):

4. continue

5. print(i)

Output:

2.14.3 Pass Statement

The pass statement is a null operation since nothing happens when it is executed. It is used in
the cases where a statement is syntactically needed but we don't want to use any executable
statement at its place.

For example, it can be used while overriding a parent class method in the subclass but don't
want to give its specific implementation in the subclass.

Pass is also used where the code will be written somewhere but not yet written in the program
file. Consider the following example.
Example

1. list = [1,2,3,4,5]

2. flag = 0

3. for i in list:

4. print("Current element:",i,end=" ");

5. if i==3:

6. pass

7. print("\nWe are inside pass block\n");

8. flag = 1

9. if flag==1:

10. print("\nCame out of pass\n");

11. flag=0

Output:

Current element: 1 Current element: 2 Current element: 3

We are inside pass block

Came out of pass

Current element: 4 Current element: 5

Python Pass

In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It
just makes the control to pass by without executing any code. If we want to bypass any code
pass statement can be used.
It is beneficial when a statement is required syntactically, but we want we don't want to
execute or execute it later. The difference between the comments and pass is that, comments
are entirely ignored by the Python interpreter, where the pass statement is not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

1. # pass is just a placeholder for

2. # we will adde functionality later.

3. values = {'P', 'y', 't', 'h','o','n'}

4. for val in values:

5. pass

Example - 2:

1. for i in [1,2,3,4,5]:

2. if(i==4):

3. pass

4. print("This is pass block",i)

5. print(i)

Output:

1. 1

2. 2

3. 3

4. This is pass block 4


5. 4

6. 5

We can create empty class or function using the pass statement.

1. # Empty Function

2. def function_name(args):

3. pass

4. #Empty Class

5. class Python:

6. pass
UNIT III –ADVANCED DATA TYPES IN PYTHON
3.1 List:

A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python consists
of six data-types that are capable to store the sequences, but the most common and reliable
type is the list.

A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].

A list can be define as below

1. L1 = ["John", 102, "USA"]


2. L2 = [1, 2, 3, 4, 5, 6]

IIf we try to print the type of L1, L2, and L3 using type() function then it will come out to be
a list.

1. print(type(L1))
2. print(type(L2))

Output:

<class 'list'>
<class 'list'>

Characteristics of Lists

The list has the following characteristics:

 The lists are ordered.


 The element of the list can access by index.
 The lists are the mutable type.
 The lists are mutable types.
 A list can store the number of various elements.

3.2 Tuple:

Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar
to lists since the value of the items stored in the list can be changed, whereas the tuple is
immutable, and the value of the items stored in the tuple cannot be changed.

Creating a tuple

A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can be
defined as follows.
1. T1 = (101, "Peter", 22)
2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

An empty tuple can be created as follows.

T4 = ()

A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by
using their specific index value.

3.3 SET:

A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can
modify it after its creation.

Unlike other collections in Python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print them all
together, or we can get the list of elements by looping through the set.

3.4 Frozenset:

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.

The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().

The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.

3.5 Dictionary:

Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key. It is the mutable data-structure. The dictionary is defined
into element Keys and values.
 Keys must be a single element
 Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be any Python object. In contrast, the keys are the immutable Python object, i.e.,
Numbers, string, or tuple.

3.6 Range:

Python range() function returns an immutable sequence of numbers starting from 0,


increments by 1 and ends at a specified number.

Signature

1. range(start, stop, step)

Parameters

start (optional) : It is an integer number that specifies the starting position. The Default value
is 0.

stop (optional) : It is an integer that specifies the ending position.

step (optional) : It is an integer that specifies the increment of a number. The Default value is
1.

Return

It returns an immutable sequence of numbers starting from 0, increments by 1, and ends at a


specified number.

Python range() Function Example 1

The below example shows the working of range().

1. # empty range
2. print(list(range(0)))
3.
4. # using the range(stop)
5. print(list(range(4)))
6.
7. # using the range(start, stop)
8. print(list(range(1,7 )))

Output:

[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Explanation:

Note: In the above example, we've converted the range to a Python list and returned a
generator-like object that only prints the output on demand.

A range object returned by the range constructor can also be accessed by its index. It can
support both positive and negative indices.

Python range() Function Example 2

The below example creates a list of number between the given numbers using range()
function.

1. start = 5
2. stop = 12
3. step = 4
4.
5. print(list(range(start, stop, step)))

Output:

[5, 9]

4.7 Bytes & Byte Array:

The python bytes() function in Python is used for returning a bytes object. It is an immutable
version of bytearray() function.

It can create empty bytes object of the specified size.

Signature

 bytes(source)
 bytes(encoding)
 bytes(error)

Parameters

source is used to initialize the bytes object. It is an optional parameter.

encoding is optional unless source is string type. It is used to convert the string to bytes using
str.encode() function

errors is also an optional parameter. It is used when the source is string type. Also, when
encoding fails due to some error.

Return

It returns a bytes object.


Let's see some examples of bytes() function to understand it's functionality.

Python bytes() Function Example 1

This is a simple example of converting string into bytes.

1. string = "Hello World."


2. arr = bytes(string, 'utf-8')
3. print(arr)

Output:

b ' Hello World.'

The python bytearray() function returns a bytearray object and can convert objects into
bytearray objects, or create an empty bytearray object of the specified size.

Signature

1. bytearray(x, encoding, error)

Parameters

x (optional) : It is the source that initializes the array of bytes.

encoding (optional) : It is an encoding of the string.

error (optional) : It takes action when the encoding fails.

Return

It returns an array of bytes.

Python bytearray() Function Example 1

The below example shows an array of bytes from a string:

1. string = "Python is programming language."


2.
3. # string with encoding 'utf-8'
4. arr = bytearray(string, 'utf-8')
5. print(arr)

Output:

bytearray(b'Python is programming language.')

3.8 None:
Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also used for the end of lists in
Python.

Example - Special Literals

1. val1=10
2. val2=None
3. print(val1)
4. print(val2)

Output:

10
None

3.9 List indexing and splitting:

The indexing is processed in the same way as it happens with the strings. The elements of the
list can be accessed by using the slice operator [].

The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th
index, the second element of the list is stored at the 1st index, and so on.

We can get the sub-list of the list using the following syntax.

1. list_varible(start:stop:step)

 The start denotes the starting index position of the list.


 The stop denotes the last index position of the list.
 The step is used to skip the nth element within a start:stop

Consider the following example:

1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
6. # Slicing the elements
7. print(list[0:6])
8. # By default the index value is 0 so its starts from the 0th element and go for index -
1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])

Output:

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

Unlike other languages, Python provides the flexibility to use the negative indexing also. The
negative indices are counted from the right. The last element (rightmost) of the list has the
index -1; its adjacent left element is present at the index -2 and so on until the left-most
elements are encountered.

Let's have a look at the following example where we will use negative indexing to access the
elements of the list.

1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])

Output:

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

3.10 Updating List values:

Lists are the most versatile data structures in Python since they are mutable, and their values
can be updated by using the slice and assignment operator.

Python also provides append() and insert() methods, which can be used to add values to the
list.

Consider the following example to update the values inside the list.

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to the second index
4. list[2] = 10
5. print(list)
6. # Adding multiple-element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

The list elements can also be deleted by using the del keyword. Python also provides us the
remove() method if we do not know which element is to be deleted from the list.

Consider the following example to delete the list elements.

1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
3. # It will assign value to the value to second index
4. list[2] = 10
5. print(list)
6. # Adding multiple element
7. list[1:3] = [89, 78]
8. print(list)
9. # It will add value at the end of the list
10. list[-1] = 25
11. print(list)

Output:

[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

3.11 List Operations:

The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.

Let's see how the list responds to various operators.

1. Consider a Lists l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8] to perform operation.

Operator Description Example


Repetition The repetition operator enables the list elements to be L1*2 = [1, 2, 3, 4, 1,
repeated multiple times. 2, 3, 4]
Concatenation It concatenates the list mentioned on either side of l1+l2 = [1, 2, 3, 4, 5,
the operator. 6, 7, 8]
Membership It returns true if a particular item exists in a particular print(2 in l1) prints
list otherwise false. True.
Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Output
1
2
3
4
Length It is used to get the length of the list len(l1) = 4

3.12 Iterating a List:

A list can be iterated by using a for - in loop. A simple list containing four strings, which can
be iterated as follows.

1. list = ["John", "David", "James", "Jonathan"]


2. for i in list:
3. # The i variable will iterate over the elements of the List and contains each element
in each iteration.
4. print(i)

Output:

John
David
James
Jonathan

3.13 Adding Elements to the List:

Python provides append() function which is used to add an element to the list. However, the
append() function can only add value to the end of the list.

Consider the following example in which, we are taking the elements of the list from the user
and printing the list on the console.

1. #Declaring the empty list


2. l =[]
3. #Number of elements will be entered by the user
4. n = int(input("Enter the number of elements in the list:"))
5. # for loop to take the input
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the item
8. l.append(input("Enter the item:"))
9. print("printing the list items..")
10. # traversal loop to print the list items
11. for i in l:
12. print(i, end = " ")

Output:

Enter the number of elements in the list:5


Enter the item:25
Enter the item:46
Enter the item:12
Enter the item:75
Enter the item:42
printing the list items
25 46 12 75 42

3.14 Removing Elements from the List:

Python provides the remove() function which is used to remove the element from the list.
Consider the following example to understand this concept.

Example -

1. list = [0,1,2,3,4]
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
6. print("\nprinting the list after the removal of first element...")
7. for i in list:
8. print(i,end=" ")

Output:

printing original list:


01234
printing the list after the removal of first element...
0134

3.15 List Built-in Functions and Methods:

Python provides the following built-in functions, which can be used with the lists.

SN Function Description Example


1 cmp(list1, It compares the elements of This method is not used in the Python 3
list2) both the lists. and the above versions.
2 len(list) It is used to calculate the L1 = [1,2,3,4,5,6,7,8]
length of the list. print(len(L1))
8
3 max(list) It returns the maximum L1 = [12,34,26,48,72]
element of the list. print(max(L1))
72
4 min(list) It returns the minimum L1 = [12,34,26,48,72]
element of the list. print(min(L1))
12
5 list(seq) It converts any sequence to str = "Johnson"
the list. s = list(str)
print(type(s))
<class list>

Let's have a look at the few list examples.

Example: 1- Write the program to remove the duplicate element of the list.

1. list1 = [1,2,2,3,55,98,65,65,13,29]
2. # Declare an empty list that will store unique values
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:

[1, 2, 3, 55, 98, 65, 13, 29]

Example:2- Write a program to find the sum of the element in the list.

1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
5. print("The sum is:",sum)

Output:

The sum is: 67

Example: 3- Write the program to find the lists consist of at least one common element.

1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
6. print("The common element is:",x)

Output:

The common element is: 2

3.16 Tuple Indexing and Splitting:

The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from
0 and goes to length(tuple) - 1.

The items in the tuple can be accessed by using the index [] operator. Python also allows us
to use the colon operator to access multiple items in the tuple.

Consider the following image to understand the indexing and slicing in detail.
Consider the following example:

1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
5. # It will give the IndexError
6. print(tup[8])

Output:

1
2
3
tuple index out of range

In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
element outside of tuple that raised an IndexError.

1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
8. # element 0 to 6 and take step of 2
9. print(tuple[0:6:2])

Output:

(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

3.17 Tuple Operations:

The operators like concatenation (+), repetition (*), Membership (in) works in the same way
as they work with the list. Consider the following table for more detail.

Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example


Repetition The repetition operator enables the tuple elements T1*2 = (1, 2, 3, 4, 5,
to be repeated multiple times. 1, 2, 3, 4, 5)
Concatenation It concatenates the tuple mentioned on either side T1+T2 = (1, 2, 3, 4, 5,
of the operator. 6, 7, 8, 9)
Membership It returns true if a particular item exists in the tuple print (2 in T1) prints
otherwise false True.
Iteration The for loop is used to iterate over the tuple for i in T1:
elements. print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple. len(T1) = 5

3.18 Tuple Inbuilt Functions:

SN Function Description
1 cmp(tuple1, It compares two tuples and returns true if tuple1 is greater than
tuple2) tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.

3.19 Where use Tuple:

Using tuple instead of list is used in the following scenario.

1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be
changed.

2. Tuple can simulate a dictionary without keys. Consider the following nested structure,
which can be used as a dictionary.

1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)]


3.20 List Vs Tuple:

SN List Tuple
1 The literal syntax of list is shown by The literal syntax of the tuple is shown by the
the []. ().
2 The List is mutable. The tuple is immutable.
3 The List has the a variable length. The tuple has the fixed length.
4 The list provides more functionality The tuple provides less functionality than the
than a tuple. list.
5 The list is used in the scenario in which The tuple is used in the cases where we need
we need to store the simple collections to store the read-only collections i.e., the
with no constraints where the value of value of the items cannot be changed. It can
the items can be changed. be used as the key inside the dictionary.
6 The lists are less memory efficient than The tuples are more memory efficient
a tuple. because of its immutability.

3.21 Nesting List and Tuple:

Nested list is created by placing a comma-separated sequence of sublists.

L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']

Access Nested List Items by Index

You can access individual items in a nested list using multiple indexes.

The indexes for the items in a nested list are illustrated as below:
L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2])
# Prints ['cc', 'dd', ['eee', 'fff']]

print(L[2][2])
# Prints ['eee', 'fff']

print(L[2][2][0])
# Prints eee

3.22 Set Data Structure- Creating a Set:

The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by the
passed sequence.

Example 1: Using curly braces

1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su


nday"}
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday

Example 2: Using set() method

1. Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "


Sunday"])
2. print(Days)
3. print(type(Days))
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}


<class 'set'>
looping through the set elements ...
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday

It can contain any type of element such as integer, float, tuple etc. But mutable elements (list,
dictionary, set) can't be a member of set. Consider the following example.

1. # Creating a set which have immutable elements


2. set1 = {1,2,3, "JavaTpoint", 20.5, 14}
3. print(type(set1))
4. #Creating a set which have mutable element
5. set2 = {1,2,3,["Javatpoint",4]}
6. print(type(set2))

Output:

<class 'set'>

Traceback (most recent call last)


<ipython-input-5-9605bb6fbc68> in <module>
4
5 #Creating a set which holds mutable elements
----> 6 set2 = {1,2,3,["Javatpoint",4]}
7 print(type(set2))

TypeError: unhashable type: 'list'

In the above code, we have created two sets, the set set1 have immutable elements and set2
have one mutable element as a list. While checking the type of set2, it raised an error, which
means set can contain only immutable elements.

Creating an empty set is a bit different because empty curly {} braces are also used to create
a dictionary as well. So Python provides the set() method used without an argument to create
an empty set.

1. # Empty curly braces will create dictionary


2. set3 = {}
3. print(type(set3))
4.
5. # Empty set using set() function
6. set4 = set()
7. print(type(set4))

Output:

<class 'dict'>
<class 'set'>

Let's see what happened if we provide the duplicate element to the set.

1. set5 = {1,2,4,4,5,8,9,9,10}
2. print("Return set with unique elements:",set5)

Output:

Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}

In the above code, we can see that set5 consisted of multiple duplicate elements when we
printed it remove the duplicity from the set.

3.23 Set Operations:

Set can be performed mathematical operation such as union, intersection, difference, and
symmetric difference. Python provides the facility to carry out these operations with
operators or methods

3.24 Adding Items to the Set:

Python provides the add() method and update() method which can be used to add some
particular item to the set. The add() method is used to add a single element whereas the
update() method is used to add multiple elements to the set. Consider the following example.

Example: 1 - Using add() method

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nAdding other months to the set...");
5. Months.add("July");
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)

Output:

printing the original set ...


{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...

Printing the modified set...


{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}

looping through the set elements ...


February
July
May
April
March
August
June
January

To add more than one item in the set, Python provides the update() method. It accepts iterable
as an argument.

Consider the following example.

Example - 2 Using update() function

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nupdating the original set ... ")
5. Months.update(["July","August","September","October"]);
6. print("\nprinting the modified set ... ")
7. print(Months);

Output:

printing the original set ...


{'January', 'February', 'April', 'May', 'June', 'March'}

updating the original set ...


printing the modified set ...
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}

3.25 Removing Items from the Set:

Python provides the discard() method and remove() method which can be used to remove the
items from the set. The difference between these function, using discard() function if the item
does not exist in the set then the set remain unchanged whereas remove() method will
through an error.

Consider the following example.

Example-1 Using discard() method


1. months = set(["January","February", "March", "April", "May", "June"])
2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.discard("January");
6. months.discard("May");
7. print("\nPrinting the modified set...");
8. print(months)
9. print("\nlooping through the set elements ... ")
10. for i in months:
11. print(i)

Output:

printing the original set ...


{'February', 'January', 'March', 'April', 'June', 'May'}

Removing some months from the set...

Printing the modified set...


{'February', 'March', 'April', 'June'}

looping through the set elements ...


February
March
April
June

Python provides also the remove() method to remove the item from the set. Consider the
following example to remove the items using remove() method.

Example-2 Using remove() function

1. months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(months)
4. print("\nRemoving some months from the set...");
5. months.remove("January");
6. months.remove("May");
7. print("\nPrinting the modified set...");
8. print(months)

Output:

printing the original set ...


{'February', 'June', 'April', 'May', 'January', 'March'}

Removing some months from the set...

Printing the modified set...


{'February', 'June', 'April', 'March'}

We can also use the pop() method to remove the item. Generally, the pop() method will
always remove the last item but the set is unordered, we can't determine which element will
be popped from set.

Consider the following example to remove the item from the set using pop() method.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving some months from the set...");
5. Months.pop();
6. Months.pop();
7. print("\nPrinting the modified set...");
8. print(Months)

Output:

printing the original set ...


{'June', 'January', 'May', 'April', 'February', 'March'}

Removing some months from the set...

Printing the modified set...


{'May', 'April', 'February', 'March'}

In the above code, the last element of the Month set is March but the pop() method removed
the June and January because the set is unordered and the pop() method could not determine
the last element of the set.

Python provides the clear() method to remove all the items from the set.

Consider the following example.

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving all the items from the set...");
5. Months.clear()
6. print("\nPrinting the modified set...")
7. print(Months)

Output:

printing the original set ...


{'January', 'May', 'June', 'April', 'March', 'February'}

Removing all the items from the set...


Printing the modified set...
set()

3.26 Difference Between discard() and remove():

Despite the fact that discard() and remove() method both perform the same task, There is one
main difference between discard() and remove().

If the key to be deleted from the set using discard() doesn't exist in the set, the Python will
not give the error. The program maintains its control flow.

On the other hand, if the item to be deleted from the set using remove() doesn't exist in the
set, the Python will raise an error.

Consider the following example.

Example-

1. Months = set(["January","February", "March", "April", "May", "June"])


2. print("\nprinting the original set ... ")
3. print(Months)
4. print("\nRemoving items through discard() method...");
5. Months.discard("Feb"); #will not give an error although the key feb is not available in
the set
6. print("\nprinting the modified set...")
7. print(Months)
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
10. print("\nPrinting the modified set...")
11. print(Months)

Output:

printing the original set ...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through discard() method...

printing the modified set...


{'March', 'January', 'April', 'June', 'February', 'May'}

Removing items through remove() method...


Traceback (most recent call last):
File "set.py", line 9, in
Months.remove("Jan")
KeyError: 'Jan'

3.27 Union of Two Sets:


The union of two sets is calculated by using the pipe (|) operator. The union of the two sets
contains all the items that are present in both the sets.

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}


2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Python also provides the union() method which can also be used to calculate the union of two
sets. Consider the following example.

Example 2: using union() method

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}

3.28 Intersection of Two Sets:

The intersection of two sets can be performed by the and & operator or the intersection()
function. The intersection of the two sets is given as the set of the elements that common in
both sets.
Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}
3. print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}


2. set2 = {"Steve", "Milan", "David", "Martin"}
3. print(set1.intersection(set2)) #prints the intersection of the two sets

Output:

{'Martin', 'David'}

Example 3:

1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)

Output:

{1,2,5}
The intersection_update() method removes the items from the original set that are not present
in both the sets (all the sets if more than one are specified).

The intersection_update() method is different from the intersection() method since it modifies
the original set by removing the unwanted items, on the other hand, the intersection() method
returns a new set.

Consider the following example.

1. a = {"Devansh", "bob", "castle"}


2. b = {"castle", "dude", "emyway"}
3. c = {"fuson", "gaurav", "castle"}
4.
5. a.intersection_update(b, c)
6.
7. print(a)

Output:

{'castle'}

3.29 Difference of Two Sets:

The difference of two sets can be calculated by using the subtraction (-) operator or
intersection() method. Suppose there are two sets A and B, and the difference is A-B that
denotes the resulting set will be obtained that element of A, which is not present in the set B.

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}
Output:

{'Thursday', 'Wednesday'}

Example 2 : Using difference() method

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday", "Sunday"}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days
2

Output:

{'Thursday', 'Wednesday'}

Symmetric Difference of two sets

The symmetric difference of two sets is calculated by ^ operator or symmetric_difference()


method. Symmetric difference of sets, it removes that element which is present in both sets.
Consider the following example:

Example - 1: Using ^ operator

1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)

Output:

{3, 4, 5, 6, 8, 9, 10}

Example - 2: Using symmetric_difference() method


1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)

Output:

{3, 4, 5, 6, 8, 9, 10}

3.30 Set Comparisons:

Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using
which we can check whether a set is a subset, superset, or equivalent to other set. The
boolean true or false is returned depending upon the items present inside the sets.

Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


2. Days2 = {"Monday", "Tuesday"}
3. Days3 = {"Monday", "Tuesday", "Friday"}
4.
5. #Days1 is the superset of Days2 hence it will print true.
6. print (Days1>Days2)
7.
8. #prints false since Days1 is not the subset of Days2
9. print (Days1<Days2)
10.
11. #prints false since Days2 and Days3 are not equivalent
12. print (Days2 == Days3)

Output:

True
False
False

3.31 Frozen set Data Structure:

The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set
cannot be changed and therefore it can be used as a key in the dictionary.

The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().

The frozenset() method is used to create the frozenset object. The iterable sequence is passed
into this method which is converted into the frozen set as a return type of the method.

Consider the following example to create the frozen set.


1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
3. print("\nprinting the content of frozen set...")
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset afte
r creation

Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after
creation
AttributeError: 'frozenset' object has no attribute 'add'

3.32 Dictionary Data Structure- Creating the Dictionary:

The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to define the
dictionary is given below.

Syntax:

1. Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable
object.

Let's see an example to create a dictionary and print its content.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)

Output

<class 'dict'>
Printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Python provides the built-in function dict() method which is also used to create dictionary.
The empty curly braces {} is used to create empty dictionary.

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Creating a Dictionary
7. # with dict() method
8. Dict = dict({1: 'Java', 2: 'T', 3:'Point'})
9. print("\nCreate Dictionary by using dict(): ")
10. print(Dict)
11.
12. # Creating a Dictionary
13. # with each item as a Pair
14. Dict = dict([(1, 'Devansh'), (2, 'Sharma')])
15. print("\nDictionary with each item as a pair: ")
16. print(Dict)

Output:

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Java', 2: 'T', 3: 'Point'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

3.33 Accessing the Dictionary Values:

We have discussed how the data can be accessed in the list and tuple by using the indexing.

However, the values can be accessed in the dictionary by using the keys as keys are unique in
the dictionary.

The dictionary values can be accessed in the following way.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE

Python provides us with an alternative to use the get() method to access the dictionary values.
It would give the same result as given by the indexing.

3.34 Updating Dictionary Values:

The dictionary is a mutable data type, and its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method is
also used to update an existing value.

Note: If the key-value already present in the dictionary, the value gets updated. Otherwise,
the new keys added in the dictionary.

Let's see an example to update the dictionary values.

Example - 1:

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Adding elements to dictionary one at a time
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
10. print("\nDictionary after adding 3 elements: ")
11. print(Dict)
12.
13. # Adding set of values
14. # with a single Key
15. # The Emp_ages doesn't exist to dictionary
16. Dict['Emp_ages'] = 20, 33, 24
17. print("\nDictionary after adding 3 elements: ")
18. print(Dict)
19.
20. # Updating existing Key's Value
21. Dict[3] = 'JavaTpoint'
22. print("\nUpdated key value: ")
23. print(Dict)

Output:
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

Output:

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

3.35 Deleting Elements Using del Keyword:

The items of the dictionary can be deleted by using the del keyword as given below.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output:

<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined

The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.

 Using pop() method

The pop() method accepts the key as an argument and remove the associated value. Consider
the following example.

1. # Creating a Dictionary
2. Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas'}
3. # Deleting a key
4. # using pop() method
5. pop_ele = Dict.pop(3)
6. print(Dict)

Output:

{1: 'JavaTpoint', 2: 'Peter'}

Python also provides a built-in methods popitem() and clear() method for remove elements
from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas
the clear() method removes all elements to the whole dictionary.

3.36 Iterating Dictionary:

A dictionary can be iterated using for loop as given below.

Example 1
# for loop to print all the keys of a dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. for x in Employee:
3. print(x)

Output:

Name
Age
salary
Company

Example 2

#for loop to print all the values of the dictionary

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. for x in Employee:
3. print(Employee[x])

Output:

John
29
25000
GOOGLE

Example - 3

#for loop to print the values of the dictionary by using values() method.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. for x in Employee.values():
3. print(x)

Output:

John
29
25000
GOOGLE

Example 4

#for loop to print the items of the dictionary by using items() method.
1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. for x in Employee.items():
3. print(x)

Output:

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')

3.37 Properties of Dictionary Keys:

1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than
one value for a single key, then the value which is last assigned is considered as the value of
the key.

Consider the following example.

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Nam
e":"John"}
2. for x,y in Employee.items():
3. print(x,y)

Output:

Name John
Age 29
Salary 25000
Company GOOGLE

2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as
the key, but we cannot use any mutable object like the list as the key in the dictionary.

Consider the following example.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[1


00,201,301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)

Output:

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'
3.38 Built-in Dictionary Functions:

The built-in python dictionary methods along with the description are given below.

SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it
returns false.
2 len(dict) It is used to calculate the length of the dictionary.
3 str(dict) It converts the dictionary into the printable string representation.
4 type(variable) It is used to print the type of the passed variable.

3.39 Built-in Dictionary Methods:

The built-in python dictionary methods along with the description are given below.

SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the
None, /) values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed
key.
5 dict.has_key(key) It returns true if the dictionary contains the
specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= It is used to set the key to the default value if the
"None") key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value
pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()
UNIT IV

4.1 Python Functions:

A function is a set of statements that take inputs, do some specific computation and
produces output. The idea is to put some commonly or repeatedly done task together and
make a function, so that instead of writing the same code again and again for different
inputs, we can call the function. Python also provides built-in functions like print(), etc.
but we can also create your own functions. These functions are called user-defined
functions.

4. 2 Advantages of functions in Python

1. It helps to divide the large programs into small groups so that we can read the code, and
debug the program faster and better.
2. Python Functions stop us from writing the same logic various times. We can bind the
logic in one function and then call the same over and over.
3. Many persons can work on the same program by assigning different functions to each of
them.
4. It encourages us to call the same function with different inputs over multiple times.

4.3 Creating functions:

 We can create function using def keyword

Syntax of Function

def function_name(parameters):

"""docstring""“

statement(s)

Above shown is a function definition that consists of the following components.


 Keyword def that marks the start of the function header.

 A function name to uniquely identify the function. Function naming follows the
same rules of writing identifiers in Python.

 Parameters (arguments) through which we pass values to a function. They are optional.

 A colon (:) to mark the end of the function header.

 Optional documentation string (docstring) to describe what the function does.

 One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).

 An optional return statement to return a value from the function

Example of a function

def greet(name):

""" This function greets to the person

passed in as a parameter """

print("Hello, " + name + ". Good morning!")

Docstrings :

 The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
 Although optional, documentation is a good programming practice. Unless you can
remember what you had for dinner last week, always document your code.
 In the above example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines. This string
is available to us as the __doc__ attribute of the function.

For example:

Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)

This function greets to

the person passed in as

a parameter

4.4 Function calling

How to call a function in python?

Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.

Example:

>>> greet('Paul')

Hello, Paul. Good morning!

Ex:

def greet(name):

""" This function greets to the

person passed in as a parameter """

print("Hello, " + name + ". Good morning!")

greet('Paul')

return statement in functions:

 The return statement is used to exit a function and go back to the place from where it
was called.

Syntax of return
return [expression_list]

 This statement can contain an expression that gets evaluated and the value is returned.
 If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.

For example:

>>> print(greet("May"))

Hello, May. Good morning!

None

 Here, None is the returned value since greet() directly prints the name and
no return statement is used.

Example of return

def absolute_value(num):

"""This function returns the

absolute value of the entered

number""“

if num >= 0:

return num

else:

return –num

print(absolute_value(2))

print(absolute_value(-4))

Output
4

4.5 Parameters in Function:

 A parameter is the variable listed inside the parentheses in the function definition.
In Python, you can define a function that takes variable number of parameters
Ex:
def greet(name, msg):
"""This function greets to the person with the provided
message"""
print("Hello", name + ', ' + msg)
greet("Monica", "Good morning!")
Output
Hello Monica, Good morning!
 Here, the function greet() has two parameters. Since we have called this function with
two arguments, it runs smoothly and we do not get any error.

If we call it with a different number of parameters, the interpreter will show an error
message.

Below is a call to this function with one and no parameters along with their respective error
messages.

>>> greet("Monica") # only one argument

TypeError: greet() missing 1 required positional argument: 'msg‘

>>> greet() # no arguments

TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'


4.6. Call by reference in Python
 In Python, call by reference means passing the actual value as an argument in the
function. All the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by the reference.
 All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back in
the calling function.

For example ,

# Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist.append([1,2,3,4])

print("Values inside the function: ", mylist)

return

# Now you can call changeme function

mylist = [10,20,30]

changeme(mylist)

print("Values outside the function: ", mylist)

 Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −

Output:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]

Values outside the function: [10, 20, 30, [1, 2, 3, 4]]


There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.

For example,

# Function definition is here

def changeme( mylist ):

"This changes a passed list into this function"

mylist = [1,2,3,4]; # This would assig new reference in mylist

print("Values inside the function: ", mylist)

return

# Now you can call changeme function

mylist = [10,20,30];

changeme( mylist );

print("Values outside the function: ", mylist)

 The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result –

Output:

Values inside the function: [1, 2, 3, 4]

Values outside the function: [10, 20, 30]


4.7. Types of Arguments:

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are
passed into a function.
From a function's perspective:
 A parameter is the variable listed inside the parentheses in the function definition.
 An argument is the value that are sent to the function when it is called.

There are three types of Python arguments:

1. Default Arguments
2. Keyword Arguments
3. Arbitrary Arguments

Fig: Types of arguments

1. Default Arguments:
 Function arguments can have default values in Python.
 We can provide a default value to an argument by using the assignment operator (=).
Here is an example:

def greet(name, msg="Good morning!"):

"""
This function greets to the person with the provided message. If the message is not
provided, it defaults to "Good morning!"
"""
print("Hello", name + ', ' + msg)
greet("Python")
greet(“python”, “programming”)
Output:
Hello Python, Good morning!
Hello Python, programming

 In this function, the parameter name does not have a default value and is required
(mandatory) during a call.
 On the other hand, the parameter msg has a default value of "Good morning!". So, it is
optional during a call. If a value is provided, it will overwrite the default value.
 Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
 This means to say, non-default arguments cannot follow default arguments. For example,
if we had defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument

4.7.1 Python Keyword Arguments


 When we call a function with some values, these values get assigned to the arguments
according to their position.For example, in the above function greet(), when we called it as
greet("Bruce", "How do you do?"), the value "Bruce" gets assigned to the argument name
and similarly "How do you do?" to msg. Python allows functions to be called using
keyword arguments. When we call functions in this way, the order (position) of the
arguments can be changed. Following calls to the above function are all valid and produce
the same result.
Program:
# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce")
1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")
Output:
Hello Bruce, How do you do?
Hello Bruce, How do you do?
Hello Bruce, How do you do?
As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments. Having a
positional argument after keyword arguments will result in errors.
For example, the function call as follows:
greet(name="Bruce","How do you do?")
Will result in an error:
SyntaxError: non-keyword arg after keyword arg

4.7.2 Python Arbitrary Arguments


 Sometimes, we do not know in advance the number of arguments that will be passed into
a function. Python allows us to handle this kind of situation through function calls with
an arbitrary number of arguments. In the function definition, we use an asterisk (*) before
the parameter name to denote this kind of argument.
Here is an example.
def greet(*names):
"""This function greets all the
person in the names tuple.""“
# names is a tuple with arguments
for name in names:
print("Hello", name)
greet("Monica", "Luke", "Steve", "John")
Output:
Hello Monica
Hello Luke
Hello Steve
Hello John

4.7.3 Variable-Length Arguments in Python:


Some functions have no arguments, others have multiple. There are times we have functions with
arguments we don't know about beforehand. We may have a variable number of arguments
because we want to offer a flexible API to other developers or we don't know the input size.
With Python, we can create functions to accept any amount of arguments. These functions can
accept an unknown amount of input, either as consecutive entries or named arguments.

In the following Python program we are calling a function and passing two integer values and it
is returning back the sum.

# func

def sum(x, y):

return x + y

result = sum(10, 20)

print(result) # 30

So, the above code will print 30 as output.

Now, imagine we want to create a sum function that can take any number of arguments (like 2,
3, 4 ...).The problem with above sum function is that we can only pass two arguments.Python
allows us to create functions that can take multiple arguments. So, lets create multi-argument
functions.

Following is the syntax to create a function that can take variable length arguments.

def func(*args):

# body of the function

Where, func is the name of the function and *args holds variable length arguments.

Passing multiple arguments:

 In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.

Program:
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
Output:
<class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40)

So, we can see that the args variable is of type tuple and we are also able to print all the values
that were passed to the function as a tuple.
Accessing multiple arguments:

Since the multiple arguments passed to the function are tuple so we can access them using for
loop. In the following Python program we are printing out the individual argument.

Program:

def sum(*args):

for arg in args:

print(arg)

print('sum(10, 20)')

sum(10, 20)

print('sum(10, 20, 30)')

sum(10, 20, 30)

print('sum(10, 20, 30, 40)')

sum(10, 20, 30, 40)

The above code will given us the following output.


sum(10, 20)
10
20
sum(10, 20, 30)
10
20
30
sum(10, 20, 30, 40)
10
20
30
40

So, now that we are able to access the individual argument passed to the function let's go ahead
and modify the sum function that we are working on to return us the sum of the arguments.

Multiple arguments sum function:

Program:
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Output:
30
60
100

4.8 Scope of Variables:


 A variable is only available from inside the region it is created. This is called scope.
 There are 3 basic scopes of variables in Python
1. Global Variables
2. Local Variables
3. Nonlocal Variables

1. Global Variables:
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside of the function.
Example : Create a Global Variable
x = "global”
def foo():
print("x inside:", x) //inside
foo()
print("x outside:", x) //outside
In the above code, we created x as a global variable and defined a foo() to print the global variable
x. Finally, we call the foo() which will print the value of x.
What if you want to change the value of x inside a function?
x = "global"
def foo():
x=x*2
print(x)
foo()
Output:
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not defined
inside foo().

2. Local Variables:
 A variable declared inside the function's body or in the local scope is known as a local
variable.
Example : Accessing local variable outside the scope
def foo():
y = "local"
foo()
print(y)
Output:
NameError: name 'y' is not defined
The output shows an error because we are trying to access a local variable y in a global scope
whereas the local variable only works inside foo() or local scope.
Example: Create a Local Variable
Normally, we declare a variable inside the function to create a local variable.
def foo():
y = "local"
print(y)
foo()
Output:
local
Let's take a look at the earlier problem where x was a global variable and we wanted to modify x
inside foo().
Global and local variables
Here, we will show how to use global variables and local variables in the same code.
Example : Using Global and Local variables in the same code
x = "global "
def foo():
global x
y = "local"
x=x*2
print(x)
print(y)
foo()
Output:
global global
local
In the above code, we declare x as a global and y as a local variable in the foo(). Then, we use
multiplication operator * to modify the global variable x and we print both x and y.After calling the
foo(), the value of x becomes global global because we used the x * 2 to print two times global.
After that, we print the value of local variable y i.e local.

Example : Global variable and Local variable with same name


x=5
def foo():
x = 10
print("local x:", x)
foo()
print("global x:", x)
Output:
local x: 10
global x: 5
In the above code, we used the same name x for both global variable and local variable. We get a
different result when we print the same variable because the variable is declared in both scopes, i.e.
the local scope inside foo() and global scope outside foo().
When we print the variable inside foo() it outputs local x: 10. This is called the local scope of the
variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the
global scope of the variable.
3. Nonlocal Variables:
 Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
 We use nonlocal keywords to create nonlocal variables.
Example : Create a nonlocal variable
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
Output:
inner: nonlocal
outer: nonlocal
In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal
variable. The inner() function is defined in the scope of another function outer().
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
4.8 Python Anonymous/Lambda Function:
 In Python, an anonymous function is a function that is defined without a name.
 While normal functions are defined using the def keyword in Python,
 anonymous functions are defined using the lambda keyword.
 Hence, anonymous functions are also called lambda functions.
How to use lambda Functions in Python?
A lambda function in python has the following syntax.
Syntax of Lambda Function in python
lambda arguments: expression
 Lambda functions can have any number of arguments but only one expression.
 The expression is evaluated and returned. Lambda functions can be used wherever
function objects are required.
Here is an example of lambda function that doubles the input value.
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
 In the above program, lambda x: x * 2 is the lambda function. Here x is the argument
and x * 2 is the expression that gets evaluated and returned.
 This function has no name. It returns a function object which is assigned to the identifier
double.
double = lambda x: x * 2
If we use a normal function. The statement is nearly the same as:
def double(x):
return x * 2
4.9 Strings Indexing and Splitting:
4.9.1 Strings Indexing:
For example in string, we can access individual character using indexing and a range of
characters using slicing. Index starts from 0 and ends with length -1, and this index must
be an integer.
str=“HELLO”
H E L L O
0 1 2 3 4

Forward indexing

Positive indexing:
In indexing, for accessing the individual character we can use slice operator [ ], inside
that specify index number.
str[0]=‘H’
str[1]=‘E’
str[2]=‘L’
str[3]=‘L’
str[3]=‘O’
if we try to access a character out of index range then interpreter will raise an IndexError.
>>> str[5]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str[5]
IndexError: string index out of range
The index must be an integer if we try to access the data with non-integer indexes values
then interpreter raises an TypeError.

negative indexing:
Python allows negative indexing for its sequence. The index of -1 refers to the last item,
-2 refers to last 2nd item. This is called backward indexing.
str=‘hello’
H E L L O

-5 -4 -3 -2 -1

Backward indexing
>>> str[-1]
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
4.9.2 String splitting:
split()
split() method breaks up a string at the specified separator and returns a list of strings.
syntax of split() is:
str.split(separator)
separator (optional)- It is a delimiter. The string splits at the specified separator. If
the separator is not specified, any whitespace (space) string is a separator.
Ex:
text='hello python programming'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.split(', '))
grocery1 = 'Milk, Chicken: Bread:coffee'
# Splitting at ':'
print(grocery1.split(':'))
Output:
[‘hello', ‘python', ‘programming']
['Milk', 'Chicken', 'Bread']
['Milk, Chicken, Bread']
4.10 String Operators:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied
on the python string are as below:
 Assignment operator: “=.”
 Concatenate operator: “+”
 String repetition operator: “*”
 String slicing operator: “[]”
 String comparison operator: “==” & “!=”
 Membership operator: “in” & “not in”
 Escape sequence operator: “\”
 String formatting operator: “%” & “{}”
String Operators in Python:
1. Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “. Python
string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple quotes[‘’’
‘’’]. var_name = “string” assigns “string” to variable var_name.
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:

2. Concatenate Operator “+”


Two strings can be concatenated or join using “+” operator in python, as explained in the
below example code:
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)

Output:

3.String Repetition Operator “*”


The same string can be repeated in python by n times using string*n as explained in the
below example.
Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
4. String slicing operator “[]”
Characters from a specific index of the string can be accessed with the string[index]
operator. The index is interpreted as a positive index starting from 0 from the left side
and a negative index starting from -1 from the right side.

String H E L L O W O R L D

Positive index 0 1 2 3 4 5 6 7 8 9

Negative index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

 string[a]: Returns a character from a positive index a of the string from the left side as

displayed in the index graph above.

 string[-a]: Returns a character from a negative index a of the string from the right side as

displayed in the index graph above.

 string[a:b]: Returns characters from positive index a to positive index b of the as

displayed in index graph above.

 string[a:-b]: Returns characters from positive index a to the negative index b of the

string as displayed in the index graph above.

 string[a:]: Returns characters from positive index a to the end of the string.

 string[:b] Returns characters from the start of the string to the positive index b.
 string[-a:]: Returns characters from negative index a to the end of the string.

 string[:-b]: Returns characters from the start of the string to the negative index b.

 string[::-1]: Returns a string with reverse order.

Code:

string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])

Output:

5. String Comparison Operator “==” & “!=”

The string comparison operator in python is used to compare two strings.


 “==” operator returns Boolean True if two strings are the same and return Boolean False
if two strings are not the same.
 “!=” operator returns Boolean True if two strings are not the same and return Boolean
False if two strings are the same.

These operators are mainly used along with if condition to compare two strings where the
decision is to be taken based on string comparison.

Code:

string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4)
print(string2==string3)
print(string1!=string4)
print(string2!=string3)

Output:

6. Membership Operator “in” & “not in”:

 Membership operator is used to searching whether the specific character is part/member


of a given input python string.

 “a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is
not in the string.
 “a” not in the string: Returns boolean True if “a” is not in the string and returns False
if “a” is in the string.

A membership operator is also useful to find whether a specific substring is part of a given
string.

Code:

string1 = "helloworld"
print("w" in string1)
print("W" in string1)
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
print("Hello" in string1)
print("hello" not in string1)

Output:

7. Escape Sequence Operator “\.”

To insert a non-allowed character in the given input string, an escape character is used.
An escape character is a “\” or “backslash” operator followed by a non-allowed character.
An example of a non-allowed character in python string is inserting double quotes in the
string surrounded by double-quotes.
1. Example of non-allowed double quotes in python string:

Code:

string = "Hello world I am from "India""


print(string)

Output:

2. Example of non-allowed double quotes with escape sequence operator:

Code:

string = "Hello world I am from \"India\""

print(string)

Output:

8. String Formatting Operator “%.”

String formatting operator is used to format a string as per requirement. To insert another
type of variable along with string, the “%” operator is used along with python string. “%”
is prefixed to another character indicating the type of value we want to insert along with the
python string. Please refer to the below table for some of the commonly used different
string formatting specifiers:

Operator Description

%d Signed decimal integer

%u unsigned decimal integer

%c Character

%s String

%f Floating-point real number

Code:

name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:

4.11 Python File Handling:

What is a file?
 File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
 Since, random access memory (RAM) is volatile which loses its data when computer is turned
off, we use files for future use of the data.
 If you are working in a large software application where they process a large number of data,
then we cannot expect those data to be stored in a variable as the variables are volatile in
nature.
 As files are non-volatile in nature, the data will be stored permanently in a secondary device
like Hard Disk
How Python Handle Files?
 If you are working in a large software application where they process a large number of
data, then we cannot expect those data to be stored in a variable as the variables are
volatile in nature.
 As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk.
Types Of File in Python
There are two types of files in Python. They are:
1. Binary file
2. Text file
1. Binary files in Python
 Most of the files that we see in our computer system are called binary files.
Example:
Document files: .pdf, .doc, .xls etc.
Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal text editor
but we can’t read the content present inside the file. That’s because all the binary files will be
encoded in the binary format, which can be understood only by a computer or machine. For
handling such binary files we need a specific type of software to open it.
 For Example, You need Microsoft word software to open .doc binary files. Likewise, you
need a pdf reader software to open .pdf binary files.
2. Text files in Python:
Text files don’t have any specific encoding and it can be opened in normal text editor itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Python File Handling Operations
 Most importantly there are 4 types of operations that can be handled by Python on files:
1. Open
2. Read
3. Write
4. Close
 Other operations include:
1. Rename
2. Delete
4.12 opening a File:

 Python provides the open() function which accepts two arguments, file name and access
mode in which the file is accessed.
 The function returns a file object which can be used to perform various operations like
reading, writing, etc.
 File object:
 File objects contain methods and attributes that can be used to collect information about
the file you opened. They can also be used to manipulate said file.
 To get a file object we use Python’s built-in open function

Syntax:
file_object = open(“filename”, “mode”)
where file_object is the variable to add the file object.
 File objects contain methods and attributes that can be used to collect information
about the file you opened. They can also be used to manipulate said file.
 mode – tells the interpreter and developer which way the file will be used.
Access Modes for File Objects:

 r: Opens the file in read-only mode. Starts reading from the beginning of the file and is
the default mode for the open() function.
 w: Opens in write-only mode. The pointer is placed at the beginning of the file and this
will overwrite any existing file with the same name. It will create a new file if one with
the same name doesn't exist.
 a: Opens a file for appending new information to it. The pointer is placed at the end of
the file. A new file is created if one with the same name doesn't exist.
 r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
 w+: Opens a file for writing and reading.
 a+: Opens a file for both appending and reading.
 rb: Opens the file as read-only in binary format and starts reading from the beginning
of the file. While binary format can be used for different purposes, it is usually used when
dealing with things like images, videos, etc.
 wb: Opens a write-only file in binary mode.

 ab: Opens a file for appending in binary mode.

 rb+: Opens a file for reading and writing in binary mode.

 wb+: Opens a file for writing and reading in binary mode.

 ab+: Opens a file for both appending and reading in binary mode

Ex:
#Create a text file
>>> f=open(“fdp.txt","w")
>>> f
Output:
<_io.TextIOWrapper name='demo.txt' mode='w' encoding='cp1252'>
Or
>>> with open("fdp1.py","w") as f:
f.write("this is 1st program")
f.close()
#to know the current path
>>> import os
>>> os.path
Output:
<module'ntpath'fromC:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-
32\\lib\\ntpath.py'>

4.13 Reading a Text File in Python:


 If you need to extract a string that contains all characters in the file.
Syntax:
fileobject.read()
Ex;
>>> f=open(“fdp.txt","r")
>>>a= f.read()
>>>print(a) // to print all characters in the file
Ex:
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose , if we want to get a character ,then use slicing concept
>>> f=open("fdp.py","r")
>>> a=f.read()
>>> print(a[2])
i
>>> print(a[0:])
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose, I want to read a file is to call a certain number of characters.
>>> f=open(“fdp.txt","r")
>>> a=f.read(22)
>>>print(a)
Ex:
this is first line
Thi
4.14 How to read multiple lines in file:
If you want to read a first line from file, then you use the readline() function.
Ex: #Displaying first line from file
>>> f=open(“fdp.txt","r")
>>> a=f.readline() or >>> print(open(“fdp.txt","r").readline())

this is first line


>>>print(a)
this is first line
For suppose, in first line I want 2nd character then use a[1]
>>> f=open("fdp.py","r")
>>> a=f.readline()
>>> print(a[1])
H
We can also specify bytes in readline(),which returns specified bytes from first line.
Return only the five first bytes from the first line:
>>>f= open(“fdp.txt", "r")
>>>print(f.readline(5))
This
readlines():
If you want to read a data line by line from file, then you use the readlines() function
Ex: #Displaying first line from file

>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>> print(a[0])
this is first line
#Displaying second line from file
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[1])
This is file concepts in python
For suppose, If we want last line then use a[-1]
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[-1])
previous function is write function
4.15. Looping through the File:
 We can iterate through the file handle, no need to call readlines().on large files, you don't have
to read all the lines (that's what readlines() does) at once.
 In a with-statement, use open(file, mode) with mode as "r" to open file for reading. Inside
the with-statement, use a for-loop to iterate through the lines. Then, call str.strip() to strip the
end-line break from each line.
SAMPLE.TXT
This is
an existing file.
-----------------------------------
with open("sample.txt", "r") as a_file:
for line in a_file:
stripped_line = line.strip()
print(stripped_line)
OUTPUT
This is
an existing file.

4.16 How to write in to file:


 In order to write into a file in Python, we need to open it in write w, or append a .
 Writing a string or sequence of bytes (for binary files) is done using
the write() method. This method returns the number of characters written to the file.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()
 Then open fdp.txt file in your path.
 We need to be careful with the w mode, as it will overwrite into the file if it already
exists. Due to this, all the previous data are erased.
How to append new data in to existing file:
>>> f=open(“fdp.txt","a")
>>> f.write(" \n This is file concepts in python\n")
35
>>> f.write(" \nThis is append method")
23
>>> f.close()
NOTE: open fdp.txt file for output
Shall we write multiple lines in file with write() function?
Answer is NO
How to write multiple lines in file:
writelines():
 The method writelines() writes a sequence of strings to the file.
 The sequence can be any iterable object producing strings, typically a list of strings.
 There is no return value.
Syntax:
fileObject.writelines( sequence )
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write function"])
>>>f.close()
Note: open fdp txt file in your path and see the text

Python Close File


 In order to close a file, we must first open the file. In python, we have an in-built method
called close() to close the file which is opened.
 Whenever you open a file, it is important to close it, especially, with write method.
Because if we don’t call the close function after the write method then whatever data we have
written to a file will not be saved into the file.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
my_file.close()

Python Rename():
 Python provides us with an “os” module which has some in-built methods that would
help us in performing the file operations such as renaming and deleting the file.
 In order to use this module, first of all, we need to import the “os” module in our program
and then call the related methods.
rename() method:
 This rename() method accepts two arguments i.e. the current file name and the new
file name.
Syntax:
os.rename(current_file_name, new_file_name)
Ex:
>>> import os
>>> os.rename("fdp1.txt","fdp2.txt")
Python remove() method:
We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example:
import os
os.remove("fdp2.txt")

4.17. File Pointer Position:


Python file method tell() returns the current position of the file read/write pointer within the
file.
1. tell() in Python
tell() tells us the current position of the cursor
Syntax

Following is the syntax for tell() method −


fileObject.tell()

Return Value
This method returns the current position of the file read/write pointer within the file.

Ex:

>>> f=open(“fdp.txt","r")

>>> f.seek(20)

20

>>> print(f.readline())

This is file concepts in python\n'

>>> print(f.tell())

20

4.18.Modifying File Pointer Position:

 The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.

 If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end of the
file would be taken as the reference position.

seek() in python:

 The seek() method sets the current file position in a file stream.
Syntax

file.seek(offset)

Where offset is a number representing the position to set the current file stream position.

Ex:

>>> f=open(“fdp.txt","r")

>>> f.seek(20)

>>> print(f.readline())

#output: ‘This is file concepts in python\n'

4.19 File Built-in Methods


1. close()
2. fileno()
3. read()
4. readable()
5. readline( )
6. readlines()
7. seek()
8. seekable()
9. tell()
10. truncate()
11. writable()
12. write()
13. writelines()
14. detach
1. close() in Python
With close(), we close a file to free up the resources held by it.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()
2. fileno() in Python
 It is used to get the file number i.e. the file descriptor as an integer of the stream.
 It may return an error if an operating system does not use a file descriptor of the file is
closed.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.fileno()
4

3. read() in Python
The read() method returns the specified number of bytes from the file.
Syntax:
file.read(size)
 Where size is the number of bytes to be read from the file.
Ex:
>>> f=open("abc.txt","r")
>>> a=f.read()
>>> print(a)
4. readable() in Python
This returns True if the object is readable
Ex:
>>> f=open("abc.txt",”r")
>>> f.readable()
True
>>> f=open("abc.txt","w")
>>> f.readable()
False
>>> f=open("abc.txt","a")
>>> f.readable()
False

5. readline( ) in Python:
The readline() method returns first line from the file.
Syntax
file.readline(size)
Ex:
>>> f=open("abc.txt","r")
>>> a=f.readline()
>>>print(a)
welcome to python programming
You can also specified how many bytes from the line to return, by using the size parameter.
Return only the five first bytes from the first line:
>>>f= open("demofile.txt", "r")
>>>print(f.readline(5))
6. readlines() in Python:

readlines() method returns a list containing each line in the file as a list item.
Ex:
>>> f=open("demo.txt","r")
>>> a=f.readlines()
>>> print(a)
['hi...hello...python‘,’welcome to python world']

7. seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
>>> print(f.readline()) #output: ‘This is file concepts in python\n'
8. seekable() in Python:
This returns whether file allows us to change the file position
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seekable()
True
9. tell() in Python
tell() tells us the current position of the cursor.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
This is file concepts in python\n'
>>> print(f.tell())
20
10. truncate():
 This method truncates the file's size. If the optional size argument is present, the file
is truncated to (at most) that size.
 The size defaults to the current position
 This method would not work in case file is opened in read-only mode.
Syntax:
fileObject.truncate( [ size ])
Example:
>>> f=open(“fdp.txt","w")
>>> #fdp.txt size is 139bytes
>>> f.truncate()
0 >>> #fdp.txt size is 0 bytes

11. writable() in Python


This returns True if the stream can be written to.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.writable()
True
>>> f=open(“fdp.txt","r")
>>> f.writable()
False
12. write(s) in Python
 This method takes string ‘s’, and writes it to the file. Then, it returns the number of
characters written.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("truncate function")
17

13. writelines():
 The method writelines() writes a sequence of strings to the file.
 The sequence can be any iterable object producing strings, typically a list of strings.
 There is no return value.
Syntax:
fileObject.writelines( sequence)
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write function"])
>>>f.close()
Note: open new.txt file in your path and see the text
14. detach( ):
This detaches the underlying binary buffer from TextIOBase and returns raw stream from buffer.
syntax:
f.detach()
Ex:
>>> f=open("ab.txt","r")
>>> f.detach()
<_io.BufferedReader name='ab.txt'>
>>> f.read()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
f.read()
ValueError: underlying buffer has been detached

Python file Built-in attributes:

Ex:
>>> f=open("new.txt","w")
>>> print("Name of the File:",f.name)
Name of the File: new.txt
>>> print("Mode of the File:",f.mode)
Mode of the File: w
>>> print("closed?:",f.closed)
closed?: False
>>> f.close()
>>> print("closed?:",f.closed)
closed?: True
>>> print("Encoding of the File:",f.encoding)
Encoding of the File: cp1252
Encoding in Files
File encoding represents converting characters into a specific format which only a machine
can understand.
Different machines have different encoding format as shown below.
 Microsoft Windows OS uses ‘cp1252’ encoding format by default.
 Linux or Unix OS uses ‘utf-8’ encoding format by default.
 Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.

4.20 Python Exceptions:

What Are Exceptions?

Errors:

 In the context of software, errors are either syntactical or logical in nature.


 Syntax errors indicate errors with the construct of the software and cannot be
executed by the interpreter or compiled correctly.
 These errors must be repaired before execution can occur.
 Once programs are semantically correct, the only errors that remain are logical.
 Logical errors/ Run time errors can either be caused by lack of or invalid input, or
by the inability of the logic to generate, calculate, or otherwise produce the desired
results based on the input.

 Run time errors are also called Exceptions

 These errors are sometimes known as domain and range failures

Common Exceptions:
 An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
 Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to
tackle with.
 Python provides us with the way to handle the Exception so that the other part of the code
can be executed without any disruption. However, if we do not handle the exception, the
interpreter doesn't execute all the code that exists after the that.
There are two types of exception:
1. System defined exceptions
2. User-defined exceptions
1. System defined exceptions:

A list of System defined exceptions that can be thrown from a normal python program is
given below.

2. ZeroDivisionError: Occurs when a number is divided by zero.

3. NameError: It occurs when a name is not found. It may be local or global.

4. IndentationError: If incorrect indentation is given.

5. IOError: It occurs when Input Output operation fails.

6. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

4.21.without Handling Exceptions:


1. ZeroDivisionError: Occurs when a number is divided by zero
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value0
>>> c=a/b
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
c=a/b
ZeroDivisionError: division by zero
2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘

3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
4. SyntaxError: Python interpreter syntax error
>>> for
File "<string>", line 1
for
^
SyntaxError: invalid syntax
 SyntaxError exceptions are the only ones that do not occur at run-time.
 They indicate an improperly constructed piece of Python code which cannot execute
until corrected.
 These errors are generated at compile-time, when the interpreter loads and attempts to
convert your script to Python bytecode

5. IndexError: request for an out-of-range index for sequence
>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
 IndexError is raised when attempting to access an index that is outside the valid range
of a sequence.
6. KeyError: request for a non-existent dictionary key
>>> aDict = {'host': 'earth', 'port': 80}
>>> print aDict['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
 Mapping types such as dictionaries depend on keys to access data values. Such values
are not retrieved if an incorrect/nonexistent key is requested.
7.IOError: input/output error
>>> f = open("blah")
Traceback (innermost last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'blah‘
 Attempting to open a nonexistent disk file is one example of an operating system
input/output (I/O) error. Any type of I/O error raises an IOError exception

4.22. Except Statement with no Exception:


Exception handling in python:
1. ZeroDivisionError: Occurs when a number is divided by zero.
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value0
>>> c=a/b
Output:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
c=a/b
ZeroDivisionError: division by zero
 If the python program contains suspicious code that may throw the exception, we must
place that code in the try block.
 The try block must be followed with the except statement which contains a block of
code that will be executed if there is some exception in the try block.
 When an error occurs with in try block .python looks for matching except block to
handle it ,if there is an error ,execution jumps there.
Ex:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/b
print("the result is",c)
except:
print("error occured“)
C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value0
error occured
C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value2
The result is 2

2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Output:
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘
With except statement:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/'b'
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>typeerror.py
enter a value3
enter b value 4
error occured

3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Output:
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
With except statement:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/d
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>nameerror.py
enter a value2
enter b value3
error occured

4.23 Declaring Multiple Exceptions:


1. except Statement with Multiple Exceptions:
 The python allows us to declare the multiple exceptions with the except clause. Declaring
multiple exceptions is useful in the cases where a try block throws multiple exceptions.
Ex: # handle zero divison error
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:0
please enter non-zero for denimoniator
# handle type error
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/'b';
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:2
please use proper types only
# handle Name error
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/d;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:6
please use defined names only

some of the exception errors


except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occurred.')
Declaring multiple exceptions (or )except Statement with Multiple Exceptions
 The python allows us to declare the multiple exceptions with the except clause.
 Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.

Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code
Handling All Exceptions:
If you really want to handle all errors, you can still do that too, but use BaseException
- BaseException
|- KeyboardInterrupt
|- SystemExit
|- Exception
|- (all other current built-in exceptions)
Python exception hierarchy or standard exceptions:

Ex:
try:
except BaseException, e:
# handle all errors
or
try:
except Exception, e:
# handle real errors
4.24 else block:
 We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the try
block.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Output:
C:\Users\ajee\Desktop\py>else.py
Enter a:4
Enter b:0
can't divide by zero
C:\Users\ajee\Desktop\py>else.py
Enter a:4
Enter b:2
a/b = 2
Hi I am else block
4.25 Finally block :
The finally block will be executed regardless if the try block raises an error or not.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except :
print("please enter non-zero for denimoniator")
else:
print("Hi I am else block")
finally:
print("Thank you")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:3
a/b = 1
Hi I am else block
Thank you
Output:
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:0
please enter non-zero for denimoniator
Thank you
Assert statement in python:
 Python has built-in assert statement to use assertion condition in the program.
 assert statement has a condition or expression which is supposed to be always true. If
the condition is false assert halts the program and gives an assertionError.
 It is used for debugging
Syntax:
assert <condition>,<error message>
Here error message is optional
Ex:
x = "hello”
assert x == "hello“
print(x)
#if condition returns False, AssertionError is raised
assert x == "goodbye", "x should be 'hello‘“
o/p:
hello
Traceback (most recent call last):
File "main.py", line 17, in <module>
assert x == "goodbye", "x should be 'hello‘”
AssertionError: x should be 'hello'

4.26 Custom Exception or User defined exception:


 User can also define exceptions to indicate something is going wrong in your
program ,those are called customized exception or programmatic exception.
 The raise keyword is used to raise an exception.
 You can define what kind of error to raise, and the text to print to the user.

ex: Raise an error and stop the program if x is lower than 0:


x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero“)
o/p:
Traceback (most recent call last):
File "demo_ref_keyword_raise.py", line 4, in <module>
raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero
Ex: Raise a TypeError if x is not an integer:
x = "hello”
if not type(x) is int:
raise TypeError("Only integers are allowed")
Exceptions and the sys Module:
 An alternative way of obtaining exception information is by accessing the exc_info()
function in the sys module. This function provides a 3-tuple of information.
1. exc_type: exception class object
2. exc_value: (this) exception class instance object
3. exc_traceback: traceback object
Ex:
>>> try:
float('abc123')
except:
import sys
exc_tuple = sys.exc_info()
>>> print(exc_tuple)
( <class exceptions.ValueError at f9838>, <exceptions.ValueError instance at 122fa8>,
<traceback object at 10de18> )
UNIT V

5.1 Python Packages:


A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required in a
program, that package can be imported and its modules can be put to use.

Any Python file, whose name is the module’s name property without the .py extension, is a
module.

A package is a directory of Python modules that contains an additional __init__.py file,


which distinguishes a package from a directory that is supposed to contain multiple Python
scripts. Packages can be nested to multiple depths if each corresponding directory contains
its own __init__.py file.

5.2 Python Libraries:


Python Libraries are a set of useful functions that eliminate the need for writing codes from
scratch.

There are over 137,000 python libraries present today.

Python libraries play a vital role in developing machine learning, data science, data
visualization, image and data manipulation applications and more.

A library is a collection of pre-combined codes that can be used iteratively to reduce the
time required to code. They are particularly useful for accessing the pre-written frequently
used codes, instead of writing them from scratch every single time. Similar to the physical
libraries, these are a collection of reusable resources, which means every library has a root
source. This is the foundation behind the numerous open-source libraries available in
Python.

5.3 Python Modules:


A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python
code file saved with the extension (.py) is treated as the module. We may have a runnable
code inside the python module.

Modules in Python provides us the flexibility to organize the code in a logical way.

To use the functionality of one module into another, we must have to import the specific
module.
Example
In this example, we will create a module named as file.py which contains a function func
that contains a code to print some message on the console.

Let's create the module named as file.py.

#displayMsg prints a message to the name being passed.


def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg()
defined in the module named file.

5.4 Collection Module:


The Python collection module is defined as a container that is used to store collections of
data, for example - list, dict, set, and tuple, etc. It was introduced to improve the
functionalities of the built-in collection containers.

Python collection module was first introduced in its 2.4 release.


There are different types of collection modules which are as follows:
namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position
in the tuple. It was used to eliminate the problem of remembering the index of each field of
a tuple object in ordinary tuples.

Examples
pranshu = ('James', 24, 'M')
print(pranshu)

Output:
('James', 24, 'M')
OrderedDict()

The Python OrderedDict() is similar to a dictionary object where keys maintain the order of
insertion. If we try to insert key again, the previous value will be overwritten for that key.

Example
import collections
d1=collections.OrderedDict()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13

for k,v in d1.items():


print (k,v)

Output:
A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-
in dict class. It provides all methods provided by dictionary but takes the first argument as
a default data type.

Example
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])

Output:
0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.

5. 5 Math Module:
Python math module is defined as the most famous mathematical functions, which includes
trigonometric functions, representation functions, logarithmic functions, etc. Furthermore,
it also defines two mathematical constants, i.e., Pie and Euler number, etc.

Pie (n): It is a well-known mathematical constant and defined as the ratio of circumstance
to the diameter of a circle. Its value is 3.141592653589793.

Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.

There are different math modules which are given below:


math.log()
This method returns the natural logarithm of a given number. It is calculated to the base e.

Example
import math
number = 2e-7 # small value of of x
print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
log(fabs(x), base) is : -6.698970004336019
<
math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.

Example
import math
x=13 # small value of of x
print('log10(x) is :', math.log10(x))
Output:

log10(x) is : 1.1139433523068367
math.exp()
This method returns a floating-point number after raising e to the given number.

Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)
Output:

The given number (x) is : 0.05


e^x (using exp() function) is : 0.05127109637602412
math.pow(x,y)
This method returns the power of the x corresponding to the value of y. If value of x is
negative or y is not integer value than it raises a ValueError.

Example
import math
number = math.factorial(7)
print("The factorial of number:",number)
Output:
The factorial of number: 5040

5.6 OS Module:
Python OS module provides the facility to establish the interaction between the user and the
operating system. It offers many useful OS functions that are used to perform OS-based
tasks and get related information about operating system.

The OS comes under Python's standard utility modules. This module offers a portable way
of using operating system dependent functionality.
The Python OS module lets us work with the files and directories.

To work with the OS module, we need to import the OS module.


import os
There are some functions in the OS module which are given below:

os.name()
This function provides the name of the operating system module that it imports.

Currently, it registers 'posix', 'nt', 'os2', 'ce', 'java' and 'riscos'.

Example
import os
print(os.name)
Output:
nt
os.mkdir()

The os.mkdir() function is used to create new directory. Consider the following example.
import os
os.mkdir("d:\\newdir")
It will create the new directory to the path in the string argument of the function in the D
drive named folder newdir.

os.getcwd()
It returns the current working directory(CWD) of the file.

Example
import os
print(os.getcwd())
Output:

C:\Users\Python\Desktop\ModuleOS
os.chdir()
The os module provides the chdir() function to change the current working directory.

import os
os.chdir("d:\\")
Output:

d:\\
os.rmdir()
The rmdir() function removes the specified directory with an absolute or related path. First,
we have to change the current working directory and remove the folder.

Example
import os
# It will throw a Permission error; that's why we have to change the current working
directory.
os.rmdir("d:\\newdir")
os.chdir("..")
os.rmdir("newdir")

5.7 Random Module:


The Python random module functions depend on a pseudo-random number generator
function random(), which generates the float number between 0.0 and 1.0.

There are different types of functions used in a random module which is given below:

random.random()
This function generates a random float number between 0.0 and 1.0.

random.randint()
This function returns a random integer between the specified integers.

random.choice()
This function returns a randomly selected element from a non-empty sequence.

Example
# importing "random" module.
import random
# We are using the choice() function to generate a random number from
# the given list of numbers.
print ("The random number from list is : ",end="")
print (random.choice([50, 41, 84, 40, 31]))

Output:
The random number from list is : 84
random.shuffle()
This function randomly reorders the elements in the list.

random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its argument. It
accepts three arguments, beginning number, last number, and step, which is used to skip a
number in the range. Consider the following example.

# We are using randrange() function to generate in range from 100


# to 500. The last parameter 10 is step size to skip
# ten numbers when selecting.
import random
print ("A random number from range is : ",end="")
print (random.randrange(100, 500, 10))

Output:
A random number from range is : 290
random.seed()
This function is used to apply on the particular random number with the seed argument. It
returns the mapper value. Consider the following example.

5.8 Statistics Module:


Python statistics module provides the functions to mathematical statistics of numeric data.
There are some popular statistical functions defined in this module.

mean() function
The mean() function is used to calculate the arithmetic mean of the numbers in the list.

Example
import statistics
# list of positive integer numbers
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
# Printing the mean
print("Mean is :", x)
Output:
Mean is : 4.857142857142857
median() function

The median() function is used to return the middle value of the numeric data in the list.

Example
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("Median of data-set is : % s "
% (statistics.median(datasets)))
Output:
Median of data-set is : 4.5
mode() function
The mode() function returns the most common data that occurs in the list.
5.9 Sys Module:
The python sys module provides functions and variables which are used to manipulate
different parts of the Python Runtime Environment. It lets us access system-specific
parameters and functions.

import sys
First, we have to import the sys module in our program before running any functions.

sys.modules
This function provides the name of the existing python modules which have been imported.

sys.argv
This function returns a list of command line arguments passed to a Python script. The name
of the script is always the item at index 0, and the rest of the arguments are stored at
subsequent indices.

sys.base_exec_prefix
This function provides an efficient way to the same value as exec_prefix. If not running a
virtual environment, the value will remain the same.

sys.base_prefix
It is set up during Python startup, before site.py is run, to the same value as prefix.

5.10 Date & Time Module:


Python provides the datetime module work with real dates and times. In real-world
applications, we need to work with the date and time. Python enables us to schedule our
Python script to run at a particular timing.

In Python, the date is not a data type, but we can work with the date objects by importing
the module named with datetime, time, and calendar.

The datetime classes are classified in the six main classes.


date - It is a naive ideal date. It consists of the year, month, and day as attributes.
time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour,
minute, second, microsecond, and tzinfo as attributes.
datetime - It is a grouping of date and time, along with the attributes year, month, day, hour,
minute, second, microsecond, and tzinfo.
timedelta - It represents the difference between two dates, time or datetime instances to
microsecond resolution.
tzinfo - It provides time zone information objects.
timezone - It is included in the new version of Python. It is the class that implements the
tzinfo abstract base class.

5.11 Loading the Module in our Python Code:


We need to load the module in our python code to use its functionality. Python provides two
types of statements as defined below.

The import statement


The from-import statement

5.12 import Statement:


The import statement is used to import all the functionality of one module into another.
Here, we must notice that we can use the functionality of any python source file by
importing that file as the module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded
once regardless of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.


import module1,module2,........ module n

Hence, if we need to call the function displayMsg() defined in the file file.py, we have to
import that file as a module into our module as shown in the example below.

Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)

Output:
Enter the name?John
Hi John

5.13 from-import Statement:


Instead of importing the whole module into the namespace, python provides the flexibility
to import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.

from < module-name> import <name 1>, <name 2>..,<name n>


Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.

calculation.py:
#place the code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while
accessing summation()

Output:
Enter the first number10
Enter the second number20
Sum = 30

The from...import statement is always better to use if we know the attributes to be imported
from the module in advance. It doesn't let our code to be heavier. We can also import all the
attributes from a module by using *.

Consider the following syntax.

from <module> import *

5.14 Renaming a Module:


Python provides us the flexibility to import some module with a specific name so that we
can use this name to use that module in our python source file.

The syntax to rename a module is given below.


import <module-name> as <specific-name>

Example
#the module calculation of previous example is imported in this example as cal.
import calculation as cal;
a = int(input("Enter a?"));
b = int(input("Enter b?"));
print("Sum = ",cal.summation(a,b))

Output:
Enter a?10
Enter b?20
Sum = 30
5.15 Regular Expressions:
The regular expressions can be defined as the sequence of characters which are used to
search for a pattern in a string. The module re provides the support to use regex in the python
program. The re module throws an exception if there is some error while using the regular
expression.

The re module must be imported to use the regex functionalities in python.


import re

Regex Functions
The following regex functions are used in the python.

5.16 Command Line Arguments:


The Python supports the programs that can be run on the command line, complete with
command line arguments. It is the input parameter that needs to be passed to the script when
executing them.

It means to interact with a command-line interface for the scripts.

It provides a getopt module, in which command line arguments and options can be parsed.

5.17 Object Oriented Programming (OOPs):


Like other general-purpose programming languages, Python is also an object-oriented
language since its beginning. It allows us to develop applications using an Object-Oriented
approach. In Python, we can easily create and use classes and objects.

An object-oriented paradigm is to design the program using classes and objects. The object
is related to real-word entities such as book, house, pencil, etc. The oops concept focuses
on writing the reusable code. It is a widespread technique to solve the problem by creating
objects.

Major principles of object-oriented programming system are given below.


Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation

5.18 Object-oriented vs Procedure-oriented Programming languages:

5.19 Object:
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.

When we define a class, it needs to create an object to allocate the memory. Consider the
following example.

Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)

c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1 object
will allocate memory for these values.

5.20 Class:
The class can be defined as a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have an employee class, then it should contain
an attribute and method, i.e. an email id, name, age, salary, etc.

Syntax
class ClassName:
<statement-1>
.
.
<statement-N>

5.21 Method:
The method is a function that is associated with an object. In Python, a method is not unique
to class instances. Any object type can have methods.

5.22 Inheritance:
Inheritance is the most important aspect of object-oriented programming, which simulates
the real-world concept of inheritance. It specifies that the child object acquires all the
properties and behaviors of the parent object.

By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.

It provides the re-usability of the code.

5.23 Polymorphism:
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in different
ways. For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on the animal.
So, the abstract "animal" concept does not actually "speak", but specific animals (like dogs
and cats) have a concrete implementation of the action "speak".

5.24 Data Abstraction:


Data abstraction and encapsulation both are often used as synonyms. Both are nearly
synonyms because data abstraction is achieved through encapsulation.

Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.

5.25 Encapsulation:
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.

5.26 Python Class and Objects:


We have already discussed in previous tutorial, a class is a virtual entity and can be seen as
a blueprint of an object. The class came into existence when it instantiated. Let's understand
it by an example.

Suppose a class is a prototype of a building. A building contains all the details about the
floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects
of this class.

On the other hand, the object is the instance of a class. The process of creating an object can
be called instantiation.

5.27 Creating Classes in Python:


In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.

Syntax
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which
can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as
Employee id, and name.

The class also contains a function display(), which is used to display the information of the
Employee.

Example
class Employee:
id = 10
name = "Devansh"
def display (self):
print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It is
always the first argument in the function definition. However, using self is optional in the
function call.

The self-parameter
The self-parameter refers to the current instance of the class and accesses the class variables.
We can use anything instead of self, but it must be the first parameter of any function which
belongs to the class.

5.28 Creating an Instance of the Class:


A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.


<object-name> = <class-name>(<arguments>)

The following example creates the instance of the class Employee defined in the above
example.

Example
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%(self.id,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()

Output:
ID: 10
Name: John

In the above code, we have created the Employee class which has two attributes named id
and name and assigned value to them. We can observe we have passed the self as parameter
in display function. It is used to refer to the same class attribute.

We have created a new instance object named emp. By using it, we can access the attributes
of the class.

5.29 Python Constructor:


A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.

Constructors can be of two types.


Parameterized Constructor
Non-parameterized Constructor

Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.

5.30 Creating the Constructor in Python:


In Python, the method the __init__() simulates the constructor of the class. This method is
called when the class is instantiated. It accepts the self-keyword as a first argument which
allows accessing the attributes or method of the class.

We can pass any number of arguments at the time of creating the class object, depending
upon the __init__() definition. It is mostly used to initialize the class attributes. Every class
must have a constructor, even if it simply relies on the default constructor.

Consider the following example to initialize the Employee class attributes.

Example
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

emp1.display()

# accessing display() method to print employee 2 information


emp2.display()

Output:
ID: 101
Name: John
ID: 102
Name: David

5.31 Parameterized Constructor:


The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
self.name = name
def show(self):
print("Hello",self.name)
student = Student("John")
student.show()

Output:
This is parametrized constructor
Hello John

5.32 Non-Parameterized Constructor:


The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.

Example
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
student.show("John")

5.33 In- built Class Functions:


The built-in functions defined in the class are described in the following table.
5.34 In-built Class Attributes:
Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.
The built-in class attributes are given in the below table.

5.35 Python Inheritance:


Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new class
instead of creating it from scratch.

In inheritance, the child class acquires the properties and can access all the data members
and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.

In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

Output:
dog barking
Animal Speaking

5.36 Python Multi-Level Inheritance:


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is no
limit on the number of levels up to which, the multi-level inheritance is archived in python.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>

Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()

Output:
dog barking
Animal Speaking
Eating bread...

5.37 Python Multiple Inheritance:


Python provides us the flexibility to inherit multiple base classes in the child class.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... BaseN):


<class-suite>

Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))

Output:
30
200
0.5

5.38 Method Overriding:


We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class method is
needed in the child class.

Consider the following example to perform method overriding in python.

Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()

Output:
Barking
Real Life Example of method overriding
class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;

class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",b1.getroi());
print("SBI Rate of interest:",b2.getroi());
print("ICICI Rate of interest:",b3.getroi());

Output:
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8

5.39 Data Abstraction in Python:


Abstraction is an important aspect of object-oriented programming. In python, we can also
perform data hiding by adding the double underscore (___) as a prefix to the attribute which
is to be hidden. After this, the attribute will not be visible outside of the class through the
object.

Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
emp.display()

Output:
The number of employees 2
AttributeError: 'Employee' object has no attribute '__count'

5.40 Graphical User Interface (GUI) Programming:


Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.

Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look this option in this chapter.

wxPython − This is an open-source Python interface for wxWindows http://wxpython.org.

JPython − JPython is a Python port for Java which gives Python scripts seamless access to
Java class libraries on the local machine http://www.jython.org

5.41 Python Tkinter:


Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-
oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −

Import the Tkinter module.

Create the GUI application main window.

Add one or more of the above-mentioned widgets to the GUI application.

Enter the main event loop to take action against each event triggered by the user.

Example
import Tkinter
top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()

5.42 Tkinter Geometry:


All Tkinter widgets have access to specific geometry management methods, which have the
purpose of organizing widgets throughout the parent widget area. Tkinter exposes the
following geometry manager classes: pack, grid, and place.
1. The pack() Method
2. The grid() Method
3. The place() Method

5.43 pack() Method:


This geometry manager organizes widgets in blocks before placing them in the parent
widget.

5.44 grid() Method:


This geometry manager organizes widgets in a table-like structure in the parent widget.

5.45 place() Method:


This geometry manager organizes widgets by placing them in a specific position in the
parent widget.

5.46 Tkinter Widgets:


There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications.

You might also like