Python (Nirali Publi)
Python (Nirali Publi)
PROGRAMMING WITH
'PYTHON'
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
4.0 Introduction
41 Use of Python Built-In Functions
4.1.1 Type Data Conversion Functions
41,2 Built-in Mathematical Functions
io
a
-
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]
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
=
L
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
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,
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).
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
* 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
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.
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 (,).
’’
‘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).
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'''
2 python
ae eee a —
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
ay UES Weer
Sr ae
iene atop)
Acrobat Reader D
alee ase ed
vite,
Fig. 1.14
; 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:
ne ae
| 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
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.
>>>
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.
Fig. 1.19
Window Help
20 2018, 14:05:16) (MSC v.1915 32 bit (Inte
c3éa, Oct
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|
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!
List: Represents sequential data that the programmer wishes to sort, merge etc.
oy
>>> b=-10
>>> b
m4
‘Ob’ or ‘OB’ ;
"Two", Three’ ]
'd=[10, "one", 20, "two" ] # heterogeneous values in list
>>> dici.values()
dict_values([‘First’, 2, ‘Third’ ])
IN PYTHON PROGRAMMING _ 7
a >>>
>>> 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"
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
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
Chapter Outcomes...
Write simple Python program for the given arithmetic expressions.
=) =) @)
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]
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
* 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
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
« 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. : - . -- ———
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
Statement just
below if 7"
else:
print(number," is odd number" )
Output:
Enter any number: 10
1@ is even number
Enter any number: 11
11 is odd number
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
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]
« 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]
>>> list1.extend(list2)
>>> list1
(1,237 sey Sf ey
‘BY, 'C']
— 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
>>> list1l.pop(2)
| >>> 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]
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.
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)
>>> tuple3
2@, 3@], [11, ‘abc’, 22.33])
(python’, [18,
Output:
10
20
30
>>>
.
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
>>> 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):
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
4. | get() Returns the value of the | >>> dict1={'name': ‘vijay’, ‘age’ :40}
specified key. >>> dict1.get( ‘name’ )
‘vijay’
-
a
Called
>>>
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="")
—
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
:|
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’ _
Learning Objectives...
To learn Basic Concepts of Functions
Seeemee
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]
contd
»
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
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
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
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
>>> a=3
>>> a=increment(3)
>>> print(a)
4
<§—$—}——
+)
——
nS
—
n o
Scope of Variable _ tg *
gram This depend,
On
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)
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
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
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.
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
, 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
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
>>>
sa
=3
4 Cc 1
o®
" ae
[sé] 2 i {> 2 3 aes
2?
5| Columns
0 Axis-1
(a) (b)
Fig. 4.6: Dimensions of NumPy Array
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
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 *
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
© 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)
un
is package is
as a package.
.
ctior
fur wy
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:
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.
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
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()
ited Programming
t integrity by
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
. .
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
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
EE TEE
Scanned with CamScanner
1 using dot operator
pt y. It displays them
Generally the
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)
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 +,
@
- .
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)
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()
- .
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
(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
|
s creating complex types by combining objects of other types.
eans that a class Composite can contain an Gomponalll
object of another
r ponent.
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
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
: # 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
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
_<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.
(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
input())
: 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. ...
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
"sample. tx +, “py
Pi “content of file1**”)
(f.read())
"sample.txt","r")
nt(f.readlines())
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
le: True
@able: True
3
nnected to tty-like device: False
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.
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.
***
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
“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")
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
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.
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.
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.
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
integer: >
cur! ed
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)
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
—_———
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
Practice Questions
ee
-
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