67% found this document useful (3 votes)
7K views

Python (Nirali Publi)

ESP Microproject of Group 13 Pratik

Uploaded by

prachi parab
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
67% found this document useful (3 votes)
7K views

Python (Nirali Publi)

ESP Microproject of Group 13 Pratik

Uploaded by

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

THIRD YEAR DIPLOMA

ENGINEERING AND TECHNOLOGY


COMPUTER ENGINEERING GROUP
SEMESTER-VI

PROGRAMMING WITH
'PYTHON'

Scanned with CamScanner


Contents ...

1.0 Introduction
1.1 Features of Python
1.1.1 Running Python Scripts
1.1.2 Internal Working of Pyt
hon
Python Building Blocks
1.2.1 Character Set
1.2.2
1.2.3
1.24
1.2.5
1.26
1.2.7

Scanned with CamScanner


i

fc and while Loops


g ts
Control Statemen
25 ie Manipulation/LOOP
2.5.1 break Statement
t
25.2 continue Statemen
25.3 pass Statement
« Practice Questions

3. Data Structures in Python


3.0 Introduction
3.1 Lists
3.1.1 Creating a List
3.1.2 Accessing Values in List
3.1.3 Deleting Values in List
ts to a List)
3.1.4 Updating Lists (Change or Add Elemen
g)
3.1.5 Basic List Operations (indexing and Slicin
3.1.5.1 Indexing
3.15.2 List Slicing
3.1.6 Built-in Functions and Methods for List
3.2 Tuples
3.2.1 Creating Tuple
3.2.2 Accessing Values in Tuple
3.2.2 Deleting Tuples
3.2.4 Updating Tuple
3.2.5 Tuple Operations
3.2.6 Build-in Functions and Methods of Tuple
3.3 Sets
2.3.1 Accessing Values in Sets
3.3.2 Deleting Values in Set
3.3.3 Updating Set
3.3.4 Basic Set Operations
3.3.5 Built-in Functions and Methods for Set
34 Dictionaries
3.4.1 Creating Dictionary
34.2 Accessing Values in a Dictionary
34.3 Deleting Elements/items from Dictionary
3.4.4 Updating Dictionary
3.4.5 Basic Operations on Directory
34.6 Built-in Functions and Methods for Dictionary
* Practice Questions
as ot “

4.0 Introduction
41 Use of Python Built-In Functions
4.1.1 Type Data Conversion Functions
41,2 Built-in Mathematical Functions

Scanned with CamScanner


a

io

a
-

Scanned with CamScanner


Scanned with CamScanner
Chapter Outcomes...
=) Identify the given variables, keywords and constants in Python.
(=| Use indentation, comments in the given program.
(=| Install the given Python IDE and editor.
(=) Develop the python program to display the given text.

Learning Objectives...
=) To understand Basic Concepts in Python Programming
=| To learn Features and Environment for Python Programming
®) To know Python Programming Building Blocks like Keywords, Variables, Identifiers etc.
=) To learn Data Types in Python Programming

FRY wrropuction
Python is a high-level, interpreted, interactive and object-oriented programming language. Today,
python is the trendiest programming language programming.
There are several reasons for why Python programming language is the preferable choice of the
programmers/developers over other popular programming languages like C++, Java and so on.
Python is popular programming language because of it provides more reliability of code, clean
syntax of code, advanced language features, scalability of code, portability of code, support object
oriented programming, broad standard library, easy to learn and read, support GUI mode,
interactive, versatile and interpreted, interfaces to all major commercial databases, and so on.
History of Python Programming Language:
Python laid its foundation in the late 1980s. Python was developed by Guido Van Rossum at National
Research Institute for Mathematics and Computer Science in Netherlands in 1990.
Inspired by Monty Python's Flying Circus, a BBC comedy series, he named the language Python.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.
ABC programming language is said to be the predecessor of Python language which was capable of
Exception Handling and interfacing with Amoeba Operating System. Like Perl, Python source code is
now available under the GNU General Public License (GPL).
In February 1991, Guido Van Rossum published Python 0.9.0 (first release) to alt.sources. In addition
to exception handling, Python included classes, lists and strings.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce which
aligned it heavily in relation to functional programming.
[1.1]

Scanned with CamScanner


1.2 _Introduction
and Syr
mi ng with 'P: hon’ 5 ‘
= 7 : rn
oa
garbage collection sys ie ; a
2.0 added new features like list comprehensions,
e Python 2. ic j
Unicode. g, Python 3.0 (also called “Py3K") was released. It was d
° BP Decco 3, 200of the language. In Python 3.0 the print
: ra ns
statement has been 7
un
{ a |
ae,
i ai ion.used in both industry and academia because of its simple, concisea
funct

a
ort of libraries. F
esa is available for almost all operating systems such as Windows, Mac, Linux/Uni
s, ! ‘
can be downloading from http://www.python.org/download
f
Some common applications of Python Programming are listed below:
1, Google's App Engine web development framework ne PyLe as an application la
2. Maya, a powerful integrated 3D modeling and animation system, provides a Python
API. Th
my
Linux Weekly News, published by using a web application written in Python programn ’ it.
DNR Ww

Google makes extensive use of Python in its Web Search Systems.


The popular YouTube video sharing service is largely written in Python programming.
The NSA (National Security Agency) uses Python programming for cryptography
intelligence analysis. ‘i
iRobot uses Python programming to develop commercial and military robotic devices.
co N

The Raspberry Pi single-board computer promotes Python programming as its =


language. ja tm
9. Nextflix and Yelp have both documented the role of Python in their software infrastructu
10. Industrial Light and Magic, Pixar and others uses Python programming in the produc
animated movies. ; F ol
PEW FEATURES OF PYTHON tec a
i

Python's features include:


Easy to Learn and Use: : as
Python is easy to learn and use. It is developer-friendly and high level programn
Python has few keywords, simple structure, and a clearly defined syntax that r
understandable for beginners.
iis
Python language is more expressive means that it is more understandable and
programmers. a
In Python programming programs are easy to write and execute as it omits some
poorly understandable and confusing features of other programming language su
Java.
- Interpreted Language:
;
Python is an interpreted language i.e., interpreter executes the
code line by line ata ti
debugging easy and thus suitable for beginners. There are excel
lent, straightforw:
with pytho n code, is interactive interpreter.
In python, we need not to learn a build system, IDE,
special text editor, or anything else
python. All we need only a command prompt and the interact
ive editor. r a |
Python provides a Python Shell (also known as Python Interactive Shell) which is 1

Scanned with CamScanner


ee "|

Programming with 'Python' 13 Introduction and Syntax of Python Program


HB Commend Prompt - python

Fig. 1.1; Python Command Prompt


3. Interactive Mode;
Python programming language has support for interactive mode, which allows interactive testing
and debugging of code. Graphical User Interfaces (GUIs) can be developed using Python.
Python supports GUI applications that can be created and ported to many system calls, libraries and
windows systems, such as Windows MFC, Macintosh and the X Window
system of Unix.
There are many free and commercial editors available for Python. Following table lists
Python
editors:
Sr. No. Editor Icon/Logo _

=
L

ng IDLE IDLE is a popular Integrated Development Environ-


ment written in Python and it has been integrated with
the default language.
Mainly used by the beginner level developers who want
to practice on Python development.
PyCharm PyCharm is one of the widely used Python IDE which
was created by Jet Brains.
With PyCharm, the developers can write a neat and
maintainable code. It helps to be more productive and
gives smart assistance to the developers.
It takes care of the routine tasks by saving time and
thereby increasing profit accordingly.
Spyder It was mainly developed for scientists and engineers to
provide a powerful scientific environment for Python.
It offers an advanced level of edit, debug, and data
exploration feature.
It is very extensible and has a good plugin system and SPYDER
API.
PyDev PyDev is an outside plugin for Eclipse. It is basically an
IDE that is used for Python development.
It is linear in size. It mainly focuses on the refactoring
of python code, debugging in the graphical pattern,
analysis of code etc. It is a strong python inter-preter.
Jupyter The Jupyter Notebook is a browser-based graphical
Notebook interface to the IPython shell. (sam
Allows us to create and share documents that contain
jupyter
live code, equations, visualizations and narrative text.
ba 2
In this text book, IDLE is used for Python programming. IDLE (Integrated Development and Learning
Environment) is an Integrated Development Environment (IDE) for Python.
To start IDLE interactive shell, search for the IDLE icon in the start menu and double click on it and
we will get the following window (See Fig. 1.2).

Scanned with CamScanner


14
ming with ‘python’
Program one like in
nly we can execute co .—
IDLE shell not © ion ofof those files
—___——
, a cae
but create .py files and se¢ execution
3 Shel
3.7.on
[ip Pyth
File Edit Shell Debug :22:¢ | ,
Mar 25 2019, 22 er
python 3.7.3 (v3.7,35€ f4ecéedl2,
()" FOE MaRS
as es rcopyright", "credits" or "license LS
>>>

Fig. 1.2: Python Shell


ee i
Free and Open Source:
d under an Os! approved o
python programming language is develope
source code is also ae al
freely available at official web address. The
any one can use and
The Python software can be freely distributed and
programs
changes/modifications to it and use the pieces in new free
table: rps
platform Independence/Cross Platform Language/Por
sar ne |
python can run on a wide variety of hardware platforms and has the
python can run equally on different platforms such asWindows, Linux, U
we can say that Python is a portable language. *.i > 5

Fig. 1.3 shows execution of Python code by interpreter.


Powe quad i

Interpreter—
be

Source code

oat ee a 7
ly y

ut
Fig. 1.3: Execof io
Pyth ne
on Cod _ + .
source
code goes through Compiler which compiles : the oa PPA:
. ce
Pythoncodesour
byte
Byte cored a lower level, platform independent, efficient and intern
source code. As soon as source code g artes Heads HEL
Machine). © BFls COR MEE TEL Te ier oad
The PYM is the runtime engine of Python; it’s uiwayy pélidniaaeei
é ‘ane 0
component that truly runs

Object-Oriented Language:
A programming language that can mod
objects, and combines data and el

Scanned with CamScanner


_ —| : im a

Programming with ‘Python’ 1.5 Introduction and Syntax of Python Program


Extensible:
Python programming implies that other languages such as C/C++ can be used to compile the code
and thus it can be used further in the python code.
python has a large and broad library and provides rich set of module and functions for rapid
application development.
Python languages bulk library is portable and cross platform compatible with Unix, Windows etc.
Limitations of Python:
1. Python is an interpreter based language. Therefore, it is bit slower than compiler based
languages.
2. Python is a high level language like C/C++/Java, it also uses many layers to communicate with
the operating system and the computer hardware.
3. Graphics intensive applications such as games make the program to run slower.
4. Due to the flexibility of the data types, Python's memory consumption is also high.
Structure of a Python Program:
Fig. 1.4 shows a typical program structure of Python programming.
Python programming programs are structured as a sequence of statements. A Python statement is
smallest program unit.
Statements are the instructions that are written in a program to perform a specific task. A Python
statement is a complete instruction executed by the Python interpreter.
By default, the Python interpreter executes all statements sequentially, but we can change order of
execution using control statements.
+ niet ul #Python Program Structure. Calculate Area and Circumference
of circle using class. # Documentation section
import math # import statement
radius=5 # global declaration Section
class Circle(): # class section

Optional ee, eee tad


def getCircumference(self):
return radius*2*math.pi
def showradius(): # sub Program section
print("Radius =",radius)
showradius() # Playground Section

Essential Bat “ai =",c.getArea()) print("“Circumference


=",c.getCircumference())
Output:
Radius = 5
Area = 78.53981633974483
Circumference = 31.41592653589793

Fig. 1.4: Typical Program Structure of Python Programming with Example


Program structure of Python programming contains following sections:
1. Documentation Section includes the comments that specify the purpose of the program.
A comments that is a non-executable statement which is ignored by the compiler while program
execution. Python comments are written anywhere in the program.
2. Import Section is used includes different built in or user defined modules.
Global Declaration Section is used to define the global variables for the programs.
&

4. Class Section describes the information about the user defined classes in the Python program.
A class is a collection of data members and member functions called method, that operate on
data members.

a es
Scanned with CamScanner
1.6
Programming with ‘Python’
defined functions. The ha
5. Sense ram
that Section
need to beincludes
executed use
when the function is called form, anywhs ir include
-
and the 5
Section is the main section of Python program —e sectio
6. Pay Ground
ea function calling.
| Running Python Scripts et ‘
‘: “
. pel has two basic modes namely, normal and interactive. ‘hes {
+ The normal script mode is the mode where the scripted and finished .py files are a
interpreter. te i:
The interactive mode is a command line shell which gives immediate feedback —
while running previously fed statements in active memory. Mh
As new lines are fed into the interpreter, the fed program is evaluated both in part and in
Interactive Mode: M ik
Interactive mode is used for quickly and conveniently running single line or blocks
of code.
example using the python shell that comes with a basic python installation. ’
The “>>>” indicates that the shell is ready to accept interactive commands. For example, if v
to print the statement “Interactive Mode”, simply type the appropriate code and hit enter,

File Edit Shell Debug Options Window Help : cesta s bie p


Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.4900 32 bit (intel)) 3
en win32
Type "copyright", "credits" or "license()" for more information.
>>> print (‘Interactive Mode')
Interactive Mode

Script Mode:
In the standard Python shell we can go to “File”> “New File” (or just hit Ctrl + N) to pull u r
script to write the code. Then save the script with a “ .py” extension.
We can save it anywhere we want for now, though we may want to make a folder someon
the code as we test Python out. To run the script, either select “Run” > “Run Module” or p
We should see een like the following, (See ze 1.6 18) and 1.6ot).

File Edit Formst Run Options Window “Help


[print ("Script Mode')

Scanned with CamScanner


Prograruniing with Eyiaian 1.7 Introduction and Syntax of Python Program

File Edit Shell Oebug Options Window Help


Python 3.6.4 (v3.6.4:d4@eceb, Dec 19 2017, 06:04:45) (MSC v.1900 32 bat (I *
ntel)] on wing2
peg "copyright", “credits” or “license()" for more information.
“= RESTART: Ct\Users\acer\AppData\Local\Programs\Python\ Python36-32\test-p
¥ Te

Script Mode
>>> |

Ee ne a ee
ne ote iné Cob4
Fig. 1.6 (b)
Internal Working of Python
Python is an object oriented programming language like C++ and Java. Python is called an
interpreted language means Python programs are executed by the interpreter.
e Python uses code modules that are interchangeable instead of a single long list of instructions that
was standard for functional programming languages.
¢ The standard implementation of python Python code
is called “CPython”. It is the default and I
widely used implementation of the
Python.
* When a programmer tries to run a
Python code as_ instructions in an
interactive manner in a Python shell, User inputs
7 Pytho Virtual
then Python performs various a “Machine (vm) | ==
operations internally.
e All such internal operations can be ral
broken down into a series of steps as
shown in Fig. 1.7. ee

¢ The Python interpreter performs following tasks to execute a Python program:


1. The interpreter reads a Python expression or statement, also called the source code, and verifies
that it is well formed. In this step, as soon as the interpreter encounters such an error, it halts
translation with an error message.
2. Ifa Python expression is well formed, the interpreter then translates it to an equivalent form in a
low-level language called byte code. When the interpreter runs a script, it completely translates
it to byte code.
3. This byte code is next sent to another software component, called the Python Virtual Machine
also halts with an
(PVM), where it is executed. If another error occurs during this step, execution
error message.
T ON BU r Oc _ Sia aha bdeagr. ieee ’ oe! ba a

* In order to write any Python program, we must be aware of its , available Keywordemmd
constant s, identifie rs and so on. 4
data types also have some knowledge of variables,
of Python programming. Python
* Keywords, identifiers, variables etc., are the basic building blocks
uses the character sets as the building block to form the basic program elements such as variables, P
a }
keywords, constants, etc.
Fy ae 7
Scanned with CamScanner
FE character Set
FEI chs cter set is a set of alphabets, letters, symbols and some special characters that are vane.
e e valid,
mming language. 7
ae Soa di e following character sets. These characters are submitted to the Python int
e Pytho such as characters, identig, ‘ i
identified in various contexts,
they are interpreted or uniquely
names or constants.
a to Z.
1. Lowercase English Letters:
A to Xs
2. Uppercase English Letters:
"!", etc.
3. Punctuation and Symbols: "S$",
as well as a newline, carriage return, horis
4. Whitespace Characters: An actual space (""),
tab, vertical tab, and a few others.
that cannot be printed liters
5. Non-Printable Characters: Characters such as backspace, "\b",
the way that the letter A can be printed.
a special role in Python like grouping
6. Delimiter: Delimiters are symbols that perform
punctuation and assignment. Following symbols and symbol combination uses as a delimiter j;
python: ;
Ns Peed ob. elt gk es ae -= *= /= %= “= &= |= “= dda cee
* A program in Python contains a sequence of instructions. Python breaks each statement int
sequence of lexical components/elements which are identify by the interpreter, known as tokens, _
* A token is a smallest unit of the program. Python contains various types of tokens, such as keyword
variables, operators, literals, identifiers etc.
'wawas identifiers
* A Python identifier is a name given to a function, class, variable, module or other objects that isu 2
in Python program.
« Allidentifiers must obey the following rules:
1. An identifier can be a combination of uppercase letters, lowercase letters, underscores, an
digits (0-9). Examples include, Name, myClass, Emp_Salary, var_1, _Address
print_hello_world.
2. Wecan use underscores to separate multiple words in the identifier. For example, Emp_Salary.
3. An identifier starts with a letter which can be alphabet (either lowercase or uppercase)
underscore (_).
4. Identifiers can be of any length.
5. Identifiers cannot start with digit and must not contain any space or tabs. Example inclu
2variable, 10ID.
6. Wecannot use Python keywords as identifiers.
7. Special characters such as %, @, and $ are not allowed within identifiers. Example inclu
) $Money, @salary.
i
Python is a case-sensitive language and this behavior extends to identifiers. Thus,
identifi ‘
and age are two distinct identifiers in Python.
Example of valid identifiers includes: Circle_Area, EmpName, Student, Sum, Salary F
Example 1@, PhoneNo.
of invalid identifiers includes: ! count, 4mar
ks, XLoan.
;
FEE] Keywords
* Pythar
on keyw
e ords are reserved words with that have special meaning and functions. The key
a rds should a ith sPecific meanin 7
oe
g in the Python programs.
not be used as variable name, constant, function name, or

Scanned with CamScanner


Programming with "Python" 19 Introduction and Syntax of Python Program

¢ Following table lists keywords in Python programming:


and as | assert break class continue
def del else elif except exec
false finally for from global if
import in is lambda none not
or | pass print raise return true
try | while with yield

5ya7e Variables
A variable is like a container that stores values that we can access or change. It is a way of pointing to
a memory location used by a program. We can use variables to instruct the computer to save or
retrieve data to and from this memory location.
A variable is a name given to a location in the computer's memory location, where the value can be
stored that can be used in the program.
When we create a variable, some space in the memory is reserved for that variable to store a data
value in it. The size of the memory reserved by the variable depends on the type of data it is going to
hold.
The variable is so called because its value may vary during the time of execution, but at a given
instance only one value can be stored in it.
Variable Declaration:
A variable is an identifier, that holds a value. In programming, we say that we assign a value toa
variable. Technically speaking, a variable is a reference to a computer memory, where the value is
stored.
Basic rules to declare variables in python programming language:
41. Variables in Python can be created from alphanumeric characters and underscore(_) character.
2. Avariable cannot begin with a number.
3. The variables are case sensitive. Means Amar is differ the ‘AMAR’ are two separate variables.
4. Variable names should not be reserved word or keyword.
5. No special characters are used except underscore (_) in variable declaration.
6. Variables can be of unlimited length.
Python variables do not have to be explicitly declared to reserve memory space. The variable is
declared automatically when the variable is initialized, i.e, when we assign a value to the variable
first time it is declared with the data type of the value assigned to it.
This means we do not need to declare the variables. This is handled automatically according to the
type of value assigned to the variable. The equal sign (=) ie., the assignment operator is used to
assign values to variables.
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 literal value or any other variable value that is stored in the variable.
Syntax: variable=value
Example: For variable.
>>> a=16
>> @

18
>>>
Python language allows assigning a single value to several variables simultaneously.
Example: a=b=c=1
is created with
All above three variables are assigned to same memory ‘location, when integer object
value 1.

one, ee oS ces neal

Scanned with CamScanner


Scanned with CamScanner
ax
tFp
yn0!
1.11 Introduction and S
Programming with ‘Python’

2, Numeric Literals: form 0 to 9.


are imm uta ble . Num eri c lite r als comprise number or digits
Numeric literals erical types.
Numeric literal s can bel
ong to following four different num
«
float (floating point) x (complex)
comple
int (signed integers) long (long integers)
In the form of a+bj
h Integers of unlimited Real numbers with both
Numbers (can be bot integer and fractional where a forms the real
(+) and size followed by lower- part and b forms the
positive part.
(-) ) with no case or uppercase L. part of
negative imaginary
Example: 87032845L Example: 26.2
fractional part. complex number.
Example: 100 Example: 3.14j

3. Boolean Literals:
ely, True or False.
A Boolean literal can have any of the two values nam
Example: For Boolean literal.
>>> 5<=2
False
>>> 3«9
True
>>>
4. Special Literals: that
special c onstant in Python programming
e Python contains one special literal ie., None. It is
represent the absence of a value or null value.
d. It is also used for end of lists in Python.
None is used to specify to that field that is not create
Example: For special literal.
>>> val1=10
val2=None # N is in uppercase here
>>>
>>> vali
10
>>> val2
>>> print (val2)
None
>>>
5. Literal Collections:
are used in Python.
* Collections such as tuples, lists and dictionary
(i) List:
are mutable i.e., modifiable. The values stored in
o List contain items of different data types. Lists
kets ([]). We can store different
list are separated by commas(,) and enclosed within a square brac
type of data in a list.
ator({] and [:]). The plus sign (+) is the
Value stored in a list can be retrieved using the slice oper
operator.
list concatenation and asterisk(*) is the repetition
(ii) Tuple:
e python objects.
o Tuple is used to store the sequence of immutabl
by commas (,).
ted
o A tuple can be created by using () brackets and separa
(iii) Directory:
{ }.
pairs created using
© The directory in Python is a collection of key value
(:) and the elements/items are separated by
° The key and value are separated by a colon
commas (,).

Scanned with CamScanner


Programmi with ‘Python’ :
lite ral collections.
Example: For
st
# create li
[1) 2.32425 6,7]
>>> numbers=
mbers)
>»»> print(nu
es
# create tupl
’, ‘b’» °C’)
>>> List=(‘a
t1)
>>> print (lis
ionary
# create dict
me’: ‘vijay’, “Iname?
: ‘patil’ }
>>> List2={ ‘fna
>>> print (list2)
Output:
[1,2,3,4,5,6,7]
Des co)
(rae

’’
‘patil
“lna;me }
{‘fname’ : ‘vijay’,
. Value and Type of Literals: : si
and any kind of cm ,
; Programming languages contain data in terms of input and output
presented ini terms 0 f value. =
or characters. To know the exact type of any value, python pro
Value can be of numbers, strings
in-built method called type.
Syntax: type(value)
Example: For value and type literals.
>>> type(‘hello python’)
<class ‘str'>
>>> type(‘a’)
<class ‘str'>
>>> type(123)
<class ‘int'>
>>> type(11.22)
<class 'float'>

‘4-3 Indentation
* Most of the programming languages like C, C++, Java
use braces { } to define a block of code. Python
uses
| indentation.
A code block (body of a function, loop
etc.) starts with
indentation and ends with the first
un-indented line,
The amount of indentation is
up to us, but it must be
Consistent throughout that bloc Sa i tara
k.
Generally, four whitespa
ces are used for indentation
and is preferred Over
tabs, (See Fig. 1.8).

Scanned with CamScanner


Frograrninirig win rytnon 1.13 Introduction and Syntax of Python Program

Example 1: For indentation. Example 2: For indentation in python,


>>> for i in range (1,11): >>> for i in range(1,11):
print(i)
print(i)
Output: AiG diate.

1 break
; Output:
4 1
5 2
6 3
7 4
8 5
9
18

Commenting in Python
Comments are meant for computer programmers for better underst
anding a program. Python
interpreter ignores the comment in the program.
1. Single Line Comment (#):
« Single line comments are created simply by beginning a line with the hash (#)
character, and they
are automatically terminated by the end of line.
Example 1: For single line comment. Example 2: For single line comment.
# print is a statement print(‘Hello Python’) # print is a statement
print( ‘Hello Python?) |
* When the python interpreter sees #, it ignores all the text after # on the
same line.
2. Multiple Line Comments (’”):
In some situations, multiline documentation is required for a program. If
we have comments that
extend multiple lines, one way of doing it is to use hash (#) in the beginni
ng of each line. Another
way of doing this is to use quotation marks, either or """,
* Similarly, when it sees the triple quotation marks "" it scans for the next
" and ignores any text in
between the triple quotation marks.
Example: For multiline comment.
'"'This is first python program
Print is a statement'''

[REM PyTHoN ENVIRONMENT SETUP (INSTALLATION AND WORKING OF IDE)


* Python distribution is available for a wide variety of platforms such as Unix, Linux, Macintosh and
Windows. We need to download only the binary code applicable for the platform and
install Python.
* The most up-to-date and current source code, binaries, documentation, news, etc.
is available on the
official website of Python https://www.python.org/.
Installing Python in Windows:
Step1: Open any internet browser then type http:///www.python.org/downloads/ in address bar
and Enter. The Home page will appear, (See Fig. 1.9).
=o —~ =
© GO trent name i =: menemmes 2 oe

2 python

ae eee a —

Fig. 1.9: Home Page

Scanned with CamScanner


Scanned with CamScanner
Programm
ee ing s
with 'Python’
eae
—$____ 518 __itroduction and Syntax of Python Program
Step5 : After complete the installation
close the windows,
& Pytho
n B71 bit) Satu,

Setup was successful


Special thanks to Mark Hamne
nd, without whose years of
freely shared Windcoms erpert
ion, Python tor Wires wots
Stl be Python for 005.

New to Python? Start with the


{ Shit atonal and
documentation
7
See what's new in this relense,
ee
7 © Disable path length lienét
Changes your machine Comba attic Vo adres preap eens, wcheceg § phen
bypass the 260 character +5

python
MAI_DATOO lermtiatin

windows
Sow
Fig, 1.13
Starting Python in different Mod
es:
a. Starting Python (Command Line):
A Python script can be executed a.
t command line also. This can be done by invoking the
on the application, interpreter
In command line mode, we type the Python programm
ing program on the Python shell and the
interpreter prints the result . The steps are given below:
Step1: Press Start button, (See Fig. 1.14).

Recently added

@ Python 3,7 (32-bit)

B Python 3.7 Module Docs (32-bit)

ay UES Weer

Sr ae

iene atop)

Acrobat Reader D

alee ase ed

vite,

P |Type here to search

Fig. 1.14

Scanned with CamScanner


a

; ith ‘Python’
1.16 :
Introduction and Syntax of Python py ™“"S ?
Progr
witha‘Py __n__
mthomn i g— ‘ey
ee
| : r
| a iti ah oe
Step2 : Clickon
i All Programs
nd then click on Python 3.7 (32 bit) as shown in| Fig, 1.14, We wil]
the Python interactive p
leo
:

Fig. 1.15
Python command prompt contains an opening message >>> called command Prompt, The

: cursor at command prompt waits for to enter Python command. A complete c ommand/s
: called a statement. For example check first command to print message, in Fig. 1.16,

Fig. 1.16
Step 3 : To exit from the co
mmand line of Python, use
Ctrl+z or quit() followed by Enter.
2. Starting Python IDLE:

When we install Pyth


on 3, we also get IDL
E ( Integrated Development . es 2
color syntax-highlig Environment). IDLE includ
ht ing editor, a
debugge r, the Python Shell,
and a complete copy of 3s
online documentatio Python
n Set.
The steps are Bi
ven below:
Step1: Press St
art button and cl
ick on IDLE (Pyt
hon 3.7, 32-bit)
options.

Scanned with CamScanner


1,17 ogran
Introduction and Syntax of Pyth on Program
Programming with ‘Python’

ne ae

r Python 3,7 (2b)

| Le Ae hd

| Ae a
Lepand

Most used

YY) ce
i ] Google Chrome

ea] Ce

Acrobat Reader DC

oO Ce mel

CI
ha
See

We) OMT a

ry

© Type here to search

Fig. 1.17
Step 2 : Wewillsee the Python interactive prompt i.e. interactive shell.
(BD Python 3.7.1 shett - o x
File Edit Shell Debug Options Window Help
Python 3.7.1 (v2.7.1:260ec2c36a, Oct 20 2016, 14:05:16) [MSC v.2915 52 bat (Inte *|
1)1 on wins2
el “help”, “copyright”, "oredita” or "license()" for more information.
>>>

inten eseatsisernssentnnasisenenta j in ean

Fig. 1.18

Python interactive shell prompt contains opening message >>>, called shell prompt. A
cursor is waiting for the command. A complete command is called a statement. When we
write a command and press enter, the python interpreter will immediately display the
result.

Scanned with CamScanner


1.18 Introduction and Syntax of

Programming with ‘Python’ - Oo x

[iB Python 3.7.1 Shell


Debug Options Window Help pasc v.1915 32 bit (Inte *%
File 20 2018, 14:05:26)
nn Oct
3-7-1 {v3.7-1:260ecze36e,
Python for more information.
oF "license ()"
ig "help", P
Type ne’,
“copyrigon’) "credita”
>>> print ("Helle Pyth
Hello Python
>>>

Fig. 1.19

Executing Python Programs Scripts:


the New File or press Ctrl+N.
e In Python IDLEs shell window, click on File, and select
— Oo x

Window Help
20 2018, 14:05:16) (MSC v.1915 32 bit (Inte
c3éa, Oct

"credits" or "license()" for more information.

Scanned with CamScanner


Scanned with CamScanner
: = ciel
Programming with Python
on Python shell.
After clicking Run Module, we will get the output of program
[3 Python 3.7.1 Shelt - OQ xX
File Edit Shell Debug Options Window Help : wil ell
Python 3.7.1 (v3.7.11260ec2c36a, Oct 20 2018, 14705116) [MSC v.1915 32 bit (Inte A
1)] on wins2
Type "help", "copyright", “credits” or "license()" for more information.

32/test.py =
= RESTART: C1/Users/vijay/AppData/Local/Programs/Python/Python37-
Hello Python
This is First Script
>>> |

_Um7 Cob4
Fig. 1.25
[ERY RUNNING SIMPLE PYTHON SCRIPTS TO DISPLAY ‘WELCOME’ MESSAGE"
e There are two modes for executing Python program namely Interactive mode Programming ang
Script mode programming.
¢ Ininteractive mode programming, interpreter is invoked and the programmer can code statemen
directly to the interpreter without passing a script file as a parameter.
¢ In script mode programming, the complete script is written in an editor such as Notepad j
Windows and then interpreter is invoked with a script parameter. It begins execution of the crit
and continues until the script is finished.
1. Interactive Mode Programming:
* Click on All Programs and then click on Python 3.7 (32-bit). We will see the Python interactive prom
in Python command line.
* This method invokes the interpreter without passing a script file and brings up the followin
prompt, (See Fig, 1.26).
BF Python 3.7 (64-bit) - Oo x|

ript is finished. When the


scri Pt is finished, the interpreter is
* Let us write a simple Py no longer active.
tho n program in a script. Python files have extensi
source code ina test.py on .py. Type the follow
file:
print"Welcome,
Python!"

Scanned with CamScanner


Programming with ‘Python’ 1.21 Introduction and Syntax of Python Program

e We assume that we have Python interpreter set in PATH variable. Now, try to run this program as
follows:
$ python test.py
Output:
Welcome, Python!
e OnLinux OS to execute a Python script modified test.py file:
#!/usr/bin/python
print"Hello, Python!"
¢ We assume that we have Python interpreter available in /usr/bin directory. Now, try to run this
program as follows:
$ chmod +x test.py # This is to make file executable
$./test.py
Hello, Python!

pe PYTHON DATA TYPES


¢ The type of data value that can be stored in an identifier/variable is known as its data type.
¢ The data type determines how much memory is allocated to store data and what operations can be
performed on it.
¢ The data stored in memory can be of many types and are used to define the operations possible on
them and the storage method for each of them.
¢ Python handles several data types to facilitate the needs of programmers and application developers
for workable data.
Declaration and Use of Data Types:
e One of the main differences between Python and strongly-typed languages like C, C++ or Java is the
way it deals with types. In strongly-typed languages every variable must have a unique data type.
e For example, if a variable is of type integer, solely integers can be saved in the variable. In Java or C,
every variable has to be declared before it can be used. Declaring a variable means binding it to a
data type.
e Declaration of variables is not required in Python. If there is need of a variable, we think of a name
and start using it as a variable.
¢ Inthe following line of code, we assign the value 42 to a variable:
i = 42
¢ The equal "=" sign in the assignment shouldn't be seen as "is equal to". It should be “read” or
interpreted as "is set to", meaning in our example "the variable i is set to 42". Now we will increase
the value of this variable by 1:
»>> ieir+l
>>> print i
43
>>>
* Python has various standard data types that are used to define the operations possible on them and
the storage method for each of them. Data types in Python programming includes:
1. Numbers: Represents numeric data to perform mathematical operations.
String: Represents text characters, special symbols or alphanumeric data.
= SN

List: Represents sequential data that the programmer wishes to sort, merge etc.
oy

Tuple: Represents sequential data with a little difference from list.


Dictionary: Represents a collection of data that associate a unique key with each value.
Boolean: Represents truth values (true or false).

Scanned with CamScanner


Introduction and Syntax of Python Program
1,22
hon
mthmi‘Pnytg
Prograwi
Data Type a value to
EE Numbers eric val ues, Number objects are
created when we assign
da ta types store num
Number ry. They
under Python numbers catego
;
them. com ple x nu mb er s fall s
er s and
ng point num on.
Integers, floati and complex in Pyth
oat
| are defined as int, fl
any decimal
Integers: ge r nu mb er . An inte ger number is a number without
presents an inte
‘An int data type re
or fractional point. r value 57.
ca lle d the int typ e var iable and stores intege
here ais
For example, a= 57, ~ 2147483648 to 2147
483647.
s in the range
These represent number
Floating Point Numbers: The floati ng point number is
a number that
flo ati ng poi nt nu mb er .
s t he . For example,
The float data type represent mples of float ing point numbers, O35; -3,445, 330.44
contains a decimal point. Exa
= 2.345.
t of
mplex Numbers:
n in the for m of a+b j. Her e, a represents the real par
ber that is writte
Acomplex number i s a num .
imaginary part of the number
he number and b represents the val ue of -1. The part a and b may contai
n the
ents the squ are roo t
the suffixJ or j after b repres s.
s or floa ts. For exa mpl e, 3+5j , 0.2+10.5j are complex number
ger
plex number
or example, in C=-1-5.5j, the com
variable C.
s -1-5.5j and is assigned to the he Z ’
erp ret er take s the data
lence, the Python int Fig, 1.27: Types of Numbers Data Typ
e
vari able C asa com ple x type .
pe of the
the
func tion to kn ow whi ch clas s a variable or a value belongs to and
can use the type()
ct belongs to a particular class.
stance() function to check if an obje
tegers (int Data Type):
a whol e num ber that can be posi tive (+) or nega tive (-). Integers can be of any length, it
integer is
aly limited by the memory available.
gers.
ample: For number data types are inte
(>>> a=10
>> a

>>> b=-10
>>> b
m4

| e the type of a variable type() function is used.


type(a)
<class ‘int’ >
ython 3, there is no limit to how long an int
computer’s memory space allows.” leper valteica bel COR geen
programming one can write integers in Hexadeci
Bina!
thon adecimal
16). Octal irene
.
Reesrmats myeesing one of the following prefixes to the ett
> gaat ‘
WW
ei , x F ns | i
ba age:

‘Ob’ or ‘OB’ ;

‘Oo’ or ‘00’ Octal


4 2.

‘Ox’ or ‘OX’ tie :


_3. decimal 16

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
1,26 Introduction and Syntax of Python Program

String Built-in Methods:


* String objects also have several useful methods to report various characteristics of the string, such
as whether it consists of digits or alphabetic characters or is all uppercase or lowercase.
Sr.No, | String Operation Explanation Example
1 4. Adds two strings together. X = “"hello”+"world”
2 |: - Replicatesa string. X=" "420
2 | upper oe a string to uppercase.
Converts x, upper()
lower Pr Converts a string to lowercase, x. lower()
title ; Capitalizes the first letter of each | x.title()
word in a string.
find, index Searches for the target in a string. x.find(y) x.index(y)
rfind, rindex Searches for the target in a string, | x.rfind(y) x.rindex(y)
from the end of the string.
Startswith, Checks the beginning or end of a | xstartswith(y) x.endswith(y)
endswith string for a match.
replace Replaces the target with a new | x.replace(y,z)
string.
strip, rstrip, lstrip | Removes whitespace or other | x.strip()
characters from the ends of a
string.
- encode Converts a Unicode string to a bytes | x. encode("utf_8”)
=; object.
EY List Data Type
List is an ordered sequence of items. It is one of the most
used datatype in Python and is very flexible.
dst can contain heterogeneous values such as integ
ers, floats, strings, tuples, lists and dictionaries
jut they are commonly used to store collections of homo
geneous objects.
The list data type in Python programming is just
like an array that can store a group of elements
€ can refer to these elements using a single name. and
eclarin Bs list is pretty straight forward. Items sep
arated by commas (,) are enclosed with
in
: For list.
first=(10, 20, 30] # homogenous values in list
Second=["One", "Two", "Three" ]
# homogenous values in list
first
®, 20, 30]
7,

"Two", Three’ ]
'd=[10, "one", 20, "two" ] # heterogeneous values in list

le", 20, ‘two']


t + second
# prints the concatenated lists
a '
» ‘Two’, ‘Three’ ]

Scanned with CamScanner


Scanned with CamScanner
Py
Introduction and Syntax of
a 8
gramming with ‘Python’
di cti ona ry dat a typ e is used. The dictionary da;
of data, the
When we have the large amount ate modify/update any value in the dictionar
y,
ch mea ns we can upd
mutable in nature whi
ace s { } and sep ara ted by : the comma ()). A gg)/
losed in curly br
Items in dictionaries are enc accessed using square braces ({}
ue, Values can be assigned and
used to separate key from val
Example: For dictionary data type.
>>> dicie{1: "First", "Second" :2}
>>> dicl
{1: ‘First’, ‘Second’: 2}
>>> type(dicl)
<class ‘dict'>
>>> dici[3]e"Third"
>>> dicl
‘First’, ‘Second’: 2, 3: 'Third'}
{1:
>>> dicl.keys()
dict_keys([1, ‘Second', 3])

>>> dici.values()
dict_values([‘First’, 2, ‘Third’ ])

IN PYTHON PROGRAMMING _ 7
a >>>

FM input AND OUTPUT In python, the input() function is


the program.
Input means the data entered by the user of t on older version.
pt an inpu t fro m a user . The raw _input () function available for Inpu
acce
# without any argument
Syntax: variable_name=input()
# with argument
variable_name=input( ‘String’ )

Example: For input in Python.


>>> input()
Hello python
‘Hello python
>>> x= input ("Enter data:")

Enter data: 11.22

>>> print(x)
41.22
In Python programmi g tl
Output means the data comes from computer after processing. aa
function display the input value on screen. 1H
able)
Syntax: print(expression/constant/vari
Example: For output in python.
>>> print ("Hello")
Hello
>>> a="Hello"
>>> b="Python"

Scanned with CamScanner


_

Programming with ‘Python’ 1.29 Introduction and Syntax of Python Program

Additional Programs:
1, Program to find the square root of a number.
xeint(input("Enter an integer number:"))
ans=x**@.5
print("Square root= ", ans)
Output:
Enter an integer number; 144
Square root= 12,0

2. Program to find the area of Rectangle.


l=float(input("Enter length of the rectangle: "))
b=float(input("Enter breadth of the rectangle: "))
area=1*b
print("Area of Rectange= ",area)
Output:
Enter length of the rectangle: 5
Enter breadth of the rectangle: 6
Area of Rectange= 30.0
3. Program to calculate area and perimeter of the square.
int(input("Enter side length of square: "))
area=side*side
perimeter = 4*side
print("Area of Square =", area)
print("Perimeter of Square =", perimeter)
Output:
Enter side length of square: 5
Area of Square = 25
Perimeter of Square = 20
4. Program to calculate surface volume and area of a cylinder.
pi=22/7
height = float(input('Height of cylinder: "))
radian = float(input('Radius of cylinder: '))
volume = pi * radian * radian * height
sur_area ((2*pi*radian) * height)
= + ((pi*radian**2)*2)
print("Volume is: ", volume)
print("Surface Area is: ", sur_area)
Output:
Height of cylinder: 4
Radius of cylinder: 6
Volume is: 452.57142857142856
Surface Area is: 377.1428571428571

5. Program to swap the value of two variables.


numi=input("Enter first value: ")
num2=input("Enter second value: "y
print("Numbers before swapping”)
print("numi= “,num1)
print("num2= “,num2)
temp=num1
numi=num2
Scanned with CamScanner
lav —
'
roge hon ming
withnPytm ;
nund=temp )
after swapping
print( “Numbers
* num)
print(“numl>
“ num)
print(“num2=

value; 10
enter first
value: 20
Enter second
re swapping
Numbers befo
numi= 10
Num2= 22
Numbers after swapping
20 a

r1ctice Questions
language?
What is Python programming
Give short history for Python.
program ming.
Enlist applications for Python
What are the features of Python?
Python programming.
List any four editors used for ent this sentence.
is interpreted and intractive' comm
Python programming language
in detail.
to run python scripts? Explain
hat is interpreter? How it works?
mming:
Explain the following features of Python progra
(i) Simple
ii) Platform independent
iii) Interactive
f) Object Oriented.
gramming and its importance.
3in about the need for learning Python pro
tically.
be the internal working of Python diagramma
.
ite in brief about characters set of Python
ite in brief about any five keywords in Python.
ite the steps to install Python and to run Python code.
at is the role of indentation in Python?
w to comment specific line(s) in Python program?
les?
at is variable? What are the rules and conventions for declaring a variab
it are the various data types available in Python programming.
nat are four built-in numeric data types in Python? Explain.
at is the difference between interactive mode and script mode of Python.
101 has developed as an open source project. Justify this statement.
ine the following terms:
Identifier

in dictionary data type in detail.

Scanned with CamScanner


A wz
List
Python Operators and
Control Flow Statements
a ee os <=

Chapter Outcomes...
Write simple Python program for the given arithmetic expressions.
=) =) @)

Use different types of operators for writing the arithmetic expressions.


Write a 'Python’ program using decision making structure for two-way branching to solve the given
problem.
Write a ‘Python’ program using decision making structure for multi-way branching to solve the given
problem.

Learning Objectives...
=) To understand Basic Operators in Python Programming
(=) To learn Control Flow and Conditional Statements in Python
{@) To study Looping in Python Programming
("| To understand Loop Manipulation Statements in Python

EQ) wrropuction
* Operators are the constructs which can manipulate the value of operands. Consider the expression
4+5-=9. Here, 4 and 5 are called operands and + is called operator. The Python language provides a
rich set of operators.
* The operator and operand when combined to perform a certain operation, it becomes an expression.
For example, in expression x + y, x and y are the variables (operands) and the plus (+) sign is the
operator that specifies the type of operation performed on the variables,
* Inany programming language, a program is written as a set of instructions. The instructions written
in programs are termed as statements.
* In Python, statements in a program are executed one after another in the order in which they are
written. This is called sequential execution of the program.
* But in some situations, the programmer may need to alter the normal flow of execution of a
program or to perform the same operations a number of times.
* For this purpose, Python provides a control structure which transfers the control from one part of
the program to some other part of the program.
* Acontrol structure is a statement that determines the control flow of the set of instructions i.e., a
program. Control statements are the set of statements that are responsible to change the flow of
execution of the program.
* There are different types of control statements supported by Python programming like
decision/conditional control, loop/iteration control and jump or loop control.
[2.1]

Scanned with CamScanner


Programming with ‘Python’ pe ens
p a
ac t
ti on e
. An ae
op er ator is a special symbol tha
h specifif ifiies a spsPecif
: ic 5. The operands can be jj
e An operator is a sym bol whici operatio
a specific
the interpreter to per form Goa
variables or expressions. \
on which operator acts. ' 4
An operand is a data item :
e ch can manipulate the
Operators are the symbol, whi rators require two
value of operands. Some ope
operands while oth ers req uire only one. Operands
Here, 5 and 2 are
Consider the expression 5 + 2 = 7.
called the operands and + is called the oper
ator. Fig. 2.1: Concept of Operator and Oper

InPython, the operators can be unary 0 per


ators or binary operator.
e

ra nd . Th es e op er at or s are basically used to py


* Unary operators are operators with only one o pe
sign to the operand. +, -, ~ are called unary operators.
Syntax: operator operand
Example:
>>> x=10
>>> +X

10
Be. ik

-10
>>> ~x

-11
¢ The invert (~) operator returns the bitwise inversion of long integer arguments. Inversion of xi
computed as ~ (x + 1).

Binary operators are operators with two operands that are mani ipulated to get the result. TITI
also used to compare numeric values and string values. P : ee
Syntax: operand1 operator operand2
e Binary operators are: **, *, /, %, +, -, <<, >>, & |, 4, <, >, , <=, , >=, ==,
‘ee?
!=, <> .

Example:
>>> x=10
>>> y=20
>>> x+y
>>> -X
30
>>> 243
5
Expression:
* An expression
.,. is
ee i but a combination
Te inati
of operators, variables, constants and rion é
* In other words, » an
an expression
ion isi a inati ;
evaluates to prodauce value. combination of literals, variables and operators tha
For examples: 1 + g

Scanned with CamScanner


Programming with ‘Python’
roa = yn 2.3 Python Operators and Control Flow Statements

* The arithmetic operators perform basic arithmetic operations like addition, subtraction,
multiplication and division. All arithmetic operators are binary operators because they can perform
operations on two operands.
e There are seven arithmetic operators provided in Python programming such as addition,
subtraction, multiplication, division, modulus, floor division, and exponential operators.
« Assume variable a holds the value 10 and variable b holds the value 20.
Sr. Operator Operator ;
No. Symbol Name Description Example

1. i: Addition Adds the value of the left and right operands. >>> a+b
30
2. = Subtraction Subtracts the value of the right operand from | >>> b-a
the value of the left operand. 10
Bs 2 Multiplication | Multiplies the value of the left and right | >>> a*b
operand. 200
4. / Division Divides the value of the left operand by the right | >>> b/a
operand. 2.0
Ds rh Exponent Performs exponential calculation. >>> a**2
100
6. % Modulus Returns the remainder after dividing the left | >>> a%b
operand with the right operand. 10
7. // Floor Division | Division of operands where the solution is a| >>> b//a
quotient left after removing decimalnumbers. | 2

EEE] Assignment operators (augmented assignment Operators)


values to variables. The
* Assignment operators are used in Python programming to assign
assignment operator is used to store the value on the right-hand side of the expression on the left-
hand side variable in the expression.
* For example, a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
* There are various compound operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent toa =a +5.
Following table shows assignment operators in Python programming:
Operator| ——SCDescription Example
Assigns values from right side operands to | c = a + b assigns value of a + b
left side operand. intoc
It adds right operand to the left operand and | c +=a is equivalent toc=c+a
assign the result to left operand.
It subtracts right operand from the left | c-=ais equivalent toc=c-a
| operand and assign the result to left operand.
—_|qt multiplies right operand with the left | c*=aisequivalenttoc=c*a
i nd and assign the result to left operand.
It | es left operand with the right operand | c /=ais equivalent toc=c/a
n the result to left operand.
sdulus using two operands and | c %=ais equivalent toc=c%a

al ) calculation on | c**=a is equivalent toc=c**a


on value to the left

on | c//=ais equivalent toc=c//a


calculation
to the left

Scanned with CamScanner


24 Python Operators
and Control Flow
Programming with ‘Python’

EEE] rela Comi


or t ison
paro aratlors
n Ope yg
binary operators and used to compare
* Comparison operators in Python programming are
Relational operators either return True or False accord
ing to the condition.
20.
e Assume variable a holds the value 10 and variable b holds the value
Sr. No. Operator Description | Exa
1. == If the values of two operands are equal, then | >>> (a==b) |
(Equality Operator) the condition becomes true. False 4

Ps l= If values of two operands are not equal, then | >>> (al=b) }


condition becomes true. True ;
(Not Equality Operator)

3. = If the value of left operand is greater than the | >>> (a>b)


(Greater Than Operator) | value of right operand, then condition becomes | False
true. a
4. < If the value of left operand is less than the | >>> (a<b)
(Less Than Operator) value of right operand, then condition becomes | True
true. ]
5. >= If the value of left operand is greater than or | >>> (a>=b)
(Greater Than Equal to | equal to the value of right operand, then | False
Operator) condition becomes true.
6. <= If the value of left operand is less than or equal | >>> (a<=b)
(Less Than Equal to | to the value of right operand, then condition | Trye .
Operator) becomes true.

ERW] Logical operators


¢ The logical operators in Python programming are used to combine one or more relatior
expressions that result in complex relational operations. The result of
the logical operator is
evaluated in the terms of True or False according to the result
of the logical expression. ‘
¢ Logical operators perform logical AND, logical OR and logical
NOT operations. These operations re
used to check two or more conditions. The resultant of this
operator is always a Boolean valu
(True or False).
e Assume variable a holds True and variable b holds False then:

1. axD If both the operands are true then (a and b)is False.
‘, (Logical AND Operator) | condition becomes true.
r.
| > OR . If any of the two operands are non-zero
| (a orb) is True.
(Logical OR Operator) then condition becomes true.
3, NOT Used to reverse the ogical
logi state of its | Not(aandb)is es, |
(Logical NOT Operator) | operand. S a 3
Bitwise Operators
Bitwise operators acts on bits and performs bit
by biti operation. Python rogramming provides
a manipulation operators to directly oper i ‘4
ate on the bits or binary oo directly.
hen we use bitwise operators on the o perands, the a “ft
operation is perfoon the bit
rmed di operands are firstly converte
to bits and
dti
Operators in Python Programming ; i
*d on two operands or one operand. are binary operators and unary operators that can b

Scanned with CamScanner


Programming with ‘Python’ 2.5 Python Operators and Control Flow Statements

« Following table shows bitwise operators assume a=10 (1010) and b=4 (0100).
| sr. No. Operator Description Example
1 & This operation performs | a&b 1010 & e100 90008

®
ut

ul
il
(Bitwise AND Operator) AND operation between
operands. Operator copies
a bit, to the result, if it
exists in both operands
2. | This
operation performs | a|b 1010 | 9100 1110 14
(Bitwise OR Operator) OR operation between
operands. It copies a bit, if
it exists in either operand.
3. 2 This operation performs | a*b=101@ * 6100 = 1110 =14
(Bitwise XOR Operator) | XOR operations between
operands. It copies the bit,
if it is set in one operand
but not both.
4. a It is unary operator and | ~a= ~ 1010 = e101
Bitwise Ones
Complement Operator) ee
operand.
aie
5. << The left operand's value is | a<<2 = 101@ << 2 =101000 = 40
(Bitwise Left Shift | moved left by the number
Operator) of bits specified by the
right operand.
6, >> The left operand's value is | a>>2 = 1010 >> 2 =@0@10 = 2
(Bitwise Right Shift | moved right by the number
Operator) of bits specified by the
right operand.
e Following table shows the outcome of each operations:
ee Tages :

0 0
0 1
1 0
a 1

Identity Operators
* Sometimes, in Python programming, need to compare the memory address of two objects; this is
made possible with the help of the identity operator.
* Identity operators are used to check whether both operands are same or not. Python provides ‘is’ and
‘is not’ operators which are called identity operators and both are used to check if two values are
located on the same part of the memory. Two variables that are equal does not imply that they are
identical. : - . -- ———

i. is Return true, if the variables on either side of the | >>> a=3


operator point to the same object and false | ,,, p.3
otherwise. >>> print(a is b)
True
2. is not Return false, if the variables on either side of the | >>> a=3
operator point to the same object and true | >>> p=3
| >>> print(a is not b)
Dak False

Scanned with CamScanner


Programming with 'Python'

Example 1:
>>> a=3
>>>, b=3.5
>>> print(a is b)
False
>>> a3
>>> b=4
>>> print(a is b)
False
>>> a=3
>>> b=3
>>> print(a is b)
True
>>>
Example 2;
>>> x=10
>>> print(type(x) is int)
True
>>>
Example
3:
2>> %2 = ‘Hello’
>>> y2 = ‘Hello’
>>> print(x2 is y2)
True
>> x2) = [1,253]
Be ¥3 =| [1,2,3]
>>> print(x3 is y3)
False
>>> x4=(1,2,3)
>>> -y4=(1,2,3)
>>> print(x4 is y4)
False
Pra _ In this example x3 and
_____ memory even though x4 are equal list but not identical. Inte Tpreter will loc
they have equal content. ate themst
Similarly x4 an
_ $e Membersh ip Operators d y4 are equal tables but no
The membership operat
ors in Python Programm
__ element in the sequence and ing are used i
used only with sequences i fa
Mi
ce
like stri act a “d
\é . ¥ TES
‘tup e. A memb P er Opesh
rat ic tl og i
iporsopeare used to check an item or an
rator reduces the effort el -
ae of sea chi gan ee an a ae A
rovovideide
s s ‘in’ i ;
‘in’ and ‘not in’ operators ' Tching an element in the list. 7
a value or variable is which are called
in a sequence,
a wait membership “a
ele Descr
True if value is fo Pe =e»
und in 1 ist or
and false it item in seque nce,
js Not in list >>> x="Hello World
or in seque
nce >>> print('H' in x
True (al
}
mM is in list or in
> x
Nelle a
E >>> prin t("Hello"|
Se
False
ae
Programming with ‘Python’
27 Python Operators and Control Flow Statements
Example:
>>> x="Hello World"
# using string
>>> print("H” in x)
True
>>> print("Hello” not in x)
False
>>> y={1:"a",2:"b"}
# using dictionary
>>> print(1 in y)
True
>>> print("a"
in y)
False
>>> z=("one","two", "three" ) # using tuple
>>> print ("two" in z)
True

Python Operator Precedence and Associativity


An expression may include some complex operations and may contain several operators. In such a
scenario, the interpreter should know the order in which the operations should be solved. Operator
precedence specifies the order in which the operators would be applied to the operands.
Moreover, there may be expressions in which the operators belong to the same group, and then to
resolve the operations, the associativity of the operators would be considered.
The associativity specifies the order in which the operators of the same group will be resolved, i.e.,
from left to right or right to left.
1. Python Operator Precedence:
¢ When an expression has two or more operators, we need to identity the correct sequence to evaluate
these operators. This is because the final answer changes depending on the sequence thus chosen.
Example 1:
10-4*2 answer is 2 because multiplication has higher precedence than subtraction.
But we can change this order using parentheses () as it has higher precedence.
(10-4)*2 answer is 12
Example 2:
10+5/5
is
When given expression is evaluated left to right answer becomes 3. And when expression
evaluated right to left, the answer becomes 11.
with the operators.
* Therefore, in order to remove this problem, a level of precedence is associated to the others.
relative
Precedence is the condition that specifies the importance of each operator
2. Associativity of Pythons Operators:
, associaiativity helps to determine which the order of
When two operators have the same precedence with same precedence are
ity decides the order in which the operators
weraiiane "associativ
executed. |
es of ass oci ati vit y.
e first.
edence is executed from the left sid
‘states all The operator of same prec
edence is executed from the right side first.
(ii) Right-To-Left: The operator of same prec
Most of the operators in Python have left-to-right associativity.
Example:
>>> SP2//5
3
>>> 5*(2//3)
e

Scanned with CamScanner


Scanned with CamScanner
Programming with Fysver: 2.9 Python Operators and Control Flow Statements
Note that indentation is required for statements which are under if condition.
Control Flow Diagram of if Statement: Example:
i=10
if(i<15):
Test Expression
print("“i is less than 15")
print("This statement is notin if”)
True
Output:
Body of if | i is less than 15
This statement is not in if

Statement just
below if 7"

Example 1: To find out absolute value of an input number.


x=int(input("Enter an integer number:"))
y=x
if (x<@):
X=-X
print( ‘Absolute value of',y, '=",x)
Output:
Enter an integer number:3
Absolute value of 3 = 3
Enter an integer number: -3
Absolute value of -3 = 3

Example 2: To find whether a number is even or odd.


number=int(input("Enter any number: "))
if (number%2)==6:
print(number, " is even number")

else:
print(number," is odd number" )

Output:
Enter any number: 10
1@ is even number
Enter any number: 11
11 is odd number

ers if-else Statement


* if statements executes when the conditions following if is true and it does nothing when the
false condition.
condition is false. The if-else statement takes care of a true as well as
Syntax:
if condition: OR if eg
statement(s) : if_bloc
else:
else:
else block
statement(s)
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Programming with ‘Python’ 2.18 _ Python Operators and Coritrol Flow Statements

OP MANIPULATION/LOOP CONTROL STATEMENTS


In Python, loop statements give us a way execute the block of code repeatedly, But sometimes, we
may want to exit a loop completely or skip specific part of loop when it meets a specified condition, {t
can be done using loop control mechanism.
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Loop control statements in Python programming are basically used to terminate a loop or skip the
particular code in the block or it can also be used to escape the execution of the program,
The loop control statements in Python programming includes break statement, continue statement
and pass statement.
break Statement
The break statement in Python terminates the current loop and resumes execution at the next
statement, just like the traditional break found in C.
Syntax: break
Control Flow Diagram for break Statement: Example: For break statement.
Enter loop 1=0
while i<10:
i=i+1
if is=5:
Vee break
print("i= ",1)
Output:
False ie
is2
is=3
Exit loop i=4

Bea continue Statement


The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.
Syntax: continue
Control Flow Diagram for continue Statement: Example: For continue statement.
Enter loop i=@
while i<10:
Test
expression isit1
of loop if is=5:
continue
print("i= ",i)
Output:
i=1
i=2
Exit loop ie
i=4
i=6
i=7
is8
i=9
i=10
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Programming with ‘Python’ 2.22 Python Operators ene Control Flow ewey |
Output:
enter &@ number: 121
Humber is palindrome
enter a number; 123
Number is hot palindrome
8. Program to return prime numbers from a list.
List«(3,2,9, 10,43, 7, 20,23)
PRINT( "Lists", list)
ist)
PRINC( "Prime numbers from the List are:")
for ain List:
primesTrue
for i in range(2,a):
if (aXixx@);
prime=False
break
if prime;
lL. append(a)
printd))
Output:
list= (3, 2, 9, 10, 43, 7, 20, 23]
Prime numbers from the list are:
(3, 2, 43, 7, 23)
9, Program to add, subtract, multiply and division of two complex
numbers,
print("Addition of two complex numbers : ", (4435)+(3-73))
print("Subtraction of two complex numbers ; ",
(4433)-(3-735))
print("Multiplication of two complex numbers : ",
(4435)*(3-735))
print("Division of two complex numbers : ", (4439)/(3-73))
Output:
Addition of two complex numbers ; (7-43)
Subtraction of two complex numbers : (1+107)
Multiplication of two complex numbers : (33-193)
i
Division of two complex numbers : ([email protected]+0 .637931034482758
74)
gr m to find the best of two test average marks out of thre
e test's marks accepted from the
Ant(input(‘enter a number'))
Qeint(input('enter 2nd number’ ))
int(input('enter the 3rd number’ ))
le(nl+n2)/2
avg2=(n2+n3)/2

. Scanned with CamScanner


Scanned with CamScanner
a.
Data Structures
in Python
Chapter Outcomes...
Write Python program to use and manipulate lists for the given problem.
eae

Write Python program to use and manipulate tuples for the given problem.
Write Python program to use and manipulate sets for the given problem.
Write Python program to use and manipulate dictionaries for the given problem.

Learning Objectives...
To learn Concepts of Lists like Defining, Accessing, Deleting, Updating and so on
eeeee

To understand Basic List Operations and Built-in List Functions


To Study Concept of Tuples with Accessing, Deleting, Updating Values in Tuples
To study Basic Tuple Operations and Built-in Tuple Functions
To understand Concepts of Sets with Accessing, Deleting, Updating Values in Sets
To understand Basic Set Operations and Built-in Set Functions
Sem

To know Concepts of Dictionaries with Accessing, Deleting, Updating Values in Dictionary


To study Basic Dictionary Operations and Built-in Dictionaries Functions

Eta) inrropuction
A data structure is a specialized format for organizing and storing data, so that various operations
can be performed on it efficiently and easily.
Any data structure is designed to organize data to suit a specific purpose so that it can be accessed
and worked with in appropriate and systematic manner/way. There are four data structures in
Python namely, list, tuple, dictionary and set.
A data structure that stores an ordered collection of items in Python is called a list. In other words, a
list holds a sequence of items or elements.
Similar to a list, the tuple is an ordered sequence of items. A set is an unordered collection of unique
items in Python. A dictionary in Python is an unordered collection of key value pairs.
The data types that are most used in Python are strings, tuples, lists and dictionaries. These are
collectively called as data structures.
EEG usts
A list in Python is a linear data structure. The elements in the list are stored in a linear order one
after other. A list is a collection of items or elements; the sequence of data in a list is ordered.
The elements or items in a list can be accessed by their positions ie. indices. The index in lists always
starts with O and ends with n-1, if the list contains n elements.
[3.1]

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
_
Pi ming with ‘Python’
35 _ Data Structures In Python

« Following table shows the list methods used for updating list.

Sr.
No. 2 rae Syntax Argument Description Return Type

1. | append() | list append(item) The item can be numbers, | Only modifies the
strings, another list, | original list. It does not
dictionary etc. return any value,
2, | extend() | listi.extend(1ist2) This extend() method| Only modifies the
takes a list and adds it to | original list. It doesn't
|_—— the end. return any value.
3, | insert() | list. insert(index, element) | This index is position | It does not return
where an element needs | anything; returns
to be inserted element - | None.
this the element to be
inserted in the list.
Let use see above methods in detail:
i, append() Method: The append() method adds an element to the end of a list. We can insert a
single item in the list data time with the append().
Example: For append() method.
>>> list1=[10,
20, 30]
>>>! Listi
[10, 20, 30]
>>> listl. append(4@Q) # add element at the end of list
>>> list1
[10, 20, 30, 40]
extend() Method: The extend() method extends a list by appending items. We can add several
items using extend() method.
Example: Program for extend() method.
>>> list1=[10, 20, 30, 40]
>>> list1
[10, 20, 30, 40]
>>> list1.extend([60,
70]) # add elements at the end of list
>>> list1
[10, 20, 30, 40, 60, 70]

insert() Method: We can insert one single item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.
Example; Program for insert() method.
>>> listi=[10, 20]
>>> listl
(16, 20]
>>> list1.insert(1,3@)
>>> list1
[10, 30, 20]
>>> listi=insert(1,[15,25])
>>> listi
—__ [10,[15, 25], 30, 20]

- Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Programming with ‘Python’ 3.9 es
In Python
Data Structur
il a
a max (list) It returns the item that has the | >>> list1
maximum value in a list. (1) 24.39 452d
>>> max(list1)
5
3. sum(list) Calculates sum of all the elements of | >>> list1
list. [4,25 35, 45. 5)
>>> sum(list1)
15

4. min(list) It returns the item that has the | >>> list1


minimum value ina list. [iy 2, Se dood
>>> min(list1)
1

5. list(seq) a tuple into a list.


It converts >>> list1
[1, 2, 3, 45 oa
>>> list(list1)
[wien 4d

Methods of List Class:


| Sr. No. Methods Description Example
J, list.append(item) It adds the item to the end of the | >>> list1
list. felipe 2ieaan 45553)
>>> list1.append(6)
>>> list1
[1, 2, 3, 4, 5, 6]
2. list.count(item) of times
It returns number the item | >>> list1
occurs in the list. FL 2 Sa 576, 31]
>>> list1.count(3)
2

Ey list.extend(seq) It adds the elements of the sequence | >>> list1


at the end of the list. Fa, e2ybr3a 4g! 5]
sprciist2
[cay Bay rer)

>>> list1.extend(list2)
>>> list1
(1,237 sey Sf ey
‘BY, 'C']

4, list .index(item) It returns the index number of the | >>> list1=[1,2,3,4,5,3]


item. If item appears more than one | 555 1ist1
ee be returns the lowest index [1, 2, 3, 4, 5, 3]
= ' >>> list1.index(3)
2

— 5. list.
ist.iinsert index, (inde item) It ins
inserts the given item onto
: the | >>> » list1
given index number while the} (1, 2, lis 3, 4, 5, 3]
elements in the list take one right >>> listl.insert(2,7)
shift. >>> list1
[3.2235 3, 4, 5, 3]
Data Structures in Python
Programming with ‘Python’ 3.10

returns the last | >>> list1


6. list.pop(item=list[-1]) It deletes and 4 5, 3)
[1,29 7,233
element of the list.
>>> list1.pop()

>>> list1l.pop(2)

from the >>> list1


7 list.remove(item) It deletes the given item 5]
[1, 2» 3 4,
list.
>>> list1.remove(3)
>>> list1
[1, 2. 4 5]

| >>> list1
list .reverse() It reverses the position (index 5]
. s list.
in the [1, 2, 3, 4
number) of the item
>>> listl.reverse()
>>> list
4, 3, 25 1)
[5,

>>> listl
a list.sort() Sorts items in the list.
[1, 35 2, 4, 5]
listl.sort()
>>>
Sous. 25:4, 5]

It sorts the elements inside the list | >>> list1


10. list.sort([func])
uses compare function if|[1, 3, 2, 5, 4]
and
provided. >>> list1.sort()
3 Ste
(ieee, 4,75)

Ee turtes as items or
on tuple is a sequence of data values called
A tuple is also a linear data structure. A Pyth
unchangeable.
elements. A tuple is a collection of items which is ordered and
angeable, ordered sequence of
A tuple is a data structure that is an immutable or unch
values cannot be modified.
elements/items. Because tuples are immutable, their
for grouping data. Each element or value that is
A tuple is a heterogeneous data structure and used
inside of a tuple is called an item.
we cannot add or remove
A tuple is an immutable data type. An immutable data type means that
items from the tuple data structure.
values in tuples ca n also b heiri
In Python tuples . are writ; ten with rounF d brackets () and e accessed by t
ing from 0.
index values, which are integers start ‘
Tuples are the sequence or series value s of different types separated b com :
are
ust
}
iy commas (,). Tuples
y
like lists, but you can not change their values.
:
Difference between Tuples and Lists
i cre i les,
4. Avvalues in odthe list can be replaced :with another any time after r its
the values in it cannot be replaced with another, once tuples are created. ; ——— oe
it !§
2. Lists allows us to add new items to i us to add new items, once
allow
0 it, but tuple does not
created.
3. We generally use tuple for heterogeneous
z
(diffi
(different) datatype s and
:
list for homogeneov®
(similar) data types.

Scanned with CamScanner


_
3.11 Data Structures in Python
Progrem =

4, Since, tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
5. Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
6. Tuples can be used as values in sets whereas lists can not.
7. Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values
like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists
are not immutable.
Following table shows difference between strings, tuples and lists.
immutable (Value cannot be modified) Mutable (values can be modified)

str="hi" tuples=(5,4.0,'a') list=[5,4.0','a']


1. | Sequence Unicode Ordered sequence. Order sequence.
| character.
2 | Values cannot be modified. | Same as list butitis faster | Value can be changed dynamically.
than list because it is
immutable.
3. | Itisa sequence of Values stored in alpha Values stored in alpha numeric.
character. numeric.
4. | Access values from string. | Access values from tuples. | Access values from list.
5. | Adding values in not Adding values is not Adding values is possible.
possible. possible.
6. | Removing values is not Removing values is not Removing values is possible.
possible. possible.

EET creating Tuple


To create tuple, all the items or elements are placed inside parentheses () separated by commas and
assigned to a variable.
The syntax for defining a tuple in Python is: <tuple_name> = (value1, value2, ... valueN).
Here, tuple name indicate name as the tuple and value1, value2,...valueN are the values assigned to
the tuple.
Example: Emp (22, “Amar”, ‘M’, 5@)
A tuple in Python is an immutable data type which means a tuple once created cannot be
altered/modified. Tuples can have any number of different data items (integer, float, string, list
etc.).
-_ method to create a tuple in Python is simply assigning a set of values to the tuple using
name't’.
oe assignment operator (=). For example: t() # creates an empty tuple with
Example: For creating tuples.
>>> tuplei=(10, 28, 38) # Atuple with integer values
>>> tuplel
(18, 20, 30)
>>> tuple2=(18, "abc", 11-22, *x") # Atuple with different data types
>>> tuple2
(1®, ‘abe", 11.22, *X*) 4 ah
>>> tuple3=(“python", [10, 20, 32] ,[11,"abc",22.33]) # Nested tuple

>>> tuple3
2@, 3@], [11, ‘abc’, 22.33])
(python’, [18,

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
ing with ‘Python’ Data Structures in Python
Programmingwith ‘Python 3.15
2, Membership Function:
ator evaluates to true
we can test if an item exists in a tuple or not, using the keyword in. T he in oper
if it finds a variable in the specified sequence and false otherwise.
Example: For membership function in tuple.
>>> tuple
(10, 20, 30, 40, 5@)
>>> 30 in tuple
True
>>> 25 in tuple
False
3, Iterating through a Tuple:
> Iteration over a tuple specifies the way which the loop can be applied to the tuple.
Following example uses a for loop to
¢ Using a for loop we can iterate through each item in a tuple.
simply iterates over a tuple.
Example: For iterating items in tuple using for loop.
>>> tuple=(10, 20,30)
>>> for i in tuple:
print(i) # use two enter to get the output

Output:
10
20
30
>>>

FR Build-in Functions and Methods of Tuple


programming.
¢ Following table built-in tuple functions in Python *
: Description Example _
| ‘Sr, No. Function
Gives the total length of the | >>> tup1
: 1. len(tuple) (L302 903)
tuple.
|
>>> len(tup1)
:
3
Returns item from the tuple | >>> tup1
2. max (tuple) (f°7500)
:
with max value.
>>> max(tup1)

Returns item from the tuple | >>> tup1


3, min(tuple) (1, 2, 3)
with min value.
>>> min(tup1)
1
1=(1,2,3)
4. ere It zips elements from two tuples | >>>» tupi
list of tuples.
inato >>> tup2=("A’, ‘B’,"C')
>>> tup3=zip(tup1, tup2)
>>> list(tup3)
[(1, ‘A’), (2, *B'), 3, “C')I
: eet ————T converts a list into tuple. >>> tuple1 = (1, 2, 3, 4, 5)
: 5. tuple(seq) >>> listi = list (tuple1)
: >>> list1
[1,2,3,4,5]
ie eres

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
fone]
Programming

.
with ‘Python’

| synmetric_aifferenceQ Returns a
3.20 es...
Set with | set-symmetric_difference
nevgymmetric
so,(
Data Structures
In Py
“yp
>
the f two or
differences 0 ra
pa
more sets : ih the set symmetric difference update.
ts symmetric_difference_update() | Modify this set with of
symmetric rat
ie eh
8. ca this
isdisjoint() Detersetmines
and others r
wheth e or | set.isdisjoint(set) |
not two sets have any |
a elements in common Ehtaktpet) |
": issubset() Determines whether one | set.is
set is a subset of the |
Raa other t =|
oe issuperset() Determines whether one | set. issuperset (set) |
set is a superset of the |
——————— other
i. add(item) —_|
It adan
dsitem to the set. | set.add(set) |
It has no effect if the :
item is already present in
——_—_ 4} the set.
12. discard(item) It removes the specified | set.discard(set)
= |
item from the set,
B. remove(item) Remove an element from | set.remove(set)
a set; it must be a
member. If the element
is not a member, raise a
KeyError.
i. pop() Remove and return an set .pop(set) |
arbitrary set element
that is the last element of
the set. Raises KeyError
if the set is empty,
15; update()
Updates the set with the
union set. update(set)
of itself and
, others
¢ Built-in functions like all(), any()
:
used with enume rate(), len.
set to perform ” ,
di fferent tasks, Considen, max max), min a Sorted(), sum() etc. are com
e Following table lis ts er set A = {3, 1,6, monly
built-in functions for set;
| Sr. ¥ |
NG) | so ee
fi: all() Return True if all elem :
is empty). —+—
> any() Return True if any elem set >>> all (A) True
t aa!
empty, return False. of the set is true
3. | len() Return the length (the number of . If the set is >>> any (A) True
items) in the mg pe
4. | max() Return the largest item in the set >>> len(A)
, —--———____ 4
———
5. | min() Return the smallest item in the >>> max(A)
ger
7 ——|
6. sorted() | Returnanew sor >>> min(A)
ted listel
sort the set itself),
fromea————__
Nom elements in the sedoas nce
1 el
7. sum() Netrun the sum of all lements in theaop >>> sorted(A)
[1, 3, 6, 7]
>>> sum(A)
17 eee

Scanned with CamScanner


Scanned with CamScanner
Data Structure. inp
Programmin, with ‘Python’ y
3.22 The, j
ictionary. Diction;
A pair of curly braces wit as an emp ty
’ ues ain bet; ween , is known
dictionary
h no val sia Ter,
are accessed by keys, not by their e : ictionar
ne the keys in the fe ence y are unique. Diction.
as and when TeQuirey
Tenechaer
nges
able (m ohana : Nae omni or update the oie as look
i tha
ch the same way tlk
up a word “a @ Pape Dag.
: dieibore de fi
* and the de nition is its COrrespo,
eae definition ie, the 3."
‘value’, word is the ' key Xdin,
Dictionaries can el ! iction r
nary can contai n another di
e
be nested i.e. a dictio ary.
Creating Dictionary
* A dictionary can be us values in a way that al
individually referenc ed to store a collection of data dex to identi lows them ;, be
dictionary is stored
ed , Ho we ve r, rather than using an fy a da ta va lu e, each tem in,
as a key value pair. in
The simplest m method to create dictionary is to simply
: assign
: the pa ir of key:values to the dictionay, :
using operator (=)
There are two
wa s for creation
1. We can teats a dictionary byof dict ionary in python.
placing a oda bra ERBEE: of key:valu Bis in con
{}. Each key is Separated from its asso e p Y brace,
ciated value by a colon(:).
Example: For creating a
dictionary using { }.
>>> dicti={}
>>> dict1 # Empty dictionary

>>> dict2={1:"Orange",
>>>
2:"Mango", 3:"Banana"} # Dictionary
dict2 with integer keys
ake ‘Orange’, 2: "M
ango' 5 Sh ‘Banana’
>>> dict3={"name }
":" vijay", 1:[16,
>>> dict3 20] } # Dictionary with mixed keys
{'name': ‘vijay’, 1: [10,
20}}
2. Python provides a bu
ild-in function dict()
Example: Creating for Creating adictiona
directory ry.
>>> di=dict({1: using dict().
"Orange", 2: "Mango
>>> dacdict ycae ", 3: "Banana"})
g d,s (2 Yellow")
>>> d3=dict(one= , (3, "Gree?)])
1, two=2, three=3)
>>> di
{1: ‘Orange’, 2: ‘Mango’, 3: ‘Banana '}
>>> d2
{1: 'Red', 2: "Yellow',
>>> d3
3: ‘Green '}
{'one': 1, 'two': 2, ‘three’: 3}
Accessing Values
ina Dictionary
* Wecan access the items
ofa dictionary by follow;
1. Referring to its key name, ins} ,
oe Ways:
Example: For access
ing dictionary;
>>> dict 1={'name':
>>> dict1['name'
]
‘vijay’
>>> dicti['adr']
Traceback (m
ost recent
File “<pyshell# cal) last):
79>" 1
dicti[‘adr']
KeyError: ‘adp*
>>>
Here, if we refer
to a key that
avoided by using get 's not in the
() method. ime
mary, ;
7ow'll get an ©*ception.Th
is error ¢3"on
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
ng ‘Python’ __Data Structinur hon,
Pytes
programmiwith 3.25

dictionary keys
2. Keys must - immutable. Which means you can use strings, numbers or tuples as
but something like [‘key’] is not allowed.
Example:
>>> dict={[1]:'Vijay',2:'amar',3;'santosh'}
Traceback (most recent call last):

File “<pyshell#2>", line 1, in <module>


dict={[1]:'Vijay',2:'Amar',3: 'Santosh'}
TypeError: unhashable type: ‘list!

Built-in Functions and Methods for Dictionary


» Python has a set of dictionary methods that we can use on dictionaries. Some of them are given in
following table.

sr. Method : on
D escripti Example
No.
elements | dict={1:'V ij
‘Amar ’ ay ’,
,3:'S 2:
antos h’ }
1. | clear() Removes all the
from the dictionary. Sosy oki:
{1: ‘Vijay’, 2: ‘amar’, 3: ‘Santosh'}

>>> dict.clear()
>>> dict
{}
copy of the | >>> dict={1: ‘Vijay’, 2: ‘amar’, 3: ‘Santosh’}
Z copy() Returns a
dictionary. >>> Xedict.copy()
>>> X

{1: 'Vijay', 2: ‘Amar’, 3: "Santosh' }

3. | fromkeys() The fromkeys() method | >>> dict=dict.fromkeys(['Vijay’, ‘Meenakshi'], ‘Author’ )


creates a new dictionary | >>> dict
with GE value for all {'Vijay': ‘Author’, ‘Meenakshi’: ‘Author’}
specified keys. —
If default value is not
specified, all keys are set to
None.

4. | get() Returns the value of the | >>> dict1={'name': ‘vijay’, ‘age’ :40}
specified key. >>> dict1.get( ‘name’ )
‘vijay’

a list containing | dict{1: ‘vijay’, 2: ‘Amar’, 3: 'Santosh'}


5. | items() Returns
the a tuple for each key | >>> for i in dict.items():
value pair. print(i)
(1, 'Vijay’)
(2, ‘Amar')
(3, 'Santosh')
ij
‘Amar ’ ay osh"}
Sant2:
,3:"',
6. | keys() Returns a list containing | dict={1:'V
the dictionary's keys. >>> dict.keys()
dict_keys([1, 2, 3])
-————
Removes the element with | dict=(1:'Vijay',
:
2: "Aman" ,3:'Santosh’}
7. | pop() ct.pop(2)) >>> print(di
the specified key.
Amar
=
See
Scanned with CamScanner
Scanned with CamScanner
*

-
a

Called

Scanned with CamScanner


Programming
with ‘Python’ 3.28 Data Structures in Python
>>> a

Traceback (most recent call last):


File "<pyshell#9>", line 1, in <module>
a
NameError: name ‘a’ is not defined
+ operator (String Concatenation):
* The concatenation operator (+) is used to join two strings.
Example: For + operator in string.
>>> "Hello" + "Python"
"HelloPython'
>>> sl="Hello”
>>> s2="Python"
>>> sl+s2
"HelloPython'
* Operator (String Multiplication):
¢ The multiplication (*) operator is used to concatenate the same string multiple times, it is called
repetition operator.
Example: for * operator in string.
>>> sl="Hello "
>>> S2=3*51
>>> s2
"Hello Hello Hello '
SSSA LISS
RRR KAR HK!

>>> a=" FF"


>>> a*S
4 oe fe ok oe ok ok Ko I

>>>

String Traversal (Traversing String with for Loop and while Loop):
e Traversal is a process in which we access all the elements of the string one by one using for and while
loop.
Example: Traversing using for loop.
>>> s=”Python Programming”
>>> for ch in s:
print(ch,end="")

Python Programming
>>> for ch in range(@,len(s),2):
print(s[ch],end="")

Example: Traversing using while loop.


>>> s=”Python Programming”
>>> index=0
>>> while index<len(s):
print(s[index],end="")
index=index+1
Output:
Python Programming


Scanned with CamScanner
3.29 Data Structures inPython

str iT gs:

gs are immutable which means that we cannot change any element of a string. If
we want to
change an element of a string, we have to create a new string.
— Example: For immutable string.
>>>str="Python”
>>estr
*python’
>>>str[@J="H"
Traceback (most recent call last):
File “<pyshell#33>", line 1, in <module>
str[@]="H"
ay TypeError: ‘str’ object does not support item assignment
« Here, when we try to change the 0" index of string to a character “H”, but the python interpreter
generates an error. The solution to this problem is to generate a new string rather than change the
old string.
Example:
>>>str="Python”
>>> stri='H'+str[1:]
>>> stri
"Hython'
* Consider the following two similar strings:
Stri=”Python”
Str2=”Python”
Here, Str1 and Str2 have the same content. Thus python uses one object for each string which has the
same content. Both Str1 and St2 refers to the same string object, whereas Str1 and Str2 have the
same ID number.
Example:
>>> Stri="Python”
>>> Str2="Python” Str1
>>> id(Str1)
54058464 Str2
>>> id(Str2) Fig. 3.7
54058464
String Indices and Accessing String Elements:
* Strings are arrays of characters and elements of an array can be accessed using indexing. Indices
start with O from left side and -1 when starting from right side.
S1=“Hello Python”

o | 1-|.2 | 3 4} 5 he 10 | 11
oo

wo

~2|-1/-10/-9|}8|7/+6/s/;la4f3foatTla
——_——
Example:
>>> sl="Hello Python"
>>> print(s1[@]) # print first character
5 H
«>> -print(s1[11]) # print last character
a
>>> print(si[-12]) # print first character
ee
q

Scanned with CamScanner


Scanned with CamScanner
Programming with ‘Python’ 3.32 Data Structures in Python

3 \r ASCII Carriage return (CR) >>> print("Hello \r World!”)


Hello World!

10. |\t tab (TAB)


ASCII Horizontal >>> print("This is tav \t key”) an
This is tav key

\v ASCII Vertical tab (VT) >>> print("Hello \v World!”)


Li:
Hello
World!

12. \ooo ASCII Character with octal | >>> print("\110\145\154\154\157\40\127


value 000 \157\162\154\144\41")|
Hello World! |
with hex | >>> print ("\x48\x65\x6c\x6C\x6F\x28\x57 )
13; \xhhh... ASCII Character
value hh... \x6FAX7\X6C\x64\x21") |
|
Hello World!

String Formatting Operator:


called the
¢ Thestring in Python have a unique b uilt-in operation, the % operator (modulo). This is also
up for the pack of having
string formatting operator. This operator is unique to strings and makes
functions from C's printf() family.
gs Example:
>>> print("My name is %s and weight is %d kg!"%('Vijay' ,6@))
My name is Vijay and weight is 60 kg!

_ Sr. No. Format Symbol Conversion


al %C Character.
Pa %S string conversion via str() prior to formatting.
3 %i signed decimal integer.
4. %d signed decimal integer.
a %u unsigned decimal integer.
6. %0 octal integer.
7. %X hexadecimal integer (lowercase letters).
8. WX hexadecimal integer (UPPERcase letters).
9, %e exponential notation (with lowercase 'e’).
10. %E exponential notation (with UPPERcase 'E’).
11. %f floating point real number.
AZ %E the shorter of %f and %e.
is %G the shorter of %f and %E.
String Formatting Functions:
e

:|
Python includes the following built-in functions to manipulate strings.

|
1. | capitalize() Makes the first letter of the | >>> sl="python programming”
string capital. >>> sl.capitalize() :
‘Python programming’ _

2. | center(width, Returns a space padded string | >>> si="python programming” )


fillchar) | with the original string centered | >>> print(si.center(3@, ‘*’))
to a total width columns. #s#***python programming****** |

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
Scanned with CamScanner
CA
Python Functions,
moi
Modules and Packages ,
Chapter Outcomes...
s) Use the Python standard func
tions for the giving problem,
a)

lm) Develop relevant user defined func


tions for the given problem using
the Python code.
f™] Write Python module for the
given problem.
fm) Write Python package for the give
n problem.

Learning Objectives...
To learn Basic Concepts of Functions
Seeemee

To study use of Python Built-in Functions


To understand User Defined Functions with its Definition, Calling, Argu
ments Passing etc.
To study Scope of Variables like Global and Local
To learn Module Concept with Writing and Importing Modules
To study Python Built-in Modules like Numeric, Mathematical, Functional Programm
ing Module
To learn Python Packages with its Basic Concepts and User Defined Packages

ZX irropuction
Functions, modules and packages are all constructs in Python programming that promote code
modularization. The modularization (modular programming) refers to the process of breaking a
large programming task into separate, smaller, more manageable subtasks or modules.
A function is a block of organized, reusable code that is used to perform a single, related
action/operation. Python has excellent support for functions.
A function can be defined as the organized block of reusable code which can be called whenever
required. A function is a piece of code that performs a particular task.
A function is a block of code which only runs when it is called. Python gives us many built-in
functions like print() but we can also create our own functions called as user-defined functions.
A module in Python programming allows us to logically organize the python code. A module is a
single source code file. The module in Python have the .py file extension. The name of the module
i file.
este meauie re defined as a python program file which contains a python code including
python functions, class, or variables. ie ee words, we can say that our Python code file saved with
i i as the module.
necro us to create a hierarchical file directory structure of modules. For
example, mymodule.mod1 stands for a module modi, in the package mymodule.
A Python package is a collection of modules which have a common purpose. In short, modules are
.
grouped together to forms packages
[4.1]

Scanned with CamScanner


Programming with 'Python'

ONS _ ms isi gram that performs . m


EEG use OF PYTHON BUILT-IN FUN that act like a Pro

Functions are the self-contained block of sta
tements available for use. These ;fur»;
task. functions that are always the given object to the Stand,,
The Python interpreter has a number of fun int) function prints
are called built-in functions. For ean
2 fic tasks. Some : of these “UNCtipy.
fy,
output device (screen) or to the text stream ie ss
perform Te type conversion functions a,
Python built-in (library) functions can be ¥ and some are C
comes in category of mathematical functions
on
Type Data Conversion Functions n the puilt-in types. To convert betwee,
Sometimes it's necessary to perform conversions betwee
types we simply use the type name as a function. rform special kinds of conversions. a) of
In addition, several built-in functions are supplied to pe rted value.
these functions return a new object representing the
nvert one data type to another. Dats
Python defines type conversion functions Ry es ee
conversion in Python can happen in following two : licitly, and/or
1. Either we A the compiler to convert a data type to some other type exp y
2. The compiler understands this by itself and does it for us.
on Implicit Data e Conversion: . . ae
eee one ne data type conversion takes place either during compilation or during
run time and is handled directly by Python.
Example: For implicit data type conversion.
>>> a=10
>>> b=25.34
>>> sum=a+b
>>> print sum
35.34
>>>

In the above example, an int value a is added to float


value b, and the result is automatically
converted to a float value sum without having to tell
the compiler. This is the implicit data
conversion.
In implicit data conversion the lowest Priority data
type alwa et i iority
data type that is available in the source code,
¥® Bet converted to the manent priority
Python Explicit Data Type Conversion:
Explicit conversion also known as type casting
where we fo s
While developing a program, sometimes it is desi Ce
esirab wre an expression to be of a specific type.
Python, this can be accomplished very easily by le
i ng useto ofconve
makaki rt one data type into another. !1‘
built-iin type conversi
ilt-
on functions.
Ew oO Tresenti
data type conversion fun
ra =
ctions with their sles
Ariat
es : 1See
givenoain e
fols awe
lowing tab A Uist
le
1. | int(x [,base]) Converts x to an|
base specif: ies the bas
inte egeifx
r. | x=int¢|. : = oe,
net" aa60 »base= 2)=12
is a stri
ng.
2) long(x
“int (*1234: »base=8)=668
[,base] ) Converts * Suey lon
es
integer. base SPeCifies the
x=long( “123” base=g)=331
3 = ase if xis a strin
g. *=long( BC «44>
7 oat(x) Converts
*11 sbase=16)=17L
x to a float
point number. ting- x :
-
“Float( 123 .45*)=193.45 ‘

contd

Scanned with CamScanner


Packages
with ‘Python’ 43 Python Functions, Modules and

complex(real[,imag]) Creates a complex number. x=complex(1,2) = (1+23)

S. str(x) Converts object x to a string xestr(10) = ‘10’


representation.
. 6 repr(x) Converts object x to an xepepr(3) = 3
expression string,
9, | eval(str) Evaluates a_ string and xzeval('1+2') = 3
returns an object.
fe ot tuple(s) Converts s to a tuple, xetuple('123') = (‘1', ‘2°. 3")
x=tuple([123]) = (123, )

rg, ~—si|: List(s) Converts s to a list, yelist('123') = ['1', '2'> ras)


xelist(['12'] = ['12']
10. set(s) Converts s to a set. x=set('Python') LA. ‘h'}
a ns Tee ‘o', oP"

11. dict(d) Creates a dictionary. d dict={'id':'11", ‘name': 'vijay'}


must be a sequence of (key, print (dict)
value) tuples. ={'id': '11', ‘name’: ‘vijay'}

12. chr (x) Converts an integer to a x=chr(65) = ‘A’


character,
Converts an integer to a xsunichr(65) =u’A’
1s; unichr(x)
Unicode character.
» 14, ord(x) Converts a single character x=ord('A')= 65
to its integer value.
hex (x) Converts an integer to a x=hex(12) = @xc
15.
hexadecimal string.
Converts an integer to an x=oct(8) = 0010
i 16. oct(x)
octal string.
rmastting Numbers and Strings:
into a specified format.
The format() function formats a specified value
‘Syntax: format(value, format )
ation
_ Example: For string and number form
>>> x=12.345
>>> format(x,".2f")
2.35!
>>>

>>> x=10. 23456


>>> format(x,"<10.2F")
space).
"10.23

: ons the result (within the available | >>>x=10.23456


- Banee’y >>> format(x,">10.2f")
P t 10.23'

A ; the result (within the | >>>x=10.23456


oe Ee >>> format (x, "*10.2f")
* 10.23 ‘
contd. ..

Scanned with CamScanner


Scanned with CamScanner
programming with ‘Python’ 45 Python Functions, Modules and Packages

Built-In Mathematical Functions


Input x
function can be described as a piece of code that may
or may not take some value(s) as input, process it, and
then finally may or may not return any value as Function f:
output.
python’s math module
is used to solve problems
related to mathematical calculations. Some functions Output f(x)
are directly executed for maths functions we need to Fig. 4.1
import math module first.
In python, there are two types of pre-defined functions.
Built-In Functions (Mathematical):
These
These are the functions which doesn't require any external code file/ Modules/ Library Files.
t Rp

»
is no nee d of
are a part of the python core and are just built within the Python compi ler hence there
importing these modules/libraries in our code.
» Following table shows some of in built mathematical functions:
Sr. No. | Functions Description Example
min() Returns smallest value among supplied | >>> min(2, 10, 30)
i
arguments. 10
2; max() Returns largest value among supplied | >>> max(20, 10, 30)
arguments. 30
3. pow( ) The pow() function returns the value of x to the | >>> pow(2, 3)
power of y (xy). If a third parameter is present, it | 8
returns x to the power of y, modulus z. >>> pow(2,3,2)
8

The round() function returns a floating point | >>> round([email protected])


4. round()
number that is a rounded version of the | 10
specified number, with the specified number of | >>> round(5.76543)
decimals. The default number of decimals is 0, | ¢
will return the | ,,, pound (5.76543, 2)
meaning that the function
nearest integer. =o :

Absolute function, also known as Modulus | >>> abs(-5)


5. abs()
(not to be confused with Modulo), returns the | 5
>>> abs(5)
non-negative value of the argument value.
5

2. Built-In Functions (Math Module):


some external files(modules) in order to be used. The process of
* The second type of functions require to do is import the file into
using these exter nal files in our co de is called importing. So all we have
dy written in that file.
our code and use the functions wh ich are alrea
ns of Math Module
* Following table shows some of inb uilt mathematical functio
Tear
Description
© ge A

returns the smallest integral >>> math.ceil(2.3) .


This function
number is
value greater than the number. If
3
returned.
already integer, same number is
integral >>> math. floor(2.3)
This function returns the greatest
number is
value smaller than the number. If
2
integer, same number is returned.
lready intege!
| already
contd.

Scanned with CamScanner


in Pan’ 46 Python Functions, Modules and Pac’ chages:

i turns thecosine of value | >>> math.cos(3)


- BOGE! Gs wekcnant The value passed in this | [email protected]
function should be in radians. fg tT ee
>>>math.cos(@)
1.6
4. | cosh() Returns the hyperbolic cosine of x. Rinietseriiee 3))
5, | copysign() Return x with the sign of y. On a platform | >>> math. copysign(1®, -12)
that supports signed zeros, copysign(1.0, -0.0) | -10.0
returns -1.0.
6. | exp() The method exp() returns returns exponential | >>> math.exp(1)
of x. 2.718281828459845
>>>
7. | fabs() This function will return an absolute or | >>> math.fabs(1@)
positive value. 10.8
>>> math. fabs(-2@) .
20.8
8. | factorial() Returns the factorial of x. >>> math. factorial(5) |
120
9. | fmod() This function returns x % y.
| >>> math. fmod(5@, 16)
2.0
|
>>> math. fmod(5e, 2@)
I
10.08
| 10, | log(a,(Base)): | This function is used to compute the natural
| >>> print(math. log(14))
logarithm (Base e) of a. 2.6398573296152584
11. | log2(a) This function is used to compute | >>> rint(math.log2(14) )
the logarithm base 2of a. Displays more | 3.807354922057604
accurate result than log(a,2).
12. | log1e(a) This function is used to compute | >>> print(math.10g10(14) )
the logarithm base 10of a, Displays more
| 1.146128035678238
accurate result than log(a,10).
13. | sqrt() The method sqrt() returns the square root of
x | >>> math. sqrt(1@@)
for x>0. 10.0
>>> math.sqrt(5)
2.23606797749979
14. | trunc() This function returns the truncated integer
of | >>> math .trunc(3.354)
x 3
ee eee cole eral fae it f TPs rts me ASN a ee ee .
ES user verwen FUN 5 sr ts hl di Dat ae
per ts ada eat
* Functions in Python programming are self- contained
programs that perfo rm some parti Erte
Once, a function is created by the progr ammer cular tasks.
for a specific task, th is funct
anytime to perform that task, ion can be called
Python gives us many built-in functions like Prin
t(), len() etc. but we can also creat
functions. These functions are called user- defined e our own
functions,
User defined function are the self- contained block
of statements created by users according to their
requirements.
A user-defined function is a block of related code
state
related action or task. A key objective of the concept
modularity and enable reusability of code.

Scanned with CamScanner


program minging ¥with 'Python' 4.7 Python Functions, Modules and Packages

Function Definition
Function definition is a block where the statements inside the function body are written. Functions
allow us to define a reusable block of code that can be used repeatedly in a program.
Syntax:
def function-name(parametes ) t
"function_docstring"
function_statements
return [expression]
Defining Function:
. Function blocks begin with the keyword def followed by the function name and parentheses ()-
. Any input parameters or arguments should be placed within these parentheses. We can also define
parameters inside these parentheses.
« The first statement of a function can be an optional statement - the documentation string of the
function or docstring.
» Thecode block within every function starts with a colon: and is indented.
e The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is the same as return None
* Thebasic syntax for a Python function definition is explained in Fig. 4.2.
Function name Arguments
An identifier by which the ~- - -. ----» Contains a list of values
function is called ‘ : passed to the function
def name(arguments):
indeittatl statement
ion Function body
Function body must ~---- Ser ---- This is executed each time
be indented ~ the function is called
return value
: Return value
*---® Ends func call and sends
tion
data back to the program
Fig. 4.2

Function Calling
call (run)
does not call it. After the def has run, we can
* The def statement only creates a function but
the function by adding parentheses after the function’s name.
Example: For calling a function.
# function definition
>>> def square(x):
return x*x

# function call
>>> square(4)
16
aD

Formal Parameters:
Concept of Actual and
1. ActualP arameteters: nction call are called actual parameters. These are the actual values
* The parameters used in the fu values or
are pas sed to the fun cti on. The actual parameters may be in the form of constant
that
variables. types of formal
parameters must match with the corresponding data
* The data types o f actual
fun ction definition.
parameters (variables) in the
i i function call
3 ea e es that are pass ed to the fun
ction definition through the function call.
ct ua l va lu or global).
ii) Th
ta nt va lu es or va ri ab le names (such as local
i They a be cons

Scanned with CamScanner


Python Functions, Modules and Packages
Programming
with ‘Python’ 4.8

2. Formal Parameters:
function definition are called formal parameters of the
* The parameters used in the hea der of
d to receive values from the calling function.
function. These parameters are use
er.
(i) They are used in the function head :
the function through function call.
values that are passed to
(ii) They are used to receive the function header.
y are trea ted as loca l vari able s of a function in which they are used in the
(iii) The
rs.
Example: For actual and formal paramete
>>> def cube(x): # formal parameters
return x*x*x

>>> result = cube(7) # actual parameters


>>> print(result)
Call by object reference
e Most programming languages have a formal mechanism for determining if a parameter receives a
copy of the argument (call by value) or a reference to the argument (call by name or call by
reference) but Python uses a mechanism, which is known as "Call-by-Object/Call by Object
Reference/Call by Sharing".
Example:
>>> def increment(n):
n=n+1
>>> a=3
>>> increment(3)
>>> print(a)
3
¢ When we pass a to increment (n), the function has the local variable n referred to the same object:

3
I I uN
e eee pr eg =n+1 as integer is immutable, by definition we are not able to modify the
re
object's value to 4 in Dp place: we must cre ate a new object
j i
with i ize
the value 4. We may visualize iti like

e All this time, ! the variable a continues to refer to th - bj i : ;


sisaineteneticns object with the value 3, since we did not change

¢ Wecan still “modify” immutable objects by capturing th e return i


>>> def increment(n): : enna
n=n+1
return n

>>> a=3
>>> a=increment(3)
>>> print(a)
4

Scanned with CamScanner


=
Programming with ‘Python’
4.9 Python Functions, Modules and Packages:
By assigning the return
value “ the function to a, we
with the value 4 created in have reassigned a to refer to the new object
still‘ 3 — but by having
: the
a Bein ¢ unction. Not i initi
e the object a initially referred to never change —=the it is
iticofa. © @ new object created by the function, we are able
to “modify” the
The same increment() function
generates a different result when we passing a mutable object: Here L
is a list which is mutable
>>> def increment(n):
n.append([4])
>>> L=[1,2,3]
>>> increment(L)
>>> print(L)
eeoys; (af)
Here, the statement L = [1,2,3] makes a variable L(box) that points towards the object (1,2,3].
On the functi on being called, a new box n is created. The contents of n are the SAME as the contents
of box L. Both the boxes contain the same object. That is, both the variables point to the
same object in
memory. Hence, any change to the object pointed at by n will also be reflect
ed by the object pointed
at by L.

<§—$—}——

+)

——
nS


n o

Hence the output of the above program will be:


(1, 2, 3, 4]
Advantages of User-Defined Functions:
1. User-defined functions help to decompose a large program into small segments which makes
program easy to understand, maintain and debug.
2. By using functions, we can avoid rewriting same logic/code again and again in a program.
3. We can call python functions any number of times in a program and from any place in a
program.
4. Wecan track a large python program easily when it is divided into multiple functions.
5. Reusability is the main achievement of Python functions.
6. Functions in Python reduces the overall size of the program.
Function Arguments
Many build in functions need arguments to be passed with them. Many build in functions require
two or more arguments. The value of the argument is always assigned to a variable known as
parameter. . :
There are four types of arguments using which can be called are Required arguments, Keyword
arguments, Default arguments, and Variable-length arguments.
Required Arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
Example: For required argument. :
>>> def display(str):
passed as argument
"This print a string
print(str)
return
# required argument
>>> display() _ .

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
nple: For void function.
‘>> def show():
str="hello”
print(str)
‘>> show()
iello
>>

Scope of Variable _ tg *
gram This depend,
On

scope of a variable dete: . nit Can access a Particy);,


ble/identifier.
wailability/accessibility of ferred to as its scons
* are two basic scopesc
mn:
lobal Variables: Global oe E )
s 4
ccessed throughout (outsi *

ody by all functions.


ocal Variables: Local

4.3 shows, global v re in the code, local


ble (z) exists only |
iple: For scope of
>> g=10
>> def show():—
1=20° 0
print("loca!
print("Global
»> show()
1cal variable= 2@
.obal variable= 10

ared outside any

3till the end of the


c ad the enti"

Scanned with CamScanner


: ramming with "Python ee i, YA Python Functions, Modules and Packages
A function is said to be a recursive if jt calls itself. For example, lets say we have a function abc() and
; in the body of abc there is a call to the abc(), = a
Example: For recursive function, i re ae sennl
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)

print(fact(@))
print (fact (4))
print(fact(6))
Output:
1
24
720
« The factorial of4 (denoted as 4!) is 1*2*3*4 = 24,
« Each function call multiples the number with the factorial of number 1 until the number is equal to
one.
fact (4) # Ist call with 4
4 * fact(3) # 2nd call with 3
4 * 3 * fact(2) # 3rd call with 2
4* 3 * 2 * fact(1) # 4th call with 1
pees 2s * 1 # return from 4th call as number=1
a3 * 2 # return from 3rd call
4*6 # return from 2nd call
24 # return from 1st call
¢ Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive
function must have a base condition that stops the recursion or else the function calls itself
infinitely.
Advantages of Recursion:
1. Recursive functions make the code look clean and elegant.
2. Acomplex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion:
1. Sometimes the logic behind recursion is hard to follow through.
2, Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
4. It consumes more storage space because the recursive calls along with variables are stored on the
stack,
5. Itisnot more efficient in terms of speed and execution time.
Example: Programs to convert U.S. dollars to Indian rupees.
def dol rup():
dollars = float(input("Please enter dollars:”))
rupees = dollars * 7@
print("Dollars: ",dollars)
print("Rupees: ",rupees)
def euro_rup():
euro= float (input("Please enter euro:"))
rupees = euro * 79.30
print("Euro: ",euro)
print("Rupees: ",rupees)

Scanned with CamScanner


Functions, Meee eee ae
python

oe ee
ng ‘Python’
Programmiwith
def menu():
print(“1: Doller to Rupees”)
print("2: Euro to Rupees”)
print(*3: Exit”)
your choice: "))
choice=int(input("Enter
if choice==1:
dol_rup()
if choice==2:
euro_rup()
if choice==3:
print("Good bye!")
menu()
Output:
i: Doller to Rupees
2: Euro to Rupees
3: Exit
Enter your choice: 1
Please enter dollars:75
Dollars: 75.8
Rupees: 5258.8

' a oy SS
EE} vovutes Python programming code defining functions,
Modules are primarily the (.py) files which contain is
class, variables, etc. with a suffix ._py appen ded in
its file name. A file containing .py python code
called a module.
we can do editing, correction. This is
If we want to write a longer program, we can use file where several files for
may want to split it into
known as creating a script. As the program gets longer, we
easier maintenance.
We may also want to use a function that we have wr itten in several
programs without copying its
definition into each program.
ce of the
In Python we can put definitions in a file and use them ina script or in an interactive instan
interpreter. Such a file is called a module.
Writing Module
¢ Writing 2 module means simply creating a file which can contains python definitions and
statements. The file name is the module name with the extension .py. To include module ina file,
use import statement.
Follow the following steps to create modules:
1. Create a first file as a python program with extension as .py. This is your module file where we
can write a function which perform some task.
2. Create a second file in the same directory called main file where i
top of the file and call the function. eam eee vote
Second file needs to be in the same directory so that i
it’s not a built-in module. Pyar now whereta find the module since
Example: For creating a module. Type the following code and save it as p1
def add(a, b): men
"This function adds two numbers and return the result"
result = a+b
return result
def sub(a, b):
“This
ee function ES subtract t wo numbers and return the result"

return result

Scanned with CamScanner


with ‘Python’
programming w 4.15 Python Functions, Modules and Packages

def mul(a, b):


"This function multiply two numbers and return the result”
result = a * b
return result
def div(a, b):
"This function divide two numbers and return the result”
result = a/b
return result
import the definitions inside a module:
import p1
print("Addition=" , p1.add(10, 2@))
print("Subtraction=" ,p1.sub(1@,20))
print("Multiplication=" »P1.mu1(10, 20) )
print("division=" ,p1.div(10,2@))
Output:
Addition= 30
Subtraction= -10
Multiplication= 200
division= 9.5

EEE) importing Modules


Import statement is used to imports a specific module by using its name. Import statement creates a
reference to that module in the current namespace. After using import statement we can refer the
things defined in that module.
We can import the definitions inside a module to another module or the interactive interpreter in
Python. We use the import keyword to do this.
Create second file. Let p2.py in same directory where p1.py is created. Write following code in p2.py.
Import the definitions inside a module:
import p1
print(p1.add(10,2@))
print(p1.sub(20,1@))
Output:
30
10
Import the definitions using the interactive interpreter:
>>> import p1
>>> pl.add(10,
20)
30
>>> pl.sub(20,10)
18
>>>
Importing Objects From Module:
.
Import stat python is si milar to #include header_file in C/C++. Python modules can get
t in
een By module by imp orting the file/function using import. Python provides
access to code from another ules.
three different ways to import mod
x
From x import a: ent namespace to all public objects
defined
Imports the module x, and creates references in the curr to things defined
this stateme nt, we can simply use a plain name to refer
by that module. If we run
in module x.
Scanned with CamScanner
; with ‘Python’ 4.17 Python Functions, Modules and Packages
programming = y

Aliasing Modules
It is possible to modify the names of modules and their functions within Python by using
the ‘as’ keyword.
we can make alias because we have already used the same name for something else in the program
or we may want to shorten a longer name.
S tax: import module as another_name
other for
Example: Create a module to define two functions. One to print Fibonacci series and
finding whether the given number is palindrome or not.
step 1: Create anew file p1.py and write the following code in it and save it.
def add(a, b):
"This function adds two numbers and return the result”
result = a+b
return result

def sub(a, b):


"This function subtract two numbers and return the result”
result = a- b
return result

def mul(a, b):


"This function multiply two numbers and return the result”
result = a * b
return result

def div(a, b):


"This function divide two numbers and return the result"
result = a/b
return result
e. Add the following code and save it.
Step 2: Create new file p2.p y to include the modul
import p1 as m
)
print("Addition=" , m.add(10, 20)
20) )
print("Subtraction=" ,m.sub(10,
print("Multiplication=" ,m.mul(1@,2@))
2@))
print("division=" ,m, div(10,
Step 3: Execute p2.py file.
Addition= 398
Subtraction= -10
Multiplication= 200
division= 0.5

Python Built in Modules se, so on. Python interpreter is



Amodule is a collection of Python objects suc h as functions, classes, and ule
is large number of built-in mod s,
bundled with a standard library cons ting of in precom piled
C and bundled with Python interpreter
* Built-in modules are generally written in pt (with .py extension) containing useful utilities.
form, A built-inmodule may be a Pyth on scri or any other Python
e may conta in one or more functions, classes, variables, constants,
* A modul
Tesources. :
) Numeric and Mathematical Modules: -related functions and data types. Foll owin g are the
es num eri c and math
}
This module pro vid
and mathematical modules
d as numeric
Modules which are classifie
s es).
(i) numbers (Numeric abstract base clas
functions).
(ii) math (Mathematical x numbers).
ical functions for comple
(iii) cmath (Mathemat

Scanned with CamScanner


Scanned with CamScanner
q
. hon Functions, Modules ang 5
4.18 o Packs
Programming with 'P hon’ “th
ti )
5 : int arit metic).
(iv) decimal (Decimal fixed point and floating pom
(v) fractions (Rational numbers).
(vi) random (Generate pseudo-random numbers).
(vii) statistics (Mathematical statistics functions). ~ : ath and cmath
eric ric tyP types. Theandm complex Mod
numbe:
The numbers module defines an abstract hierarchy
of vmoating-pomt
Contain various mathematical functions — i. f decimal numbers, using arbitrary Precigic:
The decimal module supports exact representations n
©
arithmetic.
math and cmath Modules:
thandcmath. The math module give,
Python provides two mathematical modules namely
ae ns for real numbers and cmath mog ‘
access to hyperbolic, trigonometric, and logarithmic
vise mbers.
allows us to work with mathematical functions for complex nu =

Example 1; For math module.


>>> import math
>>> math.ceil(1.@@1)
2
>>> from math import *
>>> ceil(1.0@1)
2
>>> floor(1.001)
1
>>> factorial(5)
128
>>> trunc(y115)
1
>>> sin(9@)
@.8939966636005579
>>> cos(6@)
[email protected]
>>> exp(5)
148. 4131591025766
>>> log(16)
2.772588722239781
>>> log(16,2)
4.0
>>> log(16,10)
1.2041199826559246
>>> pow(144,0.5)
12.0
>>> sqrt(144)
1250
>>>
The mathematical functions for complex numbers.
Example 2: For cmath module. VO
S O°3 e
>>> from cmath import *
>>> c=24+2j
>>> exp(c)
(-3.074932320639359+6 . 7188496974285 4)
r >>> log(c,2)
(1.5000008000000002+1. 1339003545679855)
>>> sqrt(c)
(4553775970030 7 418. 662

Scanned with CamScanner


Fe
p ogramming with ‘Python’
4.19 ti
Python FuncModul eson s,
and Packa ges
2 pecimal Module:
; Tecirsals
jmal numbers are jus
a flegers: i :
dates ine sores with fixed decimal points. We can create
A Decimal instance can represent a
number of significant digits. ny number . exactly, round up or down, and apply a limit to the
example : For decimal module.
>>> from decimal import Decimal]
>>> Decimal(121)
Decimal('121')
>>> Decimal(@.@5)
Decimal ( '@ .05800000000000000277555756156289135105907917022705078125"
)
>>> Decimal('@.15')
Decimal('@.15')
>>> Decimal ("@.@12')+Decimal('@.2")
Decimal('@.212')
>>> Decimal(72) /Decimal(7)
Decimal('10. 28571428571428571428571429' )
>>> Decimal(2).sqrt()
Decimal('1 -414213562373095048801688724' )
3, Fractions Module:
« A fraction is a number which Tepresents a whole number being divided into multiple parts. Python
fractions module allows us to manage fractions in our Python programs.
Example: For fractions module,
>>> import fractions
>>> for num, decimal in [(3, 2), (2, 5), (30, 4)]:
fract = fractions.Fraction(num, decimal)
print(fract)
Bie.
2/5
a5 72
* Itis also possible to convert a decimal into a Fractional number. Let’s look at a code snippet:
>>> import fractions
>>> for deci in ['0.6', '2.5', '2.3', ‘4e-1']:
fract = fractions. Fraction(deci)
print(fract)
Output:
3/5
5/2
23/10
2/5
>>>
4. Random Module:
* Sometimes, we want the computer to pick a random number in a given range, pick a random
element from a list etc.
The random module provides functions to perform these types of operations. This function is not
accessible directly, so we need to import ran dom module and then we need to call this function using
—Tandom static object.
Example: For random module.
>>> import random ;
# It genera te a random number in the range (0.8, :
1.8)
>>> print(random.random() )
snneaiaalgel dint(10,20)) # It generate a random integer between x and y inclusive
nt(random. ?
13.

Scanned with CamScanner


Scanned with CamScanner
- progremmina with Python’ 4.21 Python Functions, Module
s and Packages

Output:
C++
python
Java
C++
python
Java
C++
python
Java
>>>

2. nctools Module
>fu :
allows and encourages us to write reusable
python functools module provides us various tools which
code,
functions with some arguments
hon functools partial() functions are used to replicate existing
ocumented manner.
already passed in. It also creats new version of the function in a well-d
ies two numbers. Its definition looks
suppose we have a function called multiplier which just multipl
like:
def multiplier(x, y):
return x * y
or triple a number th en we will have to
Now, if we want to make some dedicated functions to double
define new functions as:
def multiplier(x, y):
return x * y
def doubleIt(x):
return multiplier(x, 2)
def tripleIt(x):
return multiplier(x, 3)
functions? Here, we can use partial functions:
But what happens when we need 1000 such
from functools import partial
def multiplier(x, y):
return x * y
y=2)
double = partial(multiplier,
triple = partial (multiplier, y=3)
print('Double of 2 is {}'. format (double(5)))
print('Triple of 5 is {}'. format (triple(5)))
Output:
Double of 5 is 10
Triple of 5 is 15
Operator Module: tors. These functions
mod ule sup pli es fun ctions that are equivalent to Python’s opera
The ope rat or as arguments, or returned as function
are handy in cases whe re callable s must be stored, passed
Tesi ee table:
are listed in
a supplied by the operator module

abs(a)
abs
add(a,b)
add
and_(a,b)
and
div(a,b)
a. contd.

Scanned with CamScanner


Python Functions, Mod
ules and p,, 4
Programming with ENG
ee a
5 eq
a==b Pp

6. | gt ail gt (a,b)
a>b =
7, invert, inv inv(a) “ta
ry are
invert (a), 3M a<=b --
‘ le(a,b)
a<<b
9, | ishitt a
i hip shift (a,b)
1¢(a,b) a<b
aXb _
11. nod nodta, by ab
=
12, | mul
3 . mul (a,b) a
ne(a,b) al=b
- —
-
14 [neg rege
15, not_ not a .
aa es not_(a)
or (a,b) al
Ib +
oS pos pos(a)
18, | repeat *b +
repeat (a,b)
19, rshift = =|
rshift(a,b)
20. azz ——$——_|
xor_ xor(a,b) cy |
Namespace and Scoping
A namespace is a system to havea unique
name for each and every object in Python.
tains a namespace in the form ofa PythonAn object Might
be a variable or a method. Python itself main
Python interpreter understands what dictionary,
exact method or variable one is tryi
depending upon the namespace, So, ng to point to in the code,
the division of the word itself give
s little more information:
Here, a name might be of any Pyt
hon method or variable and s
where is trying to access a variab
le or a method,
A namespace in python is a
collection of names, So, a nam
to corresponding objects, espace is €ssentially a map
; ping of names
At any instant, different pyt ae
hon namespaces can coexist
that there are noname collision completely isolated- the iso
s/problem. lation ensures
A scope refers to a region of
a program where a namespac
using a namespace prefix, e can be directly accessed,
i.e. without
Scopin g in Pyt
hon revolves around ,
dictionaries containing the names and the concept of na
values of the eke wise ae ‘cally
Types of Name spaces; are basicali
When a user creates a module, a glo
bal names aCe pets
creates the local namespace, The
namespace encompasse loca bu il t- in na Pace
mes a get s create d, later Creation of local functi
os
s l namespace, = €ncomp, asses global namespace and
1, Local Namespace: Thi
s namespace coverg the loc glo ’!
namespac e for every function called ina al n
ames inside a function. Python creates
2. Global Namespace: This nam Progra this
esp
the names from various import ace cov ers Mia Tematng active until the functi
used ed mod ule s on retur™
in a project. Python cre
ates Built-in
namespace for every ami
module included in
the program. It will las
t until the Program
ends.
3. Built-in 7
Namespace; is nam
covers the built-in functions espa
ce '
exception names, and bus
Python
interpreter starts and keepsCreit ate
Untsil itweasexi
thet ia ees
eS elke
oP. ie)
-
eS

Scanned with CamScanner


. rammin with ‘Python’ 4,23 Python Functions, Modules and Packages:

, Namespaces help us uniquely identify all the names inside a program. According to Python's
documentation “a scope is a textual region of a Python program, where a namespace is directly
accessible.” Directly accessible means that when we are looking for an unqualified reference to a
name Python tries to find it in the namespace.
Scopes are determined statically, but actually, during runtime, they are used dynamically. This
means that by inspecting the source code, we can tell what the scope of an object is, but this does not
prevent the software from altering that during runtime.
on Variable Scoping:
. scope is the portion of the program from where a namespace can be accessed directly without any
refix.
: Baise plices are a logical way to organize variable names when a variable inside a function (a local
variable) shares the same name asa va riable outside of the function (a global variable).
- local variables contained within a function (either in the script or within an imported
module) and
global variables can share a name as long as they do not share a namespace,
e Atany given moment, there are at least following three nested scopes;
1. Scope of the current function which has local names.
2, Scope of the module which has global names.
3. Outermost scope which has built-in names.
* Whena reference is made inside a function, the name is searched in the local namespace, then in the
global namespace and finally in the built-in namespace,
* Ifthere is a function inside another function, a new scope is nested inside the local scope. Python has
two scopes.
1. Local Scope Variable: All those variables which are assigned inside a function known as local
scope Variable
2. Global Scope Variable: All those variables which are outside the function termed as global
variable,
Example: For global scope and local scope.
global_var = 30 # global scope
def scope():
local_var = 40 # local scope
print(global_var)
print(local_var)
scope()
print(global_var)
Output:
38
48
3

E24 evruon PACKAGES


* Suppose we have developed a very large application that includes many modules. As the
Modules grows, it becomes number of
difficult to keep track of them all as they have similar names or
functionality.
It is necessary to group and organize them by some mean
which can be achieved by packages.
Introduction
a A Package is a hierarchical file directory structure that defines a single Python application
, -Xvironment that consists of modules and subpackages and sub-subpackages and so on.
- Packages allow for a hierarchical structuring of the module namespace using dot notation, Packages
a Way of structuring many packages and modules which help in a well-organized hierarch
y of
“ata set, making the directories and modules easy to access,
A Package is a collection of Python modules, i.e. a package is a directory of Python modules
‘ontaining an additional __init__.py file (For example: Phone/__init__.py).

Scanned with CamScanner


Scanned with CamScanner
with ‘Python’ 4.25 _Python Functions, Modules and Packages

jt extends the capabilities of NumPy with further useful functions for minimization, regression,
Fourier-transformation and many others.
a Both NumPy and SciPy are not part of a basic Python installation. They have to be installed after the
python installation. NumPy has to be installed before installing SciPy.
Math
some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions and angle conversion
functions.
» Two mathematical constants are also defined in math module.
« Pie (x) is a well-known mathematical constant, which is defined as the ratio of the circumference to
_ thediameter of a circle and its value is 3.141592653589793.
mm >>> import math
é >>> math.pi
3.141592653589793
cc >>>
«+ Another well-known mathematical constant defined in the math module is e. It is called Euler's
__ number and it is a base of the natural logarithm. Its value is 2.718281828459045.
>>> import math
>>> math.e
2.718281828459045
>>>

Different mathematical functions of Math module already explained in Section 4.1.2.


NumPy
_NumPy is the fundamental package for scientific computing with Python. NumPy stands for
"Numerical Python". It provides a high-performance multidimensional array object, and tools for
working with these arrays.
An array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive
integers and represented by a single variable. NumPy’s array class is called ndarray. It is also known
by the alias array.
In NumPy arrays, the individual data items are called elements. All elements of an array should be of
_ the same type. Arrays can be made up of any number of dimensions.
In NumPy, dimensions are called axes. Each dimension of an array has a length which is the total
number of elements in that direction.
» The size of an array is the total number of elements contained in an array in all the dimension. The
size of NumPy arrays are fixed; once created it cannot be changed again.
Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays
are that they are fast, easy to work with, and give users the opportunity to perform calculations
across entire arrays.
Fig. 4.6 shows the axes (or dimensions) and lengths of two example arrays; (a) is a one-dimensional
ay and (b) is a two-dimensional array.
\

sa
=3

4 Cc 1

" ae
[sé] 2 i {> 2 3 aes
2?
5| Columns
0 Axis-1

(a) (b)
Fig. 4.6: Dimensions of NumPy Array

Scanned with CamScanner


ing with ‘Python’
nin 4.27
. Python Functions, Modules and Packages

y Operations:
py, arrays allow a wide range of operations which can be performed on a particular array or 2
pination of Arrays.
n as well as Unary and Binary
operations include some basic mathematical operatio
ified.
ations. In case of +=, -=, “= operators, the existing array is mod class. This
Many unary operations are provided as a method of ndarray
4. Unary Operators:
be applied row-wise or column-wise by
- jncludes sum, min, max, etc. These functions can also
setting an axis parameter.
mentwise and a new array is created. You
, Binary Operators: These operations apply on array ele ting
s like +, -, /, , etc. In case of +=, -=, = operators, the exis
“aan use all basic arithmetic operator
yed.
aifi
arisrmod
xample: For basic array operators.
>>> arri=np.array([1,2,3,4,5])
>>> arr2=np.array([2,3,4,5,6])
>>> print(arr1)
~1 2345)
>>> print("add 1 in each element:",arr1+1)
add 1 in each element: [2345 6]
each element: ", arri-1)
>>> print("subtract 1 from
tract 1 from each element: [@ 1 2 3 4]
with each element in array: ",arr1*10)
> print("multiply 10
multiply 10 with each element in array: [10 20 3@ 40 58]
",arr1.sum())
>>> print("sum of all array elements:
sum of all array elements: 15
)
print("array sum=:", arri+arr2
array sum=: [3 5 7 9 11]
array: " arri.max())
>> print("Largest element in
sest element in array: 5

of Array:
using sto 10
_also perform reshape operation
you 1 12 “73|
numpy operation. Reshape is when
col umn s aa
the number of rows and
es a new view to an object.

penp.array([[1,2,3],[4,56]])
a=arr.reshape(3,2)

array([[1, 2],
a ifs; 4),
_{5, 6]])
ay:
ements from an array. Consider
an array
pa rt ic ul ar set of el
basically extracting
2
»6,7,8)]). i s at ind ex 1 of the pyt hon numpy array. We need
dex 0 and (3,4,5,6)
array (1,2,3,4) is at in
t of a given array:
r element (say 3) ou

ke ee

Scanned with CamScanner


a. OD P ay ¥

Lee STM Pg

* Let us cons
the id
below exam
er ple:
>>> import numpy a5 np
>>> a=np.array([(1,2,3,4),
>>> print(a[@,2]) Tt le code will
4 ; be a. foll-
4 Ws
* Now we need the 2” element from the 26
import numpy as np
a=np.array([(1,2,3,4), (5,6, y
print(a(@:,2])
ta | eld
[3 7]
* Here, colon represent
all the
s rows, inclu
Array Manipulation Functions: nts in ndarray Object
Several routines are available in Numl
They can be classifie
into the
d foll *

without changing its dar,


reshape :
flat Be
ypsed into one dimension
flatten
ravel

transpose a wf P
ndarray.T 7 T
| + a

rollaxis

horizonta!Y
gays vertically (*"
contd
Scanned with CamScanner
Scanned with CamScanner
Pree

|
a
1

|
a
:
:
:

|
=

\
|
-

|
“a
rt

Scanned with CamScanner


Scanned with CamScanner
2.2.6,
sch objects»)
.

Scanned with CamScanner


g with ‘Python’ Python Functions, Modules and Packages.

© ees
owa Se oe |S

SWE Pandas
pandas is an open-source Python Library providing high-performance data manipulation and
analysis tool using its powerful data structures.
Tt is built on the Numpy package and its key data structure is called the DataFrame. DataFrames
allow you to store and manipulate tabular data in rows of observations and columns of variables.
Rain: Pandas:
_ pip install pandas
structures supported by Pandas:
Pandas deals with the following three data structures:
_ Data Structure Dimensions Description
a 1D labeled homogeneous array, size immutable.
Data Frames 2 General 2D labeled, size-mutable tabular structure
with potentially heterogeneously typed columns.
Panel 3 General 3D labeled, size-mutable array.

ies is a one-dimensional array like structure with homogeneous data. The Series is a one
ensional array which is Labelled and it is capable of holding array of any type like Integer, Float,
String and Python Objects.
For example, the following series is a collection of integers 10, 22, 30, 40,... The syntax is as follows:
Pandas.Series(data, index, dtype, copy)
Tt takes four arguments:
data: It is the array that needs to be passed so as to convert it into a series. This can be Python
lists, NumPy Array or a Python Dictionary or Constants.
index; This holds the index values for each element passed in data. If it is not specified, default
_ isnumpy.arange(length_of_data).
» dtype: It is the datatype of the data passed in the method.
* Copy: It takes a Boolean value specifying whether or not to copy the data. If not specified, default
is false,
sre data is only mandatory argument of Series.
“ample 1; Using Series data structure of Panda.
°?> import pandas as pd
?>> import numpy as np
*?? numpy_arr = array(
[2, 4, 6, 8, 10, 20])
>>> si = pd.s eries(arr)
?>> Print(si)

Scanned with CamScanner


Scanned with CamScanner
Scanned with CamScanner
ot

un

is package is
as a package.

.
ctior
fur wy

Scanned with CamScanner


ng with ‘Python’ 447 sR thon Functions, Modules and P es

anecified functions can now be imported in the interpreter session or another executable script.
te test. py in the MyPkg folder and write following code:

_ myPkg import power, average, SayHello


gayte110()
xapower(3,2)
print("power(3,2) 4 7 x)
te that functions power() and SayHello() are imported from the package and not from their
yective modules, as done earlier, The output of above script is:
Jello world
r(3,2) : 9

ice Questions

is function?
What is module?
What is package?
Define function, Write syntax to define function. Give example of function definition.
Can a Python function return multiple values? If yes, how it works?
How function is defined and called in Python.
about void functions with suitable examples.
ig actual and formal parameter? Explain the difference along with example.
in about fruitful functions with suitable examples.
6 the difference between local and global variable.
‘in any five basic operations performed on string,
math module with its any five functions.
’Nfferentiate between match() and search() function. Explain with example.
type conversion of variable in Python.
a function that takes single character and prints ‘character is vowel’ if it is vowel,
r is not vowel’ otherwise.
pI ain various string operations that can be performed using operators in Python.
“plain with an example, how + and * operators work with strings.
xplain str.find() function with suitable example.
fine is module? What are the advantages of using module?
w to create a module and use it in a python program explain with an example.
plain various functions of math module.
ist and explain any four built in string manipulation functions supported by Python.
lain string slicing in Pyhton. Show with example.
plain the concept of namespaces with an example.
rite about the concept of scope of a variable in a function.

Scanned with CamScanner


ste classes and objects to solve the given problem.
ite Python code for data hiding for the given problem.
ite Python code using data abstraction for the given problem.
rite Python program using Inheritance for the given problem.

eating Classes and Objects in Python


Data Abstraction, Inheritance etc.
Method Overloading, Method Overriding, Data Hiding,

age (OOPL) follows an Object-Oriented


om is an Obj ect-Oriented Programming Langu lays the
) par adi gm. It dea ls wit h dec laring Python classes and objects which
amming (OOP
on of OOPs concepts. an easy way to develop programs.
e programming and pr ovides
programming offers OOP styl more powerful to help design a
jon programming uses the OOPs concepts that makes Python
ties.
that represents real-world enti Met hod overriding, Data abstracti
on and
ts suc h as Inh eri tan ce,
_also supports OOP concep
hiding.
of OOP:
fant terms in OOP/Terminology clas s pro vid es the basic structure for an: object.
It
by the user. T he of the
lass: Classes are defined me mb er s tha t are use d by the instances, (objects)
and meth od
consists of data members
mprises
class.
that is defined by its class. An object co
of a data structure and methods. Class itself
does
Object: A unique instance instance variables) instance or
(class variables and theiri objects.
j Object
ject isi an ins
‘both data members ity 1si achieved
i through (methods)
but i
the real functionality and uses the behavior
nothing es F the properties
(variables)
‘occurren ance of the class. It tak
with
defined in the class. an obj ect ; it ho lds the data associated
her a class or
Dat a Me mb er : A var iable defined in eit
- thin the object
that
cla ss or obj ect . sco p e is on ly wi
b the d in a method; it
Var iab le: A var iable that is define
Instance at
e instances of th
defines it. class and can be us ed by all th
iab le; A var iab le that is defined in the
‘Class Var
Class. [5.1]

Scanned with CamScanner


amming with

6. Instan
An objec
cet:is
7. Instantiatio
Then:
proc
8. Method: Methods are the f
and are Used ;
various instances of the cl 7
; 1 different behavion,
9. Function oresiont ee Beer
known as function overlo:
Of objec,
arguments involved,
s and data Varia),
10, Encapsulation: Encapsula
as a single entity i.e,, class. 2 safe from the o,,..°
n the method e
world. It hides the data with
that are derives »
11. Inheritance: The transfer of thect
it
A class
. ‘A’ that can use the ) be derived clas. te ‘
char
class inherited from B. This process is cal ed inl ma
12. Polymorphism: Polymorphism allows one =
i ra set of actions i.e, one...
int e al having many , i
may refer to different functionality. The | v0) ut different signatures) bei, ohn
programming, polymorphism means same f a & Uses
for different types. aa . -
13. Data Abstraction: The basic idea of data abstractio: ible only ee mecessary informatio,
unnecessary information will be hidden from eeemerraction is a process 4
hiding the implementation details and showing o1 lity to the user. Another way, i
shows only essential things to the user and. hides the internal details, for example, sending SMS
where we type the text and send the message. We don't know ne internal processing about t;
message delivery. ee cam!
by "} LASSE i me re Vee Ree Z TS
ri
Python is an object oriented programming language. Almos everything in
its properties and method
Python is an object, y:::
s. *
Object is simply a collection of data (variables) and meth
ods (functions) that act on those data.
A class is like an object constructor or a “blueprint” for creating objects. A class
defines the propert'=
and behavior (variables and methods) that is shared '
by all its o bjects,
Creating Classes
A class is a block of statements that combine data and operations, which are
into a group as a single unit and acts a bluep performed on the dat:
rint for the creation of objects.
To create a class, use the keyword ‘class’, Here’
s the very basic structure of python class defin
Syntax:
ition
class ClassName:
‘Optional class documentation string’
# list of python class variables
# python class constructor
# python class method definitions
Following is an example of creati
on of an empty class:
class Car:
Pass
Here, the pass statement is
used to indicate that this
class is e mpt
In a class we can define var
iables, ; functions , tc. y,
atleast one argume Whilei writi ion i
nt that is called self Par
ame
ter, eae
have 0°oF
The self parameter is a ref emma #0 2°
erence to the class j tself
ss. It does not have to be named self, we can ane i whuse
cla atd to a access S variab
yari les that bellon
onggss ' |
parameter of any function in the
class. sver We like, but ft has to be

Scanned with CamScanner


it ‘ 'Pyth
5.3 Object Oriented Programming in Python
rite a class on interactive interp
reter or ina py file
tive Interpreter:

student:
. “display (self):
# defining method in class
_print("Hello Python")

£ display(self): # defining method in class


print("Hello Python")
2 er coe a is a default variable that contains the memory address of the instance
PU : n use self to refer to all the instance variables and instance methods.
ects and Creating Objects
ct is an instance of a class that has some attributes and behavior.
; can be used to access the attributes of the class.
obj_name=class_name()
le:
-student ()
display ()
e program with class and objects on interactive interpreter is given below:
iss student:
def display(self): # defining method in class
print ("Hello Python")
=student() # creating object of class
# calling method of class using object

w:
ractive interpreter in .py file is given belo
e program with class and objects on inte
lass student:
def display(self):
~ print( "Hello Python")

o Python
.: Class with get and put method.
Class Car:
def get(self, color, style):
self.color = color
-self.style = style
def put(self):
| print(self.color)
print(self.style)
¢ = Car()
‘©-get('Sedan’, "Black')
¢-put()

Scanned with CamScanner


iP

ited Programming

t integrity by

may not be visible


am
:

es then are not


| private variable

Scanned with CamScanner


|
5.5
Object Oriented Pro ramming
ea in Python
TION AND DATA ABSTRACTION
. é ae x

tric
Bit cr
accaess bei
ofngmet hod
moc s sandevar
ine aiab
eles
in a class witi h the help
of encapsulatioi n. It will
on is used to hide the values or state of a struc
tu redd ne
zed parti er
es’ direct access to them. i :
ata object inside a class, Preventing
wt
ra
"
on refers to providing
j
. .

only essential informatio n abo


background details or implement ut the data to the outs
ation.
s encapsulation and abstracti Bey
on (data hiding) are often use
through encapsulatio d as synonyms. Data abstraction
n.
tio is a process: to bind data and fun
cti ons together into a single unit ice.,
is oeeooes in which the data class while
inside the class is the hidden from
he sensitive information. the outs ide world,
: iding internal details and showing func
tionality is known as data abstraction.
art encapsulation, declare the methods
or variables as private in the class. The
; cannot be called by private
the object directly. It can be called only from
within the class in which
defined.
ction prefix with double underscore is calle
d private method which is accessible only with
2 it is declared.
\g table shows the access modifiers for variables
and methods:
1

Description
-ublic methods Accessible from anywhere i.e. inside the class in which they are
defined, in the sub class, in the same script file as well as
outside the
. script file.
; ‘Private methods Accessible only in their own class. Starts with two underscores.
| Public variables Accessible from anywhere.
| Private variables Accessible only in their own class or by a method if defined. Starts with
| two underscores.
je: For access modifiers with data abstraction.
ss student:
— _a=10 #private variable
b=28 #public variable
def _ _private_method(self): #private method
print("private method is called")
def public method(self): #public method
print("public method is called”)
print("a=",self._ _a) #can be accessible in same class
=Student ()
Print("a=",s1._ _a) #generate error
rint("b=",s1.b)
Si._ _private_method() #generate error
--Public_method()

€ method is called

Scanned with CamScanner


for a class. In the

gth and width. T

Scanned with CamScanner


5.7 Object Oriented Programming in Python

le class and intialize it witwi h


;
. create a Cric
: radius. Make two methods getArea and
ce inside this class.
rcle():
weinit_ _(self,radius):
elf.radius = radius

Area", c.getArea())
circumference",c.getCircumference())

8.5

Constructor: n
h s not accept any arguments. It’s definitio
ult constructor is simple constructor whic doe
one argument which is a reference to the instance being constructed.
r.
: Display Hello message using default constructo
Student:
def _ _init_ _(self):
parametrized constructor")
ah print("This is non
def show(self,name):
print ("Hello”, name)
Student()
how("Meenakshi ")

ects of a class.
: Counting the number of obj
;s Student:
— count=0;
def _ _init_ _(self):
t.count+1
Student .count=Stud en
tudent()
=Student() nt)
of student 0 pjects” Student . cou
nt("The number
t:
:
student objects: 2
number of

terized Constructor: rameterized constr


uctor. being
te rs i s kn ow n as pa to the instance
ructor with parame gument as a re fe re nc e
ed co ns tr uc to r t ake its first ar pr ov ided by the progra
mmer.
amet er iz gu me nt s ar e
the rest © f the ar
cted known as self and
uctor.
le: For parameterized constr
class Student: :
def _init_ _(self,name):
constructor”)
print("This is parametrized
self.name = name

EE TEE
Scanned with CamScanner
1 using dot operator

pt y. It displays them

f the docstring isn't

Generally the

Scanned with CamScanner


5.9 Object Oriented Programming in Python

is a class called Test.

ain. —
“lass ‘object'>,)
main Di) | ; Test.',
ap+_ ule_ _
__module
_': 2
aaa
'
ldo Ce ab ehus (1S, a sample, class called
ree _init_ _ at @x@13AC618>, ‘'_ _dict_ _': <attribute
rt She ead en we ref_
1 ‘'_ _weak ; of
4 objects>, '_ _weakref. _— ‘ <attributee _'
eee
it Spaects>}

OD OVERLOADING
od overloading is the ability to define the method with the same name but with a different
per of arguments and data types.
arguments or
this ability one method can perform different tasks, depending on the number of
as of the arguments given.
operations according to the
athod overloading is a concept in which a method in a class performs
eters passed to it. with
a program having two methods aith same name but
other languages we can write
if we will try to do the same we
nt number of arguments or order of arguments but in python
the following issue with method overloading in Python:
o calculate area of rectangle
det area(length, breadth):
calc = length * breadth
print calc
# to calculate area of square
def area(size): ©
calc = size * size
_ print calc
area(3)
a(4,5)

exactly 1 argument (2 given)


-TypeError: area() takes
one method
i.e., it is not possible to define more than
on does not support method overloading,
e same name in a class in Python. one argument
use meth od argu ment s in pyt hon do not have a type. A method accepting
beca
a double as shown in next example.
e called with an integer value, a strin gor
Class Demo:
def method(self, a):
7 print(a)
Obj= Demo()
«method ( 50)
-method('Meenakshi')
-method([email protected])

Scanned with CamScanner


ing classby si?!

Scanned with CamScanner


ted Proa:
d Programming in (tO

ertie
bm s of objects of anot
her class, 7 inheritsAnICe
w features can be added to the code
while
sing or constructing classes from other classes js

ae class and the class from which this derived class has
acqgull es the properties and can access all the data members and
t class, A child class can also provide its specific irnplermentation +,

Base Class Class

Derived Class Clase


AaBSS

@
- .

B inheriting property of class A


- Fig. 5.1: Concept of Inheritance
properties of class B (Single Inheritance)
eritance without using constructor.
e: #parent class
uti"
play(self):
print("Name= ",self.name)
ass Category(Vehicle): #derived class
e=2000
def disp_price(self):
print("Price=$",self.price)
1=Category()
ar1.display()
‘cari.disp_price()
Dutput:
Name= Maruti
Price=$ 2000 —

ample 2: Inheritance using constructor.


class Vehicle: #parent class
def _init_ _(self,name):
self.name=name
def display(self):
print("Name= " self.name)
#derived class
class Category(Vehicle):
def init__(self,name,price): class constructor
Vehicle. init__(self, name) # pass ing data to base
self.price=price
def disp price(self):
print("Price=$ " self.price)
cari=Category( "Maruti", 2000)
Car1.display()
Carl.disp_price()

Car2=Category( "BMW" , 5000)


Car2.display()
Car2.disp price()

Scanned with CamScanner


5.1 1 Object Oriented Programming in Python

ance objects
Mi of one class procure the properties of obj jects of another class. Inherit
ie reusability, which means that some of the new features can be added to the iy sits
sisting
ice. code. The mechanism of designing or constructing classes from other classes>S 15a

ss is called derived class or child class and the class from which this derived class has
js the base class or parent class.
ce, the child class acquires the properties and can access all the data members and
lefined in the parent class. A child class can also provide its specific implementation to
of the parent class.
Base Class
Ss “3
+ properties of class A
ass B(A): Derived Class Class B
of class A
#F class : ing Ser property
B inherit ORSinty Fig. 5.1: Concept of Inheritance
# more properties of class B (Single Inheritance)

le 1; Inheritance without using constructor.


s Vehicle: #parent class
name="Maruti"
def display(self):
print(“Name= " self.name)
#derived class
lass Category(Vehicle):
price=2000
def disp_price(self):
print("Price=$",self.price)
i=Category()
display()
disp_price()

Maruti
ice=$ 2000
2: Inheritance using constructor.
ass Vehicle: #parent class
def _ _init_ _(self,name):
self.name=name
def display(self):
print ("Name= " self.name)
#derived class
ss Category(Vehicle):
:
def _init__(self,name,price) e class constructor
_(s elf ,na me ) # passing data to bas
= Vehicle, _init_
self .price=price
def disp_price(self):
print("Price=$ " self.price)
:
ard=Category("Maruti" , 2000)
1.display()
-disp_price()
=Category("BMW" , 5020)
-display()
r2.disp_price()

Scanned with CamScanner


Scanned with CamScanner
ls a ee” a ee

- .
jith ‘Python
,
5.13 Object Oriented Programming in Python

» functions of class A
B:
# variable of class A
# functions of class A
a c(A, B):
class C inheriting property of both classA and B
# add_more properties to class C
ass [ Base Class 2 | [ Base Class 3 | | ClassA Class B
4

Derived Class | _ Class C

(a) (b)
Fig. 5.3

class
Father:
def display1(self):
_ print("Father")
e class
Mother:
lef display2(self):
7 print("Mother”)
ved class
- Son(Father, Mother):
_display3(self):
print("Son")

nheritance: m a
classes are cre ated fro
nore than one derived
hierarchical inheritance.
ase - it is called me
parent (base) class na
‘program, we have a Gmail and
two child (de rived) classes named

e: For hierarchical inheritance.


Ss Email:
def send_email(self, msg):
print()
ISS Gmail(Email):
lef send_email(self, msg): )
1". format(msg)
print( "Sending ~{}° from Gmai

Scanned with CamScanner


4

ided by one os its

1€ Name and same

lows you to call that


Bey;
fae |

Scanned with CamScanner


SESE

515 ——Qiject Oriented Progra


mming in Python

. on, we do not inherit from the


base class but establish
a ips between classes through Composite
the use of instance variables
seferences to other objects.
jon also reflects the relationship 4
s between parts, called a
tionships. Some OOP design texts refe on
io r to composition as

|
s creating complex types by combining objects of other types.
eans that a class Composite can contain an Gomponalll
object of another
r ponent.

. nts composition as shown in Fig. 5.5


Fig. 5.5

ine some attributes and met


hods
ASpecificClass:
ance_variable of —Seneric_
class=GenericClass
use this instance somewhere
in the class
si e_method(Instance_var
iable of 6eneric_class)
win Program, we have three classes Email,
Gmail and yahoo. In email Clas
and using the concept of Compositi s we are referring
on.
pie: For composition.

Print("Sending “{}° from Gmail” . format (msg) )

send_email(self,
msg):
_ ~print( "Sending ~{}° from Yahoo” . format(msg) )
SS Email:
Pro ider=Gmail()
def set—Provider(se
lf, provider):
__Self.provider=
provider
we send_email(self,
msg):
Self provider. send_e
mail(msg)
ni 1 = Email)
-*S€nd_email("Hell
o! ao
*-Set_provider(Yahoo
() )
> *S€n d_email (Hello!)
“Hello!- from Gmail
—& Hello! from Yahoo

Scanned with CamScanner


‘4
Programming with 'Python' wie Object Or iented Program amIng In Py,

In Python, every time we use an expression of the form obj


top, beginning with object, look;
class object), Python searches the namespace tree from bottom to I
for the first attr it can find.
in ;,. ,
* This includes references to self attributes in the mente ak ause lower definitions
override higher ones, inheritance forms the basis of specialization. :
* Program code in Fig. 5.6 create a tree of objects in rr to be searched cr tance
Calling a class creates a new instance that remembers its class, running a Class statement creq,,.
new class and superclasses are listed in parentheses in the class statement header.
Each attribute reference triggers a new bottom - up tree search - even references to self attriby;,,
within a class's methods.

S'
ef attr(self,....):
-self.attr = V

| Instance —

object.attr?

Fig. 5.6
e Fig.5.6 summarizes the way namespace trees are constructed and populated with names. Generally:
1. Instance attributes are generated by assignments to self attributes in methods.
2. Class attributes are created by statements (assignments) in class statements.
3. Superclass links are made by listing classes in parentheses in a class statement header.
e The net result is a tree of attribute namespaces that leads from an instance, to the class it was
generated from, to all the superclasses listed in the class header.
e Python searches upward in this tree, from instances to superclasses, each time we use qualification
to fetch an attribute name from an instance object.
Specializing Inherited Methods:
¢ The tree-searching model of inheritance just described turns out to be a great way to specialize
systems. Because inheritance finds names in derived classes before it checks base classes, derive
classes can replace default behavior by redefining their base classes’ attributes.
In fact, we can build entire systems as hierarchies of classes, which are extende d by adding new
* The idea of redefin'"
existing logic in-place.
external derived classes rather than changing
inherited names leads to a variety of specialization techniques.
e For instance, derived classes may replace inherited attributes completely, provide attributes that 3
class fro™ an
base class expects to find, and extend base class methods by calling back to the base
overridden method. Here is an example that shows how extension works. a

Example : For specialized inherited methods.


A: # parent class
class
"Parent Class”
def display(self):
print (‘This is base class.')

Scanned with CamScanner


5.17 Object Oriented Programming in Python

: # derived cl
oe
/Derived class”
: display(self):
a.display(self)
(‘This is derived class.')
# instance of child
— # child calls overridden method
O
; : ac
a ES ces Sas :deo function with its own specialized version, but within
erived calls © the version exported by base class to carry out the default

base class.display() behavior, rather than


ords, derived class.display() just extends
5 it completely.
h a superclass.
n is only one way to interface wit techniques:
that illustrate a variety of common
gprogram defines multiple classes
on Super
super: Defines a method functi
and a delegate that expects an | |
Ke
action in a subclass. Provider
Replacer Extender
any | Inheritor
Inheritor: Doesn’t provide
hing — ,
new names, sO it gets everyt Fig. 5.7
defined in Super.
Ov er ri de s Sup er’ s me th od with a version of its own. run the default.
senlacer: ov er ri ding and calling back to
Super’ s me th od by
Extender: Customizes od ex pe ct ed by Super’s delegate method
.
the action me th
Provider: Implements superclass.
the va ri ou s wa ys to customize a common
le: Give a feel for
ss Super:
def method(self): # Default behavior
.method' )
print(‘in Super
lef delegate(self): # Expected to be defined
self.action() method verbatim
# Inherit
er):
ass Inheritor (Sup
method completely
pass # Replace
ass Replacer(Super):
def method(self):
er- method’ )
print(‘in Replac # Extend method behavior
er):
ass Extender(Sup
:
def method(self)
elf)
super.method(s
tender-method'
) ired method
print(‘in ex # Fill in a requ
):
ass Provider(Super
:
jef action(self) )
print(‘in Provider .@ ction’
F extender):
acer,
eritor, Repl
klass in (Inh + "...")
ass-_ _name__
print(*\n" + kl
klass() -method()
)
print (*\nProvider.--'
= Provider)

. Scanned with CamScanner


ul
un lent as usual,
ance search of
d is located in the
[ris

lass — a class that

Scanned with CamScanner


File 1/o Hand
ling ang
: Exc eption Hand
Regi ling
tcomes...
2
Nrite Python code for
the given readin 8
values from keyb
Rea
d data from the given file.
ee
e the given data toa file.
dandle the given exceptions through
Python program.
me

gp Objectives...
derstand File, I/O and Exceptio
n
‘0 study I/O Operations like
Reading Input, Printing Out
put etc.
To learn File Handling Concepts
such as Opening, Reading, Writin
g, Renaming, Deleting,
rile Contents etc. Accessing
0 study Directories in Python, File
and Directory related Standard Fun
ctions
fo understand Exception Handling in Pyth
on Programming

isa collection of related data that acts as a container of


storage as data permanently. The file
g refers to a process in whicha program processes and accesses
data stored in files.
a computer resource used for recording data ina computer storage device
. The processing on
4s performed using read/write operations performed by programs.
on supports file handling and allows users to handle files i.e., to read and write files, along with
y other file handling options, to operate on files.
Programming provides modules with functions that enable us to manipulate text files and
€s. Python allows us to create files, update their contents and also delete files.
file is a file that stores information in the term of a sequence of characters (textual
on), while a binary file stores data in the form of bits (Os and 1s) and used to store
nation in the form of text, images, audios, videos etc.

— ATIONS (READING KEYBOARD INPUT, PRINTING TO SCREEN)


Y Programming language an interface plays a very important role. It takes data from the u ser
t) and displays the output. a, alues to the
of the essential operations performed in Python language is to ae
‘am and output the data produce d by the program toa standard outpu veen provided to te
utput generated is always dependent on the input venice ee
fam. The input can be provided to the program statically and dyn
[6.1]

_<cal
Scanned with CamScanner
62 File VO Handling and Exce,y),.lo
Frogremming with ‘Python’
In static input, the raw data does
not change in every run aa
the raw data has a tendency to cha .
nge in every run of the program.
Python language has predefined fun
Input can also be provided directly ctions for reading oe ioe i. : b
in the program by assigning Se
language provides numerous buil a
t in functions that are readily ava
Some of the functions like inpu ilable to us at Python p
t() and print() are widely used
operations, respectively, |
Output (Printing to Scr
een):
The function print() is used to output data to the
output can redirect or store
standard output devices i.e., monitoi r/s |
on to a file also.
The message can be a string, or any othe
r object, the object will be converted into
written to the screen. a st
Syntax: print (object(s), Separator=separator, end=end, file-file, flush-f1\
Parameter Values:

(i) object(s): It can be any object but will be converted to string before printed.
(ii) sep='separator': Optional. Specify how to separate the objects, if there is more tl
Slee
(iii) end='end': Optional, Specify what to print at the end. Defaul
t is '\n' (line feed).
(iv) file: Optional. An object with a write method. Default
is sys.stdout.
(v) flush: Optional. a Boolean, specifying if the output is flushe
d (True) or buffere
is False.
Example: For output using print().
>>> print("Hello", “how are you?", sep=" ---")
Hello ---how are you?
>>> print(10,20,30,sep='-')
10-26-30
To make the output more attractive formattin g is used.
This can be done by using the st
method.
Example: For output using format(). —---
>>> a=10
>>> b=20
>>> print('Value of a is {} and b is {}' .format(a,b))
Value of a is 10 and b is 20
>>> print('I will visit {@} and {1} in summer" format (*Jammu',*Kashmir')
I will visit Jammu and Kashmir in summer
>>>

Just like old sprint() style used in C programming language, we can ee che |
language also. The % operator is used to accomplish this, ‘
Example: For output with %.
>>> x=12.3456789
>>> print('The value of x=%3.2f'%x)
The value of x=12.35
>>> print('The value of x=%3.4f'%x)

ss ae
The value of x=12.3457_

a Je 7
6.3 File VO Hand and
symbols available in Python programming are:
r Conversion
%oc Character,
%s String conversion via str() prior to formatting.
i Signed decimal integer.
%d Signed decimal integer.
Au Unsigned decimal integer.
%O Octal integer.
%X Hexadecimal integer (lowercase letters).
%K Hexadecimal integer (UPPERcase letters).
Ke Exponential notation (with lowercase 'e’).
%E Exponential notation (with UPPERcase'E’).
%E Floating point real number.

8 The shorter of %f and %e.


%G The shorter of %f and %E.
Input):
input, which by default
two built-in functions to read a line of text from standard
keyboard.
one argument. The syntax is
The input(prompt) function allows user input. It takes

(prompt)
before the input.
is a String, representing a default message
r input (prompt) method.
t(’Enter your name:')
m+ xX)

name: vijay
vijay data.
alw ays eva lua te the inpu t pro vided by user and return same type
function input()
as follows:
return
its ret urn int ege r valu e. If inpu t value is string type then its
, eger type then
e is int

reading input from keyboard.


()

input())

Scanned with CamScanner


Programming with ‘Python’ _$4
5
>>> type(x)
<class ‘int'>
>>> x=float (input())
2.5
>>> type(x)
<class 'float'>
eG... ey
Pee ean See
ee ee ,
Wwe tite
It is us ed to pe rm anently store dats \,,
* File is a named location on disk to store related info rmation,
non-volatile memory, (e.g. hard disk). uter f‘is turned orp,
Op
* Since, Random Access Memory (RAM) is volatile which loses its data when comp
we use files for future use of the data, I
* Files are divided into following two categories:
1. Text Files: Text files are simple texts in human readable forma t
A text file is rcstructured »,
sequence of lines of text. r
2. BinaryFiles: Binary files have binary data (0s and 18) which is understood by the c omputer,
are done, it needs to
* When we want to read from or write to a file we need to open it first. When we
be closed, so that resources that are tied with the file are freed, y
* Hence, in Python a file operation takes place in the following order:
o Opena file.
o Read or write (perform operation).
o Close the file.
Opening File in different Modes
* All files in Python programming are required to be open before some operation (read or write) can
performed on the file. In Python programming while opening a file, file object is «
using this file object we can perform different set as operations on the opened file.
¢ Python has a built-in function open() to open a file. This function returns a file object also called a
handle, as it is used to read or modify the file accordingly. ms .
Syntax: file object = open(file_name [, access mode][, buffering]) ee
»
Parameters:
file that we want
file_name: The file_name argument is a string value that contains the name ofthe |
to access.
to be open ed, ie, read,
access_mode: The access_mode determines the mode in which the file has
access mode is rea d( .)
write, append, etc. This is optional parameter and the default file
buffering: If the buffering value is set to 0, no buffering takes place, If the buf fering value is 1, line
buffering is performed while accessing a file. If we specify the buffering value as an integer greatel
size. If n egative, the buffer size
than 1, then buffering action is performed with the indicated buffer .
is the system default (default behavior),
provide the Rie fist tike in the following
¢ Ifthe path isin current working directory, we can just , ‘a
examples:
>>> file=open("sample.txt")
>>> file. read()
‘Hello I am there\n’ # content of file
22
a
os. listdir() # display file and folder
ee > clude", Lab"' ) Libs”, "LICENSE ao .t
! ‘p2.py', ‘python.exe' Python3.d11' ' mMypke’, '
2. ae ‘tcl’, co Python37.d1]' NEWS txt?
}
i txt,
_
7
scripts’, ‘share’,
‘te tae ' ' . Pyth
St.py', Tools i
‘ ‘Veruntinetag sae

: Mic
le reside o:a2 direct
s in \iit oryes\\ smne
other than ce
Pwp , We have to provide
p the full path with
i the file name:
le.read()
lo I am there\n'
ar, 2
iG

z ani specify
OF appendthe 'a'mode
to thewhile opening
also aMae
file.
e InMSmode,
file. We aay wetS s pecify whether we want to read 'r',
open the file in text mode
or binary
get strings when reading from the fj
5 : ile. The
xe files. used when dealing with non-text files like
of the file specifies the possible operations that can be performed
on the file i.e., what
we are opening a file.
Different Modes of Opening File
, C++, and Java, a file in Python programming can be opened in various
modes depending
urpose. For that, the programmer needs to specify the mode whether read 'r', write
'w', or
a’ mode.
om this, two other modes exist, which specify to open the file in text mode or binary mode.
ext mode returns strings while reading from the file. The default is reading in text mode.
binary mode returns bytes and this is the mode to be used when dealing with non-text files
image or executable files.
and binary modes are used in conjunction with the r, w, and a modes. The list of all the
s used in Python are given in following table:
eS nea’ mae ER sie Description
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
the
Opens a file for reading only in binary format. The file pointer is placed at
beginning of the file. This is the default mode.
placed at the beginning
Opens a file for both reading and writing. The file pointer
of the file.
format. The file pointer placed
Opens a file for both reading and writing in binary
at the beginning of the file.
file does
a file for writing only. Overwrites the file if th e file exists. If the
Opens
not exist, creates a new file for writing. ts. is
file if the file ex
Opens a file for writing only in binary format. Overwrites os
If the file does not exist, creates a new file for writing: isting file if the file
Opens a file for both writing and reading. Overwrites a Oe ine.
for reading
a new file
exists. If the file does not exist, creates contd. ...

Scanned with CamScanner


Scanned with CamScanner
: 67 =
Fite VO Haridtirng sei ty
AY Fig Phe 4

ng File
with operations to the file, we need to properly close the file,
will free up the resources that were tled with the file and \s done weing
ethod. ie
ect.close()
or closing
a file.
sample.txt")
Name of the file: ",f.name)
ae

g Data to File
sthod writes any string to an open file, In order to write into a file in Python, we need wo
write 'w’, append ‘a’ or exclusive creation '” mode.
method writes the contents onto the file, it takes only one parameter and returns the
characters writing to the file,
athod is called by the file object onto which we want to write the data. Vie need to be
he 'w' mode as it will overwrite into the file if it already exists, All previous data are

use three methods to write to a file in Python namely, write(string) (for text),
e_string) (for binary) and writelines (list),
ng) Method;
(stri ng) method writes the contents of string to the file, returning the number of characters

wwrite('This 4s a test\n’)
i

For write(string) method,


("sample.txt")
("**content of file1**”)
(f.read())
n("sample.txt","w")
e("first line\n")

"sample. tx +, “py
Pi “content of file1**”)
(f.read())

Scanned with CamScanner


, pytho
Be iG Hanaling and Exception Handling
ry readline() method.
(’sample.txt", Gap)
eadline()) # read first line followed by\n
eadline(3))
_readline(5))
eadline())

"sample.txt","r")
nt(f.readlines())

» ‘second line\n', ‘third line\n']

ge the current file cursor (position) using the seek() method. Similarly, the tell() method
current position (in number of bytes) of file cursor/pointer.
the file object’s position use f.seek(offset, reference_point). The position is computed from
toareference point.
ce_point can be omitted and defaults to 0, using the beginning of the file as the reference
ference points are 0 (the beginning of the file and is default), 1 (the current position of
e end of the file).
returns an integer giving the file object’s current position in the file represented as
tes from the beginning of the file when in binary mode and an opaque number when
de.
rds, the tell() is used to find the current position of the file pointer in the file while the
_to move the file pointer to the particular position.
or file position.
sample.txt", "r")
tell())
read())
#.tell())
read()) # print blank line
t(F.seek(@))
nt(f.read())

tC ine
‘ond line
4] ine

d
Scanned with CamScanner
Mann,

ooh te

Scanned with CamScanner


a. a
eH 6.11 F ile /0
Handling and Exception
Handling

Reads the content of a file line rie | fens Up pedetings


=f.rea ines()
and returns them as a list of strings, f writeline s(1ines)
f.close()
It calls the readline() to read until text =f.readlines(25) |
EOF. It returns a list of lines read print(text)
from the file. If you pass <size_hint>, f .close()
then it reads lines equalling the
Pa <size_hint> bytes,
Sets the file’s current position. position =f,seek(@,@);
print (position)
f,close()
-
Returns the file’s current position. lines =f.read(10)
#tell()
print(f.tell())
f.close()

Truncates the file’s size. If the f .truncate(16)


optional size argument is present, the f.close()
file is truncated to (at most) that size.
It writes a string to the file. And it line ='Welcome Geeks\n'

doesn’t return any value. #.write(line)


+.close()

Writes a sequence of strings to the lines =f.readlines()

file. The sequence is possibly an H#writelines()

iterable object producing strings, £ writelines(lines)


typically a list of strings. f.close()

e: For file object methods.


("sample.txt”, "w+")
one\nLine two\nLine three”)
("Line
@)
.read())
readable:",f.readable())
Is writeable:",f.writable())
File no:",f.fileno())
Is connected to tty-like device:",f.isatty())

le: True
@able: True
3
nnected to tty-like device: False

Scanned with CamScanner


Programming
with ‘Python’ Per File VO Handling¢ and Except ption Hang),-
Handling Files through OS Mod
ule:
* The OS module of Python allows us to perform Ope ;
rating System (OS) SUch ag os
making a folder, listing contents of a folder, know about a proces
s, end a process etc.
It has methods to view environment variables of the operating system on which
on and many more.
Python is Working
Directory related Standard Fun
ct

1. | os.getcwd()
Show current working import os
directory. os.getcwd() ee
2. | os.path.getsize( ) Show file size in bytes of file size =os.path.getsize(“sample. tx»)
Passed in parameter. |
3 Os.path.isfile() print(os.path.isfile("sample.txt"))
Is passed parameter a file.
4, os.path.isdir() Is passed parameter a folder. print(os.path.isdir(“sample.txt"))
5. | os. listdir()
Returns a list of allfiles and print("***Contents of Present
Goreine directory***\n
folders of present working. " os. listdir())
directory.

6. os.listdir(path) Return a list containing the | print("***contents of given


names of the entries in the directory***\n
directory given by path. ",0s.listdir(“testdir”) )

Te Os .rename(current, new) Renamea file os.rename(“sample.txt", “sample1.txt


. )

os.remove(file_name) | Deletea file.


os.remove(“sample.txt")
os.mkdir() Creates a single subdirectory. os.mkdir("“testdir")
10. os.chdir(path) Change the current working os.chdir("d:\IT")
directory to path.
Example: For handling files through OS module.
import os
os.getcwd()
print("***Contents of Present working directory***\n " » 0S.listdir())
print(os.path.isfile("sample.txt”))
print(os.path.isdir("sample.txt"))

***Contents of Present working directory***


["DLLs', ‘Doc’, ‘etc’, ‘filel.txt', ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’
‘mypkg', ‘NEWS.txt', ‘pl.py', ‘p2.py', ‘python.exe', ‘python3.dl1*,
*pythonw.exe', ‘sample.txt',
an
Scripts”, ‘share’, ‘tel’, Oe’,
*python37.41!
eopls' >
*[email protected]', '_ _pycache_ _‘]
True
False

Scanned with CamScanner


a

13
6,
aa —
ng

sam ng a File
ein on is done with the help of the rename() method, To rename c a fj)lie
in Python,
needs to be imported.
y takes two arguments, the current filename and the new filename
new_file_name)
rename (cu rrent_file_name,
remaining files.

**Contents of Present working directory***\n ",os,listdir())


a o("sample.txt","sample1.txt")
*#contents of Present working directory after rename***\n ",os.listdir())

***
rents of Present working directory
) ‘Doc’, ‘etc’, ‘filel.txt’, ‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’
kg’, ‘NEWS.txt’, '‘p1.py’, ‘p2.py', ‘python.exe', ‘python3.d1l’, ‘python37,d11',
‘share’, ‘tcl’, ‘test.py’, ‘Tools’.
onw.exe', ‘sample.txt', 'Scripts', 2
e140.d11', '_ _pycache_ _']
err*
working directory after renam
nts of Present
‘include’, ‘Lib’, ‘libs’, ‘LICENSE.txt’,
, ‘Doc', ‘etc’, 'file1.txt',
‘pl-py', ‘p2.py', ‘python.exe’, "python3.d11', ‘python37.d11',
'NEWS.txt',
‘Scripts’, ‘share’, ‘tcl’, ‘test.py’, ‘Tools’,
w.exe’, ‘Samplel.txt',
[email protected]', '_ _pycache_ Te

nga File
ing the name of the file to be deleted as the
the remove() method to delete files by supply
remove() in Python programming in used
file, the OS module need to be imported. The
he existing file with the file name.
remove(file_name)
le: For deleting files.
os
working directory***\n ",0s.listdir())
("***Contents of Present
ve("sample.txt”)
directory***\n "os. listdir())
t("***New Contents of Present working

ntents of Present working directory***


‘Lib’, ‘libs’, LICENSE.txt’,
‘file1.txt’, ‘include’,
*, "Doct, ‘etc’,
‘python.exe’, ‘python3.d11', ‘python37.d11’,
", 'NEWS.txt’, ‘pl.py', ‘p2-py', ‘Tools’,
‘share’, ‘tcl’, ‘test.py’,
‘sample.txt', 'Scripts',
onw.exe’,
me149.d11', '_ _pycache_ _']
of Present working directory***
ents
"libs", SE.Atxt,
"LICENena?
‘filel.txt’, ‘anclude’, ‘Lib’,
‘Doc’, ‘etc’, "pyt /-"".* 11",?
hone140
' 92. p y ' , ‘py tho
‘pyt n.e xe’, » ' ‘Py thon3.d11",
semunt ime
txt',’, ' ‘pl.py',
"NEWS.txt ‘p2-py', ‘Tools’,
‘Scr ipts ’, ‘sha re’, ‘tel’, ‘test-py’,
.exe ’,
*
oF
.he_ a)
pass e d in the method exists
her the file
ethod in Python programming checks whet
.
ue
is trif the file exist otherwise it returns false

Scanned with CamScanner


Handling and Excenin,, 4
Programming with 'Python' 6.14 Fie v0 a

“wakil Directories
e can arran Ze the COG
* If there are a large number of files to handle in the Python program,
different directories to make things more manageable. ie 0s 04:11.
* A directory or folder is a collection of files and sub directories. i,
(and files as well) i),
provides us with many useful methods to work with directories
PeURY Create New Directory
* Wecan make anew directory using the mkdir() method.
- ..
* This method takes in the path of the new directory. If the full pa th is not specified, the new
is created in the current working directory.
Syntax: os. mkdir (“newdir”)
Example:
>>> import os
>>> os.mkdir("testdir")

ware Get Current Directory


* We can get the present working directory using the getcwd() method.
current working directory
This method rev
in the form of a string.
Synt
os.ax:
getcwd()
Example:
>>> import os
>>> os.getcwd()
'C:\\Users\\ Meenakshi \\AppData\\Local\\Programs\\Python\ \Python37-32°
PRU Changing Directory
e Wecan change the current working directory using the chdir() method.
¢ The new path that we want to change must be supplied as a string to this method. We can use 20
forward slash (/) or the backward slash (\) to separate path elements.
Syntax: os. chdir(“dirname”)
Example:
>>> import os
>>> os.getcwd()
'C:\\Users\\Meenakshi\\AppData\\Local\ \Programs\\Python\ \Python37’
>>> os.chdir("d:\IT")
>>> os.getcwd()
Te NNT
>>>

EEZTY] List Directories and Files


¢ All files and sub directories inside a directory can be known using the listdir() method.
e This method takes in a path and returns a list of sub directories and files in that path. If no p2- e
specified, it returns from the current working directory.
Example:
>>> os.listdir()
[‘DLLs', ‘Doc’, ‘include’, ‘Lib’, ‘libs’, "LICENSE.txt’, "NEWS.txt’, ‘python-2**
‘python3.d11', ‘python37.d1l', ‘pythonw.exe", "Scripts’, ‘tcl’, ‘test.py’, ‘testo
'Tools', ‘[email protected]’]

Scanned with CamScanner


6.16 Pile /6 Handing and By.
HMM Venti tees
4

ectories in the current directory,


”)

wu stdir( )
', ‘include’, n.e‘ibxa'’,, ‘ib s’, License tzt ’, myo mydir’,
eames ture!) Filed.txt'p2 .py's ‘pytho ‘pyt hona .dll ', ’ a
‘NEWS. txt") ‘pl. py's eo
e
‘Scripts’, ‘share’, ‘tcl’,
er ‘cample.txt', ie ¢
, '. -pyeache_ _']

‘LICENSE.txt’ woke
'dnclude’, ‘Lib’, ‘libs’,
r Yate 5 'filei.txt',
‘python-exe’, = “pytho n3.d11", ‘python37,d11’.
Ueiupyiy)) ‘paspy'y ‘tcl
‘share’, ’, ‘tes t.py ’ eee
‘sample.txt', ‘Scripts’,
ycache_ mu)
me140.d11' , '_ -p

ry is not empty then we will get the “The directory 1s not empty” error, To remove - a
emove() method,
stremove all the files inside it using os.r 7”)
ata\\Local\\Programs \\Python\ \Python2
hdir("C: \\Users\\Meenakshi\\AppD
_pmdir("mydir1")
k (most recent call last):
<pyshel1#32>", line 1, in <module>
ir("mydir1") 'mydir1’
145] The directory 4s not empty:
r: [WinError Python / mydirt”)
\Meenakshi\\ AppData\ \Local\\Programs \\Python\\
ndin("c:\\Users\

emove("sample.txt”)
istdir()
ans\\Python\\Pythe n27
akshi\ \AppData\\Local\ \Progr
speincecs\\users\\Meen
mdir("mydir1”)
shutil module.
ory we can u se the rm tr ee() method inside the
remove a non-empty direct

te some content in it.


create a simple file and wri
Enter ‘x' for exit."); content: ")3
input("Enter file name to cre ate and write
A == An)

ppe (filename, “yes

\nThe file,",filename,"created success fully!");


to write on the file: “);
sentences

Scanned with CamScanner


sell
Scanned with CamScanner
617 File | /O Handling and
Exception Handli
ng

a)
Fs me: filel
to be searched;o
: of the letter:

+
vecutes a Python program, there may be a few
uncertain conditions which occur, known
s also referred to as bugs that are incorrect or inaccurate action that may eee the
jn the running of the program or may interrupt the execution of program.
following three type of error occurs:
ile Time Errors: Occurs at the time of compilation, include due error occur to the violation
ntax rules like missing of acolon (:).
aime Errors: Occurs during the runtime of a program, example, include error occur due to
iput submitted to program by user.
Errors: Occurs due to wrong logic written in the program.
s at runtime are known as exception. Errors detected during execution of program,
es a feature (Exception handling) for handling any unreported errors in program.
tion occurs in the program, execution gets terminated. In such cases we get system
ed error message.
ling the exceptions, we can provide a meaningful message to the user about the problem
system generated error message, which may not be understandable to the user.
n be either built-in exceptions or user defined exceptions.
eter or built-in functions can generate the built-in exceptions while user defined
‘e custom exceptions created by the user.
ile: For exceptions.

ceback (most recent call last):


[le “<pyshell#2>", line 1, in <module>
5/0

ODivisionError: division by zero

itr JIUuction

pti on is also called as runtime error that can halt the execution of the program.
is an error that happens/occurs during execution of a program. When that error
avoids the normal flow of the
Python generate an exception that can be handled, which
's instructions. error),
event (usually an
detected during execution are called exceptions. An exception is an n of the
flow of executio
Occurs during the execution of a program that disrupts the norm al
mor program's instructions). ry-finally
t
statement,
on programming we can handle exceptions using try except
ent and raise statement.

Scanned with CamScanner


ail
Programming with ‘Python! 6.18 __ File VO Handling and Exceptic,, Hany fis

e Following table lists a ll the standard excep tions available in Python programming languaye.
<.Cr ee a a Te
t
a! pial = eee
ArithmeticError Base class for all errors that occur for numeric calculation,
2. AssertionError Raised in case of failure of the assert statement. L
3 AttributeError Raised in case of failure of attribute reference or assignmen:,
4. Exception Base class for all exceptions.
5. a
EOFError Raised when there is no input from either the raw_inpury,
input() function and the end of file is reached. in
6. EnvironmentError Base class for all exceptions that occur outside the py...
environment.
a FloatingPointError | Raised whena floating point calculation fails.
8. ImportError Raised when an import statement fails. ;
9, IndexError Raised when an index is not found in a sequence. 3
10. IOError Raised when an input/ output operation fails, such as the p;:,.
statement or the open() function when trying to open a file +};-
does not exist.
11. IndentationError al
Raised when indentation is not specified properly.
12 Keyboardinterrupt i
Raised when the user interrupts program execution, usually
5,
pressing Ctrl+c,
13. KeyError Raised when the specified key is not found in the dictionary.
14, LookupError Base class for all lookup errors.
15. 4
NameError Raised when an identifier is not found in the local or global
namespace,
16. NotImplementedError | Raised when an abstract method that
needs to be implemented in
an inherited class is not actually implemented.
17. OverflowError Raised when a calculation exceeds maximum limit for a numeric
type.
18. OSError Raised for operating systern-related errors.
13) RuntimeError Raised when a generated error does not fall into any categor
y.
20. StopIteration Raised when the next() method of an iterator does not
point to any
object.
Ze SystemExit Raised by the sys.exit() function,
22, StandardError Base class for all built-in exceptions except Stoplteration and
SystemExit.
23. SyntaxError Raised when there is an error in Python syntax.
24. SystemError Raised when the interpreter finds an internal problem, but when
this error is encoun tered the Python interpreter does not
exit.
25. SystemExit Raised when Python interpreter js quit by using
the sys.exit(
function. If not handled in the code, causes the
interpreter to exit.
26. TypeError Raised when an operation or function is attempted that is
for the specified invalid
data type. _I
27. UnboundLocalError Raised when trying to access a local Variable in a function %
method but no value has been assigned to it.
28. ValueError Raised when the built-in function for a data type has the valid tyP*
of arguments, but the arguments have invalid values
specified.
29. ZeroDivisionError fet when division or modulo by zero takes place for all numeric
es.

Scanned with CamScanner


6.19
it! on’ File VO Handling and Excepti
on Handling
2

+ion Handling in Python Programming


ig; an event, whicich occurs during the execution of a pr :
Program that disrupts the normal
e progr m’s instructions.
hen a Python script encounters a situation that it
cannot co Pe with, it
raises an
exception is a Python object that represents an error.
ple, if function Acalls function B which in turn calls function C and an except
mp. if it is not handled in C, the exception passes to Band then to A. ion occurs in
When a Python
Script
a exception, it must either handle the exception immediately othe Twise it term
LT inates and
tion handling is a process that provides
a way to handle exceptions that occ
«jon handling is done by writing exception hand ur at runtime.
lers in the program.
eption handlers are blocks that execute when some exception occurs at runtim €. Except
displays same message that represents information about the exception. ion
ing exceptio in
atements that n needPyth on, the exception handler bloc needs to be written which consists of
to be executed according to raisedk exce ption. There are three blocks that
qin the exception handling process, namely, try, except and final
ly.
ock: A set of statements that may cause error during runtime are to be written in the try

Block: It is written to display the execution details to the user when certain exception
s in the program. The except block executed only when a certain type as exception occurs in
ecution of statements written in the try block.
ly Block: This is the last block written while writing, an exception handler in the program
indicates the set of statements that are used to clean up the resources used by the
am.
y -except
, exceptions can be handled using a try statement. A try block consisting of one or more
ts is used by programmers to partition code that might be affected by an exception.
tical operation which can raise exception is placed inside the try clause and the code that
s exception is written in except clause.
sociated except blocks are used to handle any resulting exceptions thrown in the try block. If
statement within the try block throws an exception, control immediately shifts to the catch
. Ifno exceptions is thrown in the try block, the catch block is skipped.
san be one or more except blocks. Multiple except blocks with different exception names can
ned together.
except blocks are evaluated from top to bottom in the code, but only one except block is executed
n exception that is thrown.
st except block that specifies the exact exception name of the thrown exception is executed. If
t block specifies a matching exception name then an except block that does not have an
name is selected, if one is present in the code.

ry
‘certain operations here

rt Exceptioni:
et there is Exceptioni, then execute this block.
“cept Exception2:
‘Tf there is Exception2, then execute this block.
Cena REGEs 66 ks eee ee 0

If there is no exception then execute this ptock. (vib ” oc)

Scanned with CamScanner


6.21 File /O Handlin
———a neing and Exception
and Ex Handjj
ception Ha ndi ng

integer: >
cur! ed

nter valid value


integer: 2-5

t i valid value
ar “integer: @
curred
rer valid value

n integer: 5
1 2.0

t in Python can have an optional finally clause. This clause is executed always and is
sed to release external resources.
nt written in finally clause will always be executed by the interpreter, whether the t
s an exception or not. ry
ck is always executed before leaving the try statement, whether an exception is occurred
nan exception is occurred in try block and has not been handled by an except block, it is
fter the finally block has been executed.
eis also executed “on the way out” when any other clause of the try statement is left

h = open("testfile”, "w")
ite("This is my test file for exception handling!!")

it ("file is closing")
mae)
ram to check for ZeroDivisionError Exception.
input("Enter first value:"))
iput("Enter second value:"))

Mt=x/y
feroDivisionError:
int("Division by Zero”)

Pint("Result is:",result)

rint("Execute finally clause”)

Scanned with CamScanner


ramming with ‘Python’ 6.22 File /O Handlinigg AN BxOeptio
MePtlOn
n iiy,,,,,Hari),

Output 1: Lo
Enter first value:5
Enter second value:@
Division by Zero
Execute finally clause
Output 2:
Enter first value:10
Enter second value:5
Result is: 2.0
Execute finally clause
raise Statement
¢ We can raise an existing exception by using
raise keyword, So, we just simply write raise
and then the name keywa
of the exception.
The raise statement allows the programmer to force a specif
ied exception to occur,
Example: We can use raise to throw an exception if age
is less than 18 condition occurs,
while True:
try:
age = int(input("Enter your age for election: "))
if age < 18:
raise Exception
else:
print("you are eligible for election")
break
except Exception:
print("This value is too small, try again")
Output:
Enter your
age for election: 11
This value is too small, try again
Enter your age for election: 18
you are eligible for election
>>>
¢ The raise statement can be complemented with a custom
exception as explained in next section.
User Defined Exception
¢ Python has many built-in exceptions which forces the program to output an error when something
in it goes wrong. However, sometimes we may need to create custom exceptions that serves
the
purpose.
e Python allow programmers to create their own exception class, Exceptions should typically be
derived from the Exception class, either directly or indirectly. Most of the built-in
exceptions are also
derived from Exception class.
* User can also create and raise his/her own exception known
as user defined exception.
e In the following example, we create custom exception class A
geSmallException that is derived from
the base class Exception.
————
Example 1: Raise a user defined exception if age is less than 18.
# define Python user-defined exceptions
class Error(Exception):
"“""Base class for other exceptions""” # empty class
pass
—_———

6.23 File /O Handling and Exceptic n Handling


a

rror):
l 1exception(E
class Agesma
t value too small""" # empty class
wvRaised when the inpu is

pass
# main program
while True:
try:
age for election: "))
age = int(input("“Enter your
if age < 18:
raise AgeSmallException
else:
print("you are eligible for election")
break

except AgeSmallException:
print("This value is too small, try again!")
print()
Output:
Enter your age for election: 11

This value is too small, try again!

Enter your age for election: 15

This value is too small, try again!


Enter your age for election: 18

you are eligible for election


is incorrect.
Example 2: Raise a user defined exception id password
class InvalidPassword(Exception):
pass
def verify_password(pswd):
if str(pswd) != "abc":
raise InvalidPassword
else:
print('Valid Password: ‘+str(pswd) )
# main program
# won't raise exception
verify_password("abc")
verify password("xyz") # will raise exception
Output:
Valid Password: abc
Traceback (most recent call last):
\Programs \Python \Pyt
File "C:\Users\Meenakshi \AppData\Local
<module> '

verify_password("xyz") # will raise exception 6, in


line
File "C:\Users\Meenakshi \AppData\Local \Programs\PY
verify _password
raise InvalidPassword
InvalidPassword

Scanned with CamScanner


Progr ammMing ’
with Python’ 6.24 File /O Handling a d £.
—ACe ton y ,

Practice Questions
ee

What is file? Enlist types of files in Python programming.


Ss

-
What is exception? r
»
WP ONAVAYWN
Explain the term exception handling in detail.
Explain different modes of opening a file.
Write the syntax of fopen() with example.
What are various modes of file object? Explain any o
o
Explain exception handling with example using try,
ss
Explain try...except blocks for exception handling in Python.
Explain various built in functions and methods.
. Explain open() and close() methods for opening and closing a file.
PP Be
SWODNIAHRWNEO

. Explain any three methods associated with files in Python.


RPPPRP

. List and explain any five exceptions in Python.


. List out keywords used in exception handling.
. How python handles the exception? Explain with an example program.
NPeRPe

. Differentiate between an error and exception.


. How to create a user defined exception?
. Give the syntax and significance of input() method.
. Give syntax of the methods which can be used to take input from the user in Python progra:,
less th:, »..
. Write a Python program which will throw exception if the value entered by user is
to cat
. Write a Python program to accept an integer number and use try/except
a floating point number is entered.
21. Write a Python program to read contents of first.txt
file and write same con’
at to b
2z: Write a Python program to append data to an existing file ‘python.py’. Read ch d
from the use. Then display the contents of entire file.
of lines, words and characters
23. Write a Python program to read a text file and print number
'
24. Describe the term file 1/O handling in detail. \

You might also like