Python Programming Lecture Notes
Python Programming Lecture Notes
(Autonomous)
Dundigal, Hyderabad - 500 043
LECTURE NOTES
Program B.Tech
I Semester: AERO | MECH | CIVIL
Semester II Semester: CSE | CSE (AI & ML) | CSE (DS) | CSE (CS) | CSIT |
ECE | EEE | IT
Course Type Core
Regulation UG20
Theory Practical
3 0 3 3 1.5
COURSE OBJECTIVES:
IV Develop the ability to write modular programming using object oriented concepts.
V Enhance programming skills to choose multiple career paths and engage in lifelong
learning.
COURSE OUTCOMES:
Knowledge Level
Course Outcomes (Bloom‟s
Taxonomy)
CO 1 Understand operators, precedence of operators, associativity Understand
while evaluating expressions in program statements.
CO 2 Visualize the capabilities of procedural as well as object- Understand
oriented programming in Python and demonstrate the same in
real world scenario.
MODULE – I
INTRODUCTION TO PYTHON
Introduction to Python:
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL andPHP.
Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write yourprograms.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code withinobjects.
Python is a Beginner's Language: Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers togames.
Features of Python
Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the languagequickly.
Easy-to-read: Python code is more clearly defined and visible to theeyes.
Easy-to-maintain: Python's source code is fairlyeasy-to-maintain.
A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, andMacintosh.
Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets ofcode.
Portable: Python can run on a wide variety of hardware platforms and has the same
interface on allplatforms.
Extendable: You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be moreefficient.
Databases: Python provides interfaces to all major commercialdatabases.
GUI Programming: Python supports GUI applications that can be created and ported
to many system calls, libraries, and windows systems, such as Windows MFC,
Macintosh, and the X Window system ofUNIX.
Scalable: Python provides a better structure and support for large programs than shell
scripting.
History of Python
Python was developed by Guido van Rossumin the late
eighties and early nineties at the National Research Institute
for Mathematics and Computer Science in theNetherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scriptinglanguages.
At the time when he began implementing Python, Guido van Rossum was also reading
the published scripts from "Monty Python's Flying Circus" (a BBC comedy series
from the seventies, in the unlikely case you didn't know). It occurred to him that he
needed a name that was short, unique, and slightly mysterious, so he decided to call
the language Python.
Python is now maintained by a core development team at the institute, although Guido
van Rossumstill holds a vital role in directing itsprogress.
Python 1.0 was released on 20 February,1991.
Python 2.0 was released on 16 October 2000 and had many major new features,
including a cycle detecting garbage collector and support for Unicode. With this
release the development process was changed and became more transparent and
community- backed.
Python 3.0 (which early in its development was commonly referred to as Python 3000
or py3k), a major, backwards-incompatible release, was released on 3 December 2008
after a long period of testing. Many of its major features have been back ported to the
backwards-compatible Python 2.6.x and 2.7.x versionseries.
In January 2017 Google announced work on a Python 2.7 to go transcompiler, which
The Register speculated was in response to Python 2.7's plannedend-of-life.
It's Powerful
From a features perspective, Python is something of a hybrid. Its tool set places
it between traditional scripting languages (such as Tcl, Scheme, and Perl), and systems
languages (such as C, C++, and Java). Python provides all the simplicity and ease of
use of a scripting language, along with more advanced programming tools typically
found in systems development languages.
Automatic memorymanagement
Python automatically allocates and reclaims ("garbage collects") objects when
no longer used, and most grow and shrink on demand; Python, not you, keeps track of
low- level memory details.
Programming-in-the-large support
Finally, for building larger systems, Python includes tools such as modules,
classes, and exceptions; they allow you to organize systems into components, do OOP,
and handle events gracefully.
It's Mixable
Python programs can be easily "glued" to components written in other
languages. In technical terms, by employing the Python/C integration APIs, Python
programs can be both extended by (called to) components written in C or C++, and
embedded in (called by) C or C++ programs. That means you can add functionality to
the Python system as needed and use Python programs within other environments or
systems.
It's Easy to Use
For many, Python's combination of rapid turnaround and language simplicity
make programming more fun than work. To run a Python program, you simply type it
and run it. There are no intermediate compile and link steps (as when using languages
such as C or C++). As with other interpreted languages, Python executes programs
immediately, which makes for both an interactive programming experience and rapid
turnaround after program changes. Strictly speaking, Python programs are compiled
(translated) to an intermediate form called bytecode, which is then run by
theinterpreter.
It's Easy to Learn
This brings us to the topic of this book: compared to other programming
languages, the core Python language is amazingly easy to learn. In fact In fact, you can
expect to be coding significant Python programs in a matter of days (and perhaps in
just hours, if you're already an experienced programmer).
Internet Scripting
Python comes with standard Internet utility modules that allow Python
programs to communicate over sockets, extract form information sent to a server-side
CGI script, parse HTML, transfer files by FTP, process XML files, and much more.
There are also a number of peripheral tools for doing Internet programming in Python.
For instance, the HTMLGen and pythondoc systems generate HTML files from
Python class-based descriptions, and the JPython system mentioned above provides
for seamless Python/Javaintegration.
Database Programming
Python's standard pickle module provides a simple object-persistence system: it
allows programs to easily save and restore entire Python objects to files. For more
traditional database demands, there are Python interfaces to Sybase, Oracle, Informix,
ODBC, and more. There is even a portable SQL database API for Python that runs the
same on a variety of underlying database systems, and a system named gadfly that
implements an SQL database for Python programs.
Image Processing, AI, Distributed Objects,Etc.
Python is commonly applied in more domains than can be mentioned here. But
in general, many are just instances of Python's component integration role in action.
By adding Python as a frontend to libraries of components written in a compiled
language such as C, Python becomes useful for scripting in a variety of domains. For
instance, image processing for Python is implemented as a set of library components
implemented in a compiled language such as C, along with a Python frontend layer on
top used to configure and launch the compiled components.
Applications of Python:
1. SystemsPro
gramming
2. GUIs
3. InternetScripting
4. ComponentIntegration
5. DatabaseProgramming
6. RapidPrototyping
7. Numeric and ScientificProgramming
And run this program by calling python hello.py. Make sure you change to the directory
where you saved the file before doingit.
Variables:
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types to
variables, you can store integers, decimals or characters in these variables.
KEYWORDS
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
COMMENTS
Comments are the non-executable statements explain what the program does. For large
programs it often difficult to understand what is does. The comment can be added in the
program code with the symbol # and multiple line comment code with symbol ‗‘‘ ‗‘‘ or ―‖‖
―‖‖
Example:
Python does not support braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation. All the continuous
lines indented with same number of spaces would form a block. Python strictly follow
indentation rules to indicate the blocks.
Data Types:
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and the
storage method for each of them.
Python has five standard data types:
Numbers
String
Boolean
List
Tuple
Set
Dictionary
Python Numbers:
Number data types store numeric values. Number objects are created when you assign
a value to them.
Python supports four different numerical types:
int (signedintegers)
long (long integers, they can also be represented in octal andhexadecimal)
float (floating point real values)
complex (complexnumbers)
Python allows you to use a lowercase L with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long integers
with an uppercase L.
A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x is the real part and b is the imaginary part of the complex number.
For example:
Program:
a=3
b = 2.65
c = 98657412345L
d = 2+5j
print "intis",a
print "float is",b
print "long is",c
print "complex is",d
Output:
int is 3
float is 2.65
long is 98657412345
complex is (2+5j)
Python Strings:
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings
can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning
of the string and working their way from -1 at theend.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example:
Program:
str ="WELCOME"
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "CSE" # Prints concatenated string
Output:
WELCOME
W
LCO
LCOME
WELCOMEWELCOME
WELCOMECSE
Built-in String methods for Strings:
Example:
str1="welcome"
print "Capitalize function---",str1.capitalize()
print str1.center(15,"*")
print "length is",len(str1)
print "count function---",str1.count('e',0,len(str1))
print "endswith function---",str1.endswith('me',0,len(str1))
print "startswith function---",str1.startswith('me',0,len(str1))
print "find function---",str1.find('e',0,len(str1))
str2="welcome2017"
print "isalnum function---",str2.isalnum()
print "isalpha function---",str2.isalpha()
print "islower function---",str2.islower()
print "isupper function---",str2.isupper()
str3=" welcome"
print "lstrip function---",str3.lstrip()
str4="77777777cse777777";
print "lstrip function---",str4.lstrip('7')
print "rstrip function---",str4.rstrip('7')
print "strip function---",str4.strip('7')
str5="welcome to java"
print "replace function---",str5.replace("java","python")
Output:
Capitalize function--- Welcome
****welcome****
length is 7
count function--- 2
endswith function--- True
startswith function--- False
find function--- 1
isalnum function--- True
isalpha function--- False
islower function--- True
isupper function--- False
lstrip function--- welcome
lstrip function--- cse777777
rstrip function--- 77777777cse
strip function--- cse
replace function--- welcome to python
Python Boolean:
Booleans are identified by True or False.
Example:
Program:
a = True
b = False
print a
print b
Output:
True
False
Data Type Conversion:
Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type name as a function. For example, it is not
possible to perform ―2‖+4 since one operand is integer and the other is string type. To
perform this we have convert string to integer i.e., int(“2”) + 4 =6.
There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.
Function Description
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
complex(real [,imag]) Creates a complex number.
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key, value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Arithmetic Operators:
Some basic arithmetic operators are +, -, *, /, %, **, and //. You can apply these
operators on numbers as well as variables to perform corresponding operations.
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand
- Subtraction a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 200
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) calculation on a**b =10 to
** Exponent
operators the power 20
The division of operands where the result is
9//2 = 4 and
// Floor Division the quotient in which the digits after the
9.0//2.0 = 4.0
decimal point are removed.
Program:
a =21
b =10
print "Addition is", a + b
print "Subtraction is ", a - b
print "Multiplication is ", a * b
print "Division is ", a / b
print "Modulus is ", a % b
a =2
b =3
print "Power value is ", a ** b
a = 10
b=4
print "Floor Division is ", a // b
Output:
Addition is 31
Subtraction is 11
Multiplication is 210
Division is2
Modulus is 1
Power value is 8
Floor Division is2
Comparison (Relational) Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Operator Description Example
If the values of two operands are equal, then the
== (a == b) is not true.
condition becomes true.
If values of two operands are not equal, then
!= (a != b) is true.
condition becomes true.
(a <> b) is true. This
If values of two operands are not equal, then
<> is similar to !=
condition becomes true.
operator.
If the value of left operand is greater than the value
> (a > b) is not true.
of right operand, then condition becomes true.
If the value of left operand is less than the value of
< (a < b) is true.
right operand, then condition becomes true.
If the value of left operand is greater than or equal
>= to the value of right operand, then condition (a >= b) is not true.
becomes true.
If the value of left operand is less than or equal to
<= the value of right operand, then condition becomes (a <= b) is true.
true.
Example:
a=20
b=30
if a < b:
print "b is big"
elif a > b:
print "a is big"
else:
print "Both are equal"
Output:
b is big
Assignment Operators
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a isbig"
elif b >= a and b >= c:
print "b isbig"
else:
print "c is big"
Output:
c is big
Bitwise Operators
Expression:
An expression is a combination of variables constants and operators written according
to the syntax of Python language. In Python every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable. Some
examples of Python expressions are shown in the table given below.
Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left
hand side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example:
a=10
b=22
c=34
x=a*b+c
y=a-b*c
z=a+b+c*
c-a print
"x=",x
print
"y=",y
print
"z=",z
Output:
x= 254
y=-738
z= 1178
Console Input/output
To get input from the user you can use the input function. When the input function is
called the program stops running the program, prompts the user to enter something at the
keyboard by printing a string called the prompt to the screen, and then waits for the user to
press the Enter key. The user types a string of characters and presses enter. Then the input
function returns that string and Python continues running the program by executing the next
statement after the input statement.
Python provides the function input(). input has an optional parameter, which is the
prompt string.
For example,
OUTPUT function:
We use the print() function or print keyword to output data to the standard output device
(screen). This function prints the object/string written in function.
The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character. After all
values are printed, end is printed. It defaults into a new line ( \n ).
FORMATTING
So far we‘ve encountered two ways of writing values: expression statements and the
print() function. Often you‘ll want more control over the formatting of your output than simply
printing space-separated values. There are several ways to format output.
To use formatted string literals, begin a string with f or F before the opening quotation
mark or triple quotation mark. Inside this string, you can write a Python expression between
{ and } characters that can refer to variables or literal values.
At the end of the unit students are able to:
Knowledge Level
Course Outcomes (Bloom‟s
Taxonomy)
CO 2 Visualize the capabilities of procedural as well as object- Understand
oriented programming in Python and demonstrate the same in
real world scenario.
CO 8 Make use of appropriate modules for solving real-time Apply
problems.
MODULE – II: DECISION CONTROL STATEMENTS
MODULE – II:
DECISION CONTROL STATEMENTS
Decision Making
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce True or False as
outcome. You need to determine which action to take and which statements to execute if
outcome is True or False otherwise.
Following is the general form of a typical decision making structure found in most of
the programming languages:
Python programming language assumes any non-zero and non-null values as True,
and if it is either zero or null, then it is assumed as Falsevalue.
Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
The if Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.
Syntax:
if
conditi
First, the on:
condition is tested. If the condition is True, then the statements given after
stateme
colon (:) are executed. We can write one or more statements after colon (:).
nts
Example:
a=10
b=15
if a < b:
print ―B is big‖
print ―B value is‖,b
Output:
B is big
B value is 15
The if ... else statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSEvalue.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if condition:
statement(s)
else:
statement(s)
Example:
a=48
b=34
if a < b:
print ―B is big‖
print ―B value is‖,b
else:
print ―A is big‖
print ―A value is‖, a
print ―END‖
Output:
A is big
A value is 48
END
Q) Write a program for checking whether the given number is even or not.
Program:
a=input("Enter a value: ")
if a%2==0:
print "a is EVEN number"
else:
print "a is NOT EVEN Number"
Output-1: Output-2:
Enter avalue: 56 Enter a value:27
a isEVENNumber a is NOT EVENNumber
The elifStatement
The elifstatement allows you to check multiple expressions for True and execute a
block of code as soon as one of the conditions evaluates to True.
Similar to the else, the elifstatement is optional. However, unlike else, for which there
can be at most one statement, there can be an arbitrary number of elifstatements following
anif.
Syntax: if condition1:
statement(s)
elifcondition2:
statement(s)
else:
statement(s)
Example:
a=20
b=10
c=30
if a >= b and a >= c:
print "a isbig"
elif b >= a and b >= c:
print "b isbig"
else:
print "c is big"
Output:
c is big
Decision Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement:
Python programming language provides following types of loops to handle looping
requirements.
Loop Type Description
Repeats a statement or group of statements while a given condition is
while loop
TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.
Output-1: Output-2:
1 1
END 2
2 3
END END
3
END
Output:
print "Factorial is",f
Enter the number: 5
Factorial is 120
The for loop:
The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of
elements in the sequence. The for loop can work with sequence like string, list, tuple, range
etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)
The first element of the sequence is assigned to the variable written after „for‟ and
then the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of
the sequence, the statements are executed once. So, the for loop is executed as many times as
there are number of elements in thesequence.
Example-1: Example-2:
for i range(1,5): for i range(1,5):
print i print i
print ―END‖ print ―END‖
Output-1: Output-2:
1 1
END 2
2 3
END END
3
END
Example-3: Example-4:
p 10 9 8 7 6 5 4 3 2 1
y
t
h
o
n
else:
print"*",
else:
Example-4: print " ",
print""
Example-5: for i in range(1,6):
for j in range(1,6):
if i==j:
print"$",
else:
else:
print"*",
else:
Example-8: print " ",
forprint""
i in range(1,6):
for j in range(1,4):
if i==1 or j==1 or i==3 or i==5:
print "*",
else:
for i in range(1,6):
for c in range(i,6):
print "",
for j in range(1,i+1):
Example-10: print "*",
forprint ""
i in range(1,6):
for j in range(1,i+1):
print j,
print ""
Example-11:
a=1
for i in range(1,5):
for j in range(1,i+1):
print a,
a=a+1
print ""
1) Write a program for print given number is prime number or not using for loop.
Program: n=input("Enter the n value") count=0
for i in range(2,n):
if n%i==0: count=count+1
break
if count==0:
Enter n value: 17
Prime Number
Output:
2) WriteaprogramprintFibonacciseriesandsumtheevennumbers.Fibonacciseries
break
else:
sum=0
while True:
n=input("Enter the number: ")
if n==-1:
break
else:
sum+=n
Program:
Output:
Enter the number: 1
print "The sum is",sum
Enter the number: 5
Enter the number: 6
Enter the number: 7
Enter the number: 8
Enter the number: 1
Enter the number: 5
Enter the number: -1
The sum is 33
Program:
ch='A'
for j in range(1,27):
print ch,
ch=chr(ord(ch)+1)
ABC
ABCD
A B C DE
Program:
for i in range(1,6):
ch='A'
for j in range(1,i+1):
print ch,
ch=chr(ord(ch)+1)
print ""
BC
DEF
GHIJ
KLMNO
ch='A'
for i in range(1,6):
for j in range(1,i+1):
print ch,
ch=chr(ord(ch)+1)
print ""
Program:
8) Write a program that takes input string user and display that string if string contains
at least one Uppercase character, one Lowercase character and onedigit.
Program:
pwd=input("Enter the password:")
u=False
l=False
d=False
if pwd[i].isupper():
for i in range(0,len(pwd)):
u=True
elifpwd[i].islower():
l=True
elifpwd[i].isdigit():
d=True
Output-1:
Enter the password:"Mothi556"
******Mothi556******
if u==True and l==True and d==True:
Output-2: print pwd.center(20,"*")
Enter the password:"mothilal"
else: Password
Invalid
print "Invalid Password"
9) Write a program to print sum of digits.
Program:
n=input("Enter the number: ")
sum=0
while n>0:
r=n%10
sum+=r
n=n/10
Output:
Output:
ifsum==t:
Enter the number: 153
print "ARMSTRONG"
ARMSTRONG
else:a program to take input string from the user and print that string after
11) Write
removingovals.
print "NOT ARMSTRONG"
st=input("Enter the
string:") st2=""
forifi iinnot
st:in "aeiouAEIOU":
st2=st2+i
Program:
Output:
print st2
Enter the string:"Welcome to you"
Wlcm t y
MODULE – III: CONTAINER DATA TYPES
Knowledge Level
Course Outcomes (Bloom‟s
Taxonomy)
CO 3 Demonstrate indexing and slicing mechanisms for extracting a Apply
portion of data in a sequence.
CO 4 Understandnative data types like list, set, tuple, dictionary use Understand
them in data processing applications.
MODULE – III:
Arrays:
An array is an object that stores a group of elements of same datatype.
Arrays can store only one type of data. It means, we can store only integer type elements
or only float type elements into an array. But we cannot store one integer, one float and
one character type element into the samearray.
Arrays can increase or decrease their size dynamically. It means, we need not declare the
size of the array. When the elements are added, it will increase its size and when the
elements are removed, it will automatically decrease its size inmemory.
Advantages:
Arrays are similar to lists. The main difference is that arrays can store only one type of
elements; whereas, lists can store different types of elements. When dealing with a huge
number of elements, arrays use less memory than lists and they offer faster execution than
lists.
The size of the array is not fixed in python. Hence, we need not specify how many
elements we are going to store into an array in thebeginning.
Arrays can grow or shrink in memory dynamically (duringruntime).
Arrays are useful to handle a collection of elements like a group of numbers orcharacters.
Methods that are useful to process the elements of any array are available in „array‟
module.
Creating an array:
Syntax:
Example:
The type code character should be written in single quotes. After that the elements
should be written in inside the square braces [ ] as
a = array ( „i‟, [4,8,-7,1,2,5,9] )
Importing the Array Module:
There are two ways to import the array module into our program.
The first way is to import the entire array module using import statement as,
import array
when we import the array module, we are able to get the „array‟ class of that module that
helps us to create an array.
a = array.array(‘i’, [4,8,-7,1,2,5,9] )
Here the first „array‟ represents the module name and the next „array‟ represents the class
name for which the object is created. We should understand that we are creating our array as
an object of array class.
10 20 30 40 50
a[0] a[1] a[2] a[3] a[4]
Example:
from array import *
a=array('i', [10,20,30,40,50,60,70])
print "length is",len(a)
print " 1st position character", a[1]
print "Characters from 2 to 4", a[2:5]
print "Characters from 2 to end", a[2:]
print "Characters from start to 4",a[:5]
print "Characters from start to end",a[:]
a[3]=45
a[4]=55
print "Characters from start to end after modifications ",a[:]
Output:
length is 7
1st position character 20
Characters from 2 to 4 array('i', [30, 40, 50])
Characters from 2 to end array('i', [30, 40, 50, 60, 70])
Characters from start to 4 array('i', [10, 20, 30, 40, 50])
Characters from start to end array('i', [10, 20, 30, 40, 50, 60, 70])
Characters from start to end after modifications array('i', [10, 20, 30, 45, 55, 60, 70])
Array Methods:
Method Description
a.append(x) Adds an element x at the end of the existing array a.
a.count(x) Returns the number of occurrences of x in the array a.
a.extend(x) Appends x at the end of the array a. „x‟ can be another array or
iterable object.
a.fromfile(f,n) Reads n items from from the file object f and appends at the end of
the array a.
a.fromlist(l) Appends items from the l to the end of the array. l can be any list or
iterable object.
a.fromstring(s) Appends items from string s to end of the array a.
a.index(x) Returns the position number of the first occurrence of x in the array.
Raises „ValueError‟ if not found.
a.pop(x) Removes the item x from the array a and returns it.
a.pop( ) Removes last item from the array a
a.remove(x) Removes the first occurrence of x in the array. Raises „ValueError‟
if not found.
a.reverse( ) Reverses the order of elements in the array a.
a.tofile( f ) Writes all elements to the file f.
a.tolist( ) Converts array „a‟ into a list.
a.tostring( ) Converts the array into a string.
1) Write a program to perform stack operations using array.
Program:
import sys
from array import
* a=array('i',[])
print
while "\n1.PUSH 2.POP 3.DISPLAY 4.EXIT"
True:
ch=input("Enter Your Choice: ")
if ch==1:
ele=input("Enter element:
") a.append(ele)
print
"Inserted"
elifch==2:
if len(a)==0:
if len(a)==0:
ele=input("Enter element:
") a.append(ele)
elifch==2:
if len(a)==0:
elifch==3:
if len(a)==0:
LIST:
A list is similar to an array that consists of a group of elements or items. Just like an
array, a list can store elements. But, there is one major difference between an array and a list.
An array can store only one type of elements whereas a list can store different types of
elements. Hence lists are more versatile and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values between
square brackets.
student = [556, ―Mothi‖, 84, 96, 84, 75, 84 ]
We can create empty list without any elements by simply writing empty square
brackets as: student=[ ]
We can create a list by embedding the elements inside a pair of square braces []. The
elements in the list should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. To view the elements of a list as a whole, we
can simply pass the list name to print function.
Ex:
student = [556, ―Mothi‖, 84, 96, 84, 75, 84 ] print
student
print student[0] # Access 0th element
print student[0:2] # Access 0th to 1st elements
print student[2: ] # Access 2nd to end of list elements print
student[ :3] # Access starting to 2nd elements print student[ : ] #
Access starting to ending elements print student[-1] # Access last
index value
print student[-1:-7:-1] # Access elements in reverse order
Output:
[556, ―Mothi‖, 84, 96, 84, 75, 84]
Mothi
[556, ―Mothi‖]
[84, 96, 84, 75, 84]
[556, ―Mothi‖, 84]
[556, ―Mothi‖, 84, 96, 84, 75, 84]
84
[84, 75, 84, 96, 84, ―Mothi‖]
Output:
12345
When we clone a list like this, a separate copy of all the elements is stored into „y‟.
Thelists„x‟and„y‟areindependentlists.Hence,anymodificationsto„x‟willnotaffect„y‟ and
viceversa.
Methods in Lists:
Method Description
lst.index(x) Returns the first occurrence of x in the list.
lst.append(x) Appends x at the end of the list.
lst.insert(i,x) Inserts x to the list in the position specified by i.
lst.copy() Copies all the list elements into a new list and returns it.
lst.extend(lst2) Appends lst2 to list.
lst.count(x) Returns number of occurrences of x in the list.
lst.remove(x) Removes x from the list.
lst.pop() Removes the ending element from the list.
lst.sort() Sorts the elements of list into ascending order.
lst.reverse() Reverses the sequence of elements in the list.
lst.clear() Deletes all elements from the list.
max(lst) Returns biggest element in the list.
min(lst) Returns smallest element in the list.
Example:
lst=[10,25,45,51,45,51,21,65]
lst.insert(1,46)
printlst # [10,46,25,45,51,45,51,21,65]
printlst.count(45) #2
Nested Lists:
A list within another list is called a nested list. We know that a list contains several
elements. When we take a list as an element in another list, then that list is called a nested list.
Example:
a=[10,20,30]
b=[45,65,a]
printb # display [ 45, 65, [ 10, 20, 30 ] ]
printb[1] # display65
printb[2] # display [ 10, 20, 30 ]
printb[2][0] # display10
print b[2][1] # display 20 print b[2][2]
# display 30 for x in b[2]:
print x, # display 10 2030
Nested Lists as Matrices:
Suppose we want to create a matrix with 3 rows 3 columns, we should create a list
with 3 other lists as:
mat = [ [ 1, 2, 3 ] , [ 4, 5, 6 ] , [ 7, 8, 9 ] ]
Here, „mat‟ is a list that contains 3 lists which are rows of the „mat‟ list. Each row
contains again 3 elements as:
[ [ 1, 2, 3], # first row
[ 4, 5, 6], # second row
[ 7, 8, 9]] # third row
Example:
mat=[[1,2,3],[4,5,6],[7,8,9]]
for r in mat:
print r
print ""
m=len(mat)
n=len(mat[0])
for i in range(0,m):
for j in range(0,n):
print mat[i][j],
One of the main use of nested lists is that they can be used to represent matrices. A
print ""
matrix represents a group of elements arranged in several rows and columns. In python,
matrices are created
print ""as 2D arrays or using matrix object in numpy. We can also create a
matrix using nested lists.
for i in range(0,m1):
for j in range(0,n1):
c[i][j]= a[i][j]+b[i][j]
for i in range(0,m1):
for j in range(0,n1):
print "\t",c[i][j],
print ""
Q) Write a program to perform multiplication of two matrices.
a=[[1,2,3],[4,5,6]]
b=[[4,5],[7,8],[1,2]]
c=[[0,0],[0,0]]
m1=len(a) n1=len(a[0])
m2=len(b) n2=len(b[0])
for i in range(0,m1):
for j in range(0,n2):
for k in range(0,n1):
c[i][j] +=a[i][k]*b[k][j]
for i in range(0,m1):
for j in range(0,n2):
print "\t",c[i][j],
print ""
List Comprehensions:
List comprehensions represent creation of new lists from an iterable object (like a list,
set, tuple, dictionary or range) that satisfy a given condition. List comprehensions contain
very compact code usually a single statement that performs the task.
We want to create a list with squares of integers from 1 to 100. We can write codeas: squares=[ ]
for i in range(1,11):
squares.append(i**2)
The preceding code will create „squares‟ list with the elements as shown below:
[ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The previous code can rewritten in a compact way as:
squares=[x**2 for x inrange(1,11)]
This is called list comprehension. From this, we can understand that a list
comprehension consists of square braces containing an expression (i.e., x**2). After the
expression, a fro loop and then zero or more if statements can be written.
[ expression for item1 in iterable if statement1
for item1 in iterable if statement2
for item1 in iterable if statement3…..]
Example:
Even_squares = [ x**2 for x in range(1,11) ifx%2==0]
It will display the list even squares aslist.
[ 4, 16, 36, 64, 100]
TUPLE:
A Tuple is a python sequence which stores a group of elements or items. Tuples are
similar to lists but the main difference is tuples are immutable whereas lists are mutable.
Once we create a tuple we cannot modify its elements. Hence, we cannot perform operations
like append(), extend(), insert(), remove(), pop() and clear() on tuples. Tuples are generally
used to store data which should not be modified and retrieve that data ondemand.
Creating Tuples:
We can create a tuple by writing elements separated by commas inside parentheses( ).
The elements can be same datatype or different types.
To create an empty tuple, we can simply write empty parenthesis, as: tup=( )
To create a tuple with only one element, we can, mention that element in parenthesis
and after that a comma is needed. In the absence of comma, python treats the element assign
ordinary data type.
tup = (10) tup = (10,)
print tup # display 10 print tup # display 10
print type(tup) # display <type „int‟> print type(tup) # display<type„tuple‟>
To create a tuple with different types of elements:
tup=(10, 20, 31.5, „Gudivada‟)
If we do not mention any brackets and write the elements separating them by comma,
then they are taken by default as a tuple.
tup= 10, 20, 34, 47
It is possible to create a tuple from a list. This is done by converting a list into a tuple
using tuple function.
n=[1,2,3,4]
tp=tuple(n)
printtp # display(1,2,3,4)
Another way to create a tuple by using range( ) function that returns a sequence.
t=tuple(range(2,11,2))
printt # display(2,4,6,8,10)
Accessing the tuple elements:
Accessing the elements from a tuple can be done using indexing or slicing. This is
same as that of a list. Indexing represents the position number of the element in the tuple. The
position starts from 0.
tup=(50,60,70,80,90)
printtup[0] # display50
printtup[1:4] # display(60,70,80)
print tup[-1] # display90
printtup[-1:-4:-1] # display (90,80,70)
printtup[-4:-1] # display(60,70,80)
Updating and deleting elements:
Tuples are immutable which means you cannot update, change or delete the values of
tuple elements.
Example-1:
Example-2:
However, you can always delete the entire tuple by using the statement.
Note that this exception is raised because you are trying print the deleted element.
Operations on tuple:
Operation Description
len(t) Return the length of tuple.
tup1+tup2 Concatenation of two tuples.
Tup*n Repetition of tuple values in n number of times.
x in tup Return True if x is found in tuple otherwise returns False.
cmp(tup1,tup2) Compare elements of both tuples
max(tup) Returns the maximum value in tuple.
min(tup) Returns the minimum value in tuple.
tuple(list) Convert list into tuple.
Returns how many times the element „x‟ is found in
tup.count(x)
tuple.
Returns the first occurrence of the element „x‟ in tuple.
tup.index(x)
Raises ValueError if „x‟ is not found in the tuple.
Sorts the elements of tuple into ascending order.
sorted(tup)
sorted(tup,reverse=True) will sort in reverse order.
cmp(tuple1, tuple2)The method cmp() compares elements of two tuples.
Syntax
cmp(tuple1, tuple2)
Parameters
tuple1 -- This is the first tuple to be compared
tuple2 -- This is the second tuple to be compared
Return Value
If elements are of the same type, perform the compare and return the result. If elements are
different types, check to see if they are numbers.
If numbers, perform numeric coercion if necessary andcompare.
If either element is a number, then the other element is "larger" (numbers are
"smallest").
Otherwise, types are sorted alphabetically byname.
If we reached the end of one of the tuples, the longer tuple is "larger." If we exhaust both
tuples and share the same data, the result is a tie, meaning that 0 is returned.
Example:
tuple1 = (123,'xyz')
tuple2 = (456,'abc') #display-1
print cmp(tuple1, tuple2) #display1
Nested Tuples:
print cmp(tuple2, tuple1)
Python allows you to define a tuple inside another tuple. This is called a nested tuple.
students=((―RAVI‖, ―CSE‖, 92.00), (―RAMU‖, ―ECE‖, 93.00), (―RAJA‖, ―EEE‖, 87.00))
for i in students:
print i
Output: (―RAVI‖, ―CSE‖, 92.00)
We canprints # display
also convert tuple set(into
or string * 1, set.
2.5, “abc” +)
tup= ( 1, 2, 3, 4, 5)
print set(tup) # set( [ 1, 2, 3, 4, 5 ] )
str=―MOTHILAL‖
printstr # set( [ 'i', 'h', 'm', 't', 'o' ])
Operations on set:
Sno Operation Result
1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issubset(t) (or)
4 s <= t test whether every element in s is in t
s.issuperset(t) (or)
5 s >= t test whether every element in t is in s
s.symmetric_difference(t) (or)
11 s ^ t new set with elements in either s or t but not both
Note:
To create an empty set you cannot write s={}, because python will make this as a
directory. Therefore, to create an empty set use set( ) function.
s=set() s={}
printtype(s) # display<type„set‟> print type(s) # display <type„dict‟>
Updating a set:
Since sets are unordered, indexing has no meaning. Set operations do not allow users
to access or change an element using indexing or slicing.
Dictionary:
A dictionary represents a group of elements arranged in the form of key-value pairs.
The first element is considered as „key‟ and the immediate next element is taken as its
„value‟. The key and its value are separated by a colon (:). All the key-value pairs in a
dictionary are inserted in curly braces {}.
d= { „Regd.No‟: 556, „Name‟:‟Mothi‟, „Branch‟: „CSE‟ }
Here, the name of dictionary is „dict‟. The first element in the dictionary is a string
„Regd.No‟. So, this is called „key‟. The second element is 556 which is taken as its „value‟.
Example:
d=,„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟-
printd*„Regd.No‟+ # 556
printd*„Name‟+ # Mothi
To access the elements of a dictionary, we should not use indexing or slicing. For example,
printd*„Branch‟+
dict[0] or dict[1:3] etc. expressions will give #error.
CSE To access the value associated with a key,
we can mention the key name inside the square braces, as: dict[„Name‟].
If we want to know how many key-value pairs are there in a dictionary, we can use the len( )
function, as shown
d={„Regd.No‟:556,„Name‟:‟Mothi‟,„Branch‟:„CSE‟} printlen(d)
#3
We can also insert a new key-value pair into an existing dictionary. This is done by
mentioning the key and assigning a value to it.
d={'Regd.No':556,'Name':'Mothi','Branch':'CSE'}
printd #{'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}
d['Gender']="Male"
printd # {'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi', 'Regd.No': 556}
Suppose, we want to delete a key-value pair from the dictionary, we can use del statementas:
del dict[„Regd.No‟] #{'Gender': 'Male', 'Branch': 'CSE', 'Name': 'Mothi'}
To Test whether a „key‟ is available in a dictionary or not, we can use „in‟ and „not in‟
operators. These operators return either True orFalse.
„Name‟ind #checkif„Name‟isakeyindandreturnsTrue/False
We can use any datatypes for value. For example, a value can be a number, string, list, tuple
or another dictionary. But keys should obey therules:
Keys should be unique. It means, duplicate keys are not allowd. If we enter same key
again, the old key will be overwritten and only the new key will beavailable.
emp={'nag':10,'vishnu':20,'nag':20}
print emp # {'nag': 20, 'vishnu': 20}
Keys should be immutable type. For example, we can use a number, string or tuples
as keys since they are immutable. We cannot use lists or dictionaries as keys. If they
are used as keys, we will get„TypeError‟.
emp={['nag']:10,'vishnu':20,'nag':20}
Traceback (most recent call last):
for loop is very convenient to retrieve the elements of a dictionary. Let‟s take asimple
dictionary that contains color code and its nameas:
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
Here, „r‟, „g‟, „b‟ represents keys and „RED‟, „GREEN‟, „BLUE‟ and „WHITE‟
indicate values.
colors = { 'r':"RED", 'g':"GREEN", 'b':"BLUE", 'w':"WHITE" }
for k incolors:
print k # displays only keys for k
incolors:
print colors[k] # keys to to dictionary and display the values
Converting Lists into Dictionary:
When we have two lists, it is possible to convert them into a dictionary. For example,
we have two lists containing names of countries and names of their capital cities.
There are two steps involved to convert the lists into a dictionary. The first step is to
create a „zip‟ class object by passing the two lists to zip( ) function. The zip( ) function is
useful to convert the sequences into a zip class object. The second step is to convert the zip
object into a dictionary by using dict( ) function.
Example:
countries = [ 'USA', 'INDIA', 'GERMANY', 'FRANCE' ]
d=dict(z)
Output:print d
{'GERMANY': 'Berlin', 'INDIA': 'New Delhi', 'USA': 'Washington', 'FRANCE': 'Paris'}
Converting Strings into Dictionary:
When a string is given with key and value pairs separated by some delimiter like
a comma ( , ) we can convert the string into a dictionary and use it as dictionary.
s="Vijay=23,Ganesh=20,Lakshmi=19,Nikhi
l=22" s1=s.split(',')
s2=[]
d={}
for i in s1:
s2.append(i.spli
t('='))
print d
{'Ganesh': '20', 'Lakshmi': '19', 'Nikhil': '22', 'Vijay': '23'}
Q) A Python program to create a dictionary and find the sum of values.
d={'m1':85,'m3':84,'eng':86,'c':91}
sum=0
for i in d.values():
Q) A Python sum+=i
program to create a dictionary with cricket player‟s names and scores in a
match. Also we are retrieving runs by entering the player‟s name.
printsum # 346
n=input("Enter How many players? ")
d={}
for i in range(0,n):
k=input("Enter Player name: ")
v=input("Enter score: ") d[k]=v
print d
Knowledge Level
Course Outcomes (Bloom‟s
Taxonomy)
CO 5 Compare and contrast mutable and immutable objects and Understand
understand the state change of objects during runtime.
CO 6 Understand passing of parameters and arguments in functions Understand
to do modular programming.
MODULE – IV
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you
may see characters on your screen, internally it is stored and manipulated as a combination of
0s and 1s.
This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encodings used.
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
Hello
Hello
Hello
Hello, welcome to the world of Python
How to access characters in a string?
We can access individual characters using indexing and a range of characters using slicing.
Index starts from 0. Trying to access a character out of index range will raise an IndexError.
The index must be an integer. We can't use floats or other types, this will result into
TypeError.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a
range of items in a string by using the slicing operator :(colon).
#first character
print('str[0] = ', str[0])
#last character
print('str[-1] = ', str[-1])
str = programiz
str[0] = p
str[-1] = z
str[1:5] = rogr
str[5:-2] = am
If we try to access an index out of the range or use numbers other than an integer, we will get
errors.
If we want to access a range, we need the index that will slice the portion from the string.
To learn more about the data types available in Python visit: Python Data Types
The + operator does this in Python. Simply writing two string literals together also
concatenates them.
The * operator can be used to repeat the string for a given number of times.
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
When we run the above program, we get the following output:
3 letters found
String Membership Test
We can test if a substring exists within a string or not, using the keyword in.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns
an enumerate object. It contains the index and value of all the items in the string as pairs. This
can be useful for iteration.
str = 'cold'
# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)
#character count
print('len(str) = ', len(str))
When we run the above program, we get the following output:
An escape sequence starts with a backslash and is interpreted differently. If we use a single
quote to represent a string, all the single quotes inside the string must be escaped. Similar is
the case with double quotes. Here is how it can be done to represent the above text.
>>> print("C:\\Python32\\Lib")
C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or
displayed in the exponent format. There are tons of formatting you can use. Visit here for all
the string formatting available with the format() method.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Common Python String Methods
There are numerous methods available with the string object. The format() method that we
mentioned above is one of them. Some of the commonly used methods are lower(), upper(),
join(), split(), find(), replace() etc. Here is a complete list of all the built-in methods to work
with strings in Python.
>>> "PrOgRaMiZ".lower()
'programiz'
>>> "PrOgRaMiZ".upper()
'PROGRAMIZ'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'STRINGS AND FUNCTIONS
FUNCTIONS:
A function is a block of organized, reusable code that is used to perform a single,
related action.
Once a function is written, it can be reused as and when required. So, functions are also
called reusablecode.
Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks called
modules.
Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated into the
software.
When there is an error in the software, the corresponding function can be modified
without disturbing the other functions in thesoftware.
The use of functions in a program will reduce the length of theprogram.
As you already know, Python gives you many built-in functions like sqrt( ), etc. but you can
also create your own functions. These functions are called user-definedfunctions.
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Example:
def add(a,b):
"""This function sum thenumbers"""
c=a+b
print c
return
Here, „def’ represents starting of function. „add’ is function name. After this name,
parentheses ( ) are compulsory as they denote that it is a function and not a variable or
something else. In the parentheses we wrote two variables „a‟ and „b‟ these variables are
called „parameters‟. A parameter is a variable that receives data from outside a function. So,
this function receives two values from outside and those are stored in the variables „a‟ and
„b‟. After parentheses, we put colon (:) that represents the beginning of the function body.
The function body contains a group of statements called „suite‟.
Calling Function:
A function cannot run by its own. It runs only when we call it. So, the next step is to
call function using its name. While calling the function, we should pass the necessary values
to the function in the parentheses as:
add(5,12)
Here, we are calling „add‟ function and passing two values 5 and 12 to that function.
When this statement is executed, the python interpreter jumps to the function definition and
copies the values 5 and 12 into the parameters „a‟ and „b‟ respectively.
Example:
def add(a,b):
print c
add(5,12)
Returning Results # 17 a function:
from
We can return the result or output from the function using a „return‟ statement in the
function body. When a function does not return any result, we need not write the return
statement in the body of the function.
Q) Write a program to find the sum of two numbers and return the result from the
function.
def add(a,b):
return c
print add(5,12) #17
print add(1.5,6)#6.5
Returning multiple values from a function:
A function can returns a single value in the programming languages like C, C++ and
JAVA. But, in python, a function can return multiple values. When a function calculates
multiple results and wants to return the results, we can use return statement as:
return a, b, c
Here, three values which are in „a‟, „b‟ and „c‟ are returned. These values are returned bythe
function as a tuple. To grab these values, we can three variables at the time of calling the
functionas:
x, y, z = functionName( )
Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.
Example:
def calc(a,b):
c=a+b
d=a-b
e=a*b
return
c,d,ex,y,z=calc(5,8
) print
"Addition=",x
print "Subtraction=",y
print "Multiplication=",z
Functions are First Class Objects:
In Python, functions are considered as first class objects. It means we can use functions as
perfect objects. In fact when we create a function, the Python interpreter internally creates an
object. Since functions are objects, we can pass a function to another function just like we
pass an object (or value) to a function. The following possibilities are:
It is possible to assign a function to avariable.
It is possible to define one function inside anotherfunction.
It is possible to pass a function as parameter to anotherfunction.
It is possible that a function can return another function.
To understand these points, we will take a few simpleprograms.
Q) A python program to see how to assign a function to a variable. def
display(st):
return "hai"+st
x=display("cse")
printx Output:haicse
Q) A python program to know how to define a function inside another function. def
display(st):
def message():
return "how r u?"
res=message()+st
return res
x=display("cse")
printx Output: how r u?cse
Q) A python program to know how to pass a function as parameter to another function. def
display(f):
return "hai"+f def
message():
return "how r u?"
fun=display(message())
printfun Output: haihow ru?
Q) A python program to know how a function can return anotherfunction.
defdisplay():
def message():
return "how r u?"
return message fun=display()
printfun() Output: how ru?
Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and
any modifications to that value will not reflect outside the function. In python, the values are
sent to functions by means of object references. We know everything is considered as an
object in python. All numbers, strings, tuples, lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a memory block
where we can store some value. In this case, an object with the value „10‟ is created in
memoryforwhichaname„x‟isattached.So,10 istheobject and„x‟isthenameortaggiven to that
object. Also, objects are created on heap memory which is a very huge memory that depends
on the RAM of our computer system.
Example: A Python program to pass an integer to a function and modifyit.
defmodify(x):
x=15
print "inside",x,id(x)
x=10
modify(x)
print "outside",x,id(x)
Output:
inside 15 6356456
outside 10 6356516
From the output, we can understand that the value of „x‟ in the function is 15 and that is not
available outside the function. When we call the modify( ) function and pass „x‟ as:
modify(x)
We should remember that we are passing the object references to the modify( ) function. The
object is 10 and its references name is „x‟. This is being passed to the modify( ) function.
Inside the function, we are using:
x=15
This means another object 15 is created in memory and that object is referenced by
the name „x‟. The reason why another object is created in the memory is that the integer
objects are immutable (not modifiable). So in the function, when we display „x‟ value, it will
display 15. Once we come outside the function and display „x‟ value, it will display numbers
of „x‟ inside and outside the function, and we see different numbers since they are different
objects.
In python, integers, floats, strings and tuples are immutable. That means their data
cannot be modified. When we try to change their value, a new object is created with the
modified value.
b) KeywordArguments:
Keyword arguments are arguments that identify the parameters by their names. For
example, the definition of a function that displays grocery item and its price can be written
as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which
value is for what. For example,
grocery(item=‟sugar‟, price=50.75)
Here,wearementioningakeyword„item‟anditsvalueandthenanotherkeyword„price‟and its
value. Please observe these keywords are nothing but the parameter names which receive
these values. We can change the order of the argumentsas:
grocery(price=88.00, item=‟oil‟)
In this way, even though we change the order of the arguments, there will not be any problem
as the parameter names will guide where to store that value.
def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar
price= 50.75
item= oil price=
88.0
c) DefaultArguments:
We can mention some defaultvalue for the function parameters in the definition.
Let‟s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the second
argument is „price‟ and its default value is mentioned to be 40.00. at the time of calling this
function, if we do not pass „price‟ value, then the default value of 40.00 is taken. If we
mention the „price‟ value, then that mentioned value is utilized. So, a default argument is an
argument that assumes a default value if a value is not provided in the function call for that
argument.
Example: def grocery(item,price=40.00):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75)
grocery(item="oil")
Output:
item= sugar
price= 50.75
item= oil
price= 40.0
d) Variable LengthArguments:
Sometimes, the programmer does not know how many values a function may receive. In that
case, the programmer cannot decide how many arguments to be given in the function
definition. for example, if the programmer is writing a function to add two numbers, he/she
can write:
add(a,b)
But, the user who is using this function may want to use this function to find sum of three
numbers. In that case, there is a chance that the user may provide 3 arguments to this function
as:
add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the programmer want to
develop a function that can accept „n‟ arguments, that is also possible in python. For this
purpose, a variable length argument is used in the function definition. a variable length
argument is an argument that can accept any number of values. The variable length argument
is written with a „*‟ symbol before it in the function definition as:
def add(farg, *args):
here, „farg‟ is the formal; argument and „*args‟ represents variable length argument. We can
pass 1 or more values to this „*args‟ and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print "sum is",sum+farg
add(5,10)
add(5,10,20)
add(5,10,20,30)
Output:
sum is15
sum is35
sum is65
Examples of reduce ( )
Determining the maximum of a list of numerical values by using reduce:
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>
Calculating the sum of the numbers from 1 to 100:
>>> reduce(lambda x, y: x+y, range(1,101)) 5050
Function Decorators:
A decorator is a function that accepts a function as parameter and returns a function.
A decorator takes the result of a function, modifies the result and returns it. Thus decorators
are useful to perform some additional processing required by afunction.
The following steps are generally involved in creation of decorators:
We should define a decorator function with another function name asparameter.
We should define a function inside the decorator function. This function actually modifies
or decorates the value of the function passed to the decoratorfunction.
Return the inner function that has processed or decorated thevalue.
Example-1:
def decor(fun):
def inner():
value=fun()
return value+2
return inner def
num():
return 10
result=decor(num) print
result()
Output:
12
To apply the decorator to any function, we can use „@‟ symbol and decorator name just
above the functiondefinition.
Example-2: A python program to create two decorators.
def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def decor2(fun):
def inner():
value=fun()
return value*2
return inner
def num():
return 10
result=decor1(decor2(num))
print result()
Output:
22
Example-3: A python program to create two decorators to the same function using „@‟
symbol.
def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def decor2(fun):
def inner():
value=fun()
return value*2
return inner
@decor1
@decor2
def num():
return 10
print num()
Output:
22
Function Generators:
A generator is a function that produces a sequence of results instead of a single value.
„yield‟ statement is used to return the value. def
mygen(n):
i=0
while i <n:
yieldi
i +=1
g=mygen(6) for
i in g:
print i,
Output:
012345
Note: „yield‟ statement can be used to hold the sequence of results and return it.
Modules:
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix.py appended. Within a module, the module‟s name (as a string)
is available as the value of the global variable __name. For instance, use your favourite text
editor to create a file called fibo.py in the current directory with the followingcontents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0,1
while b <n:
printb,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result =[]
a, b = 0,1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
>>>import fibo
This does not enter the names of the functions defined in fibodirectly in the current symbol
table; it only enters the module name fibothere. Using the module name you can access the
functions:
>>>fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55,89]
>>>fibo.name
'fibo'
from statement:
A module can contain executable statements as well as function definitions. These
statements are intended to initialize the module. They are executed only the first time the
module name is encountered in an import statement. (They are also run if the file is
executed as ascript.)
Each module has its own private symbol table, which is used as the global symbol table by
all functions defined in the module. Thus, the author of a module can use global variables
in the module without worrying about accidental clashes with a user‟s global variables. On
the other hand, if you know what you are doing you can touch a module‟s global variables
with the same notation used to refer to its functions,modname.itemname.
Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module
names are placed in the importing module‟s global symbol table.
There is a variant of the import statement that imports names from a module directly into
the importing module‟s symbol table. Forexample:
>>> from fibo import fib, fib2
>>>fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local
symbol table (so in the example, fibo is not defined).
The requests and flask Packages are downloaded from internet. To download install the
packages follow the commands
Installation of requestsPackage:
Command: cd C:\Python27\Scripts
Installation of flaskPackage:
Command: cd C:\Python27\Scripts
Knowledge Level
Course Outcomes (Bloom‟s
Taxonomy)
CO 2 Visualize the capabilities of procedural as well as object- Understand
oriented programming in Python and demonstrate the same in
real world scenario.
CO 7 Understand the concepts of inheritance and polymorphism for Understand
code reusability and extensibility.
CO 8 Make use of appropriate modules for solving real-time Apply
problems.
CO 9 Apply string handling mechanisms to do automated memory Apply
management and reduce out-of-bounds accesses.
CO 10 Extend the knowledge of Python programming to build Understand
successful career in software development.
MODULE – V: CLASSES AND OBJECTS
MODULE – V
CLASSES AND OBJECTS
Python has been an object-oriented language since it existed. Because of this, creating
and using classes and objects are downright easy. This chapter helps you become an expert in
using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming,
you may want to consult an introductory course on it or at least a tutorial of some sort so that
you have a grasp of the basic concepts.
However, here is small introduction of Object-Oriented Programming (OOP) to bring
you at speed:
Overview of OOP Terminology
Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables
and instance variables) and methods, accessed via dotnotation.
Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not
used as frequently as instance variablesare.
Data member: A class variable or instance variable that holds data associated with a
class and itsobjects.
Function overloading: The assignment of more than one behaviourto a particular
function. The operation performed varies by the types of objects or argumentsinvolved.
Instance variable: A variable that is defined inside a method and belongs only to the
current instance of aclass.
Inheritance: The transfer of the characteristics of a class to other classes that are
derived fromit.
Instance: An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the classCircle.
Instantiation: The creation of an instance of aclass.
Method: A special kind of function that is defined in a classdefinition.
Object: A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) andmethods.
Operator overloading: The assignment of more than one function to a particular
operator.
Creation of Class:
A class is created with the keyword class and then writing the classname. The simplest form
of class definition looks like this:
class ClassName:
<statement-1>
.
.
<statement-N>
Class definitions, like function definitions (def statements) must be executed before
they have any effect. (You could conceivably place a class definition in a branch of an if
statement, or inside a function.)
Example: class Student:
definit(self):
self.name="hari"
self.branch="CSE"
def display(self):
print self.name
print self.branch
For example, If we „Student‟ class, we can write code in the class that specifies the
attributes and actions performed by anystudent.
Observer that the keyword class is used to declare a class. After this, we should write
the class name. So, „Student‟ is our class name. Generally, a class name should start
with a capital letter, hence „S‟ is a capital in„Student‟.
In the class, we have written the variables and methods. Since in python, we cannot
declare variables, we have written the variables inside a special method, i.e. init (). This
method is used to initialize the variables. Hence the name„init‟.
The method name has two underscores before and after. This indicates that this method
is internally defined and we cannot call this methodexplicitly.
Observe the parameter „self‟ written after the method name in the parentheses. „self‟ is
a variable that refers to current classinstance.
When we create an instance for the Student class, a separate memory block is allocated
on the heap and that memory location is default stored in„self‟.
The instance contains the variables „name‟ and „branch‟ which are called instance
variables. To refer to instance variables, we can use the dot operator notation along
with self as „self.name‟ and„self.branch‟.
The method display ( ) also takes the „self‟ variable as parameter. This method displays
the values of variables by referring them using„self‟.
The methods that act on instances (or objects) of a class are called instance methods.
Instance methods use „self‟ as the first parameter that refers to the location of the
instance in thememory.
Writing a class like this is not sufficient. It should be used. To use a class, we should
create an instance to the class. Instance creation represents allotting memory necessary
to store the actual data of the variables, i.e., „hari‟,„CSE‟.
To create an instance, the following syntax is used:
instancename = Classname()
So, to create an instance to the Student class, we can write as:
s1 = Student ()
Here „s1‟ represents the instance name. When we create an instance like this, the
following steps will take placeinternally:
1. First of all, a block of memory is allocated on heap. How much memory is to be
allocated is decided from the attributes and methods available in the Studentclass.
2. After allocating the memory block, the special method by the name „init(self)‟ is
called internally. This method stores the initial data into the variables. Since this
method is useful to construct the instance, it is called„constructor‟.
3. Finally, the allocated memory location address of the instance is returned into „s1‟
variable. To see this memory location in decimal number format, we can use id( )
function as id(s1).
Self variable:
„self‟ is a default variable that contains the memory address of the instance of the
current class. When an instance to the class is created, the instance name cotains the memory
locatin of the instance. This memory location is internally passed to „self‟.
For example, we create an instance to student class as:
s1 = Student( )
Here, „s1‟ contains the memory address of the instance. This memory address is
internally and by default passed to „self‟ variable. Since „self‟ knows the memory address of
the instance, it can refer to all the members of the instance.
We use „self‟ in two eays:
The self variableis used as first parameter in the constructoras:
definit(self):
In this case, „self‟ can be used to refer to the instance variables inside the
constructor.
„self‟ can be used as first parameter in the instance methodsas:
def display(self):
Here, display( ) is instance method as it acts on the instance variables. If this
method wants to act on the instance variables, it should know the memory location
of the instance variables. That memory location is by default available to the
display( ) method through „self‟.
Constructor:
A constructor is a special method that is used to initialize the instance variables of a
class. In the constructor, we create the instance variables and initialize them with some
starting values. The first parameter of the constructor will be „self‟ variable that contains the
memory address of the instance.
definit( self ): self.name
= "hari" self.branch
="CSE"
Here, the constructor has only one parameter, i.e. „self‟ using „self.name‟and
„self.branch‟, we can access the instance variables of the class. A constructor is called at the
time of creating an instance. So, the above constructor will be called when we create an
instance as:
s1 = Student()
Let‟s take another example, we can write a constructor with some parameters in
additionto„self‟as:
definit( self , n = „ ‟ , b = „ ‟ ):
self.name = n
self.branch = b
Here, the formal arguments are „n‟ and „b‟ whose default values are given as „‟
(None) and „‟ (None). Hence, if we do not pass any values to constructor at the time of
creating an instance, the default values of those formal arguments are stored into name and
branch variables. For example,
s1 = Student( )
Since we are not passing any values to the instance, None and None are stored into
name and branch. Suppose, we can create an instance as:
s1 = Student( “mothi”, “CSE”)
In this case, we are passing two actual arguments: ―mothi‖ and ―CSE‖ to the Studentinstance.
Example:
class Student:
definit(self,n='',b=''):
self.name=n
self.branch=b
def display(self):
print "Hi",self.name
print "Branch", self.branch
s1=Student()
s1.display()
print― ------------------------------ ‖
s2=Student("mothi","CSE")
s2.display()
print― ------------------------------ ‖
Output:
Hi
Branch
------------------------------
Hi mothi
Branch CSE
------------------------------
Types of Variables:
We know that a single copy of class variable is shared by all the instances. So, if the class
variable is modified in the class namespace, since same copy of the variable is modified, the
modified copy is available to all the instances.
b) Instance namespace:
Every instance will have its own name space, called „instance namespace‟. In the
instance namespace, the names are mapped to instance variables. Every instance will have its
own namespace, if the class variable is modified in one instance namespace, it will not affect
the variables in the other instance namespaces. To access the class variable at the instance
level, we have to create instance first and then refer to the variable as instancename.variable.
Example:
classStudent:
n =10
s1 = Student( )
prints1.n # displays 10
s1.n +=1
prints1.n # displays11
s2 = Student( )
prints2.n # displays11
Before modifying the classvariable„n‟ After modifying the class variable„n‟
Types of methods:
We can classify the methods in the following 3 types:
a) Instancemethods
Accessormethods
Mutatormethods
b) Classmethods
c) Staticmethods
a) Instance Methods:
Instance methods are the methods which act upon the instance variables of the
class.instance methods are bound to instances and hence called as:
instancename.method(). Since instance variables are available in the instance, instance
methods need to know the memory address of instance. This is provided through „self‟
variable by default as first parameter for the instance method. While calling the instance
methods, we need not pass any value to the „self‟ variable.
Example:
class Student:
definit(self,n='',b=''):
self.name=n
self.branch=b
def display(self):
print "Hi",self.name
print "Branch", self.branch
s1=Student()
s1.display()
print― ------------------------------ ‖
s2=Student("mothi","CSE")
s2.display()
print― ------------------------------ ‖
Instance methods are of two types: accessor methods and mutatormethods.
Accessor methods simply access of read data of the variables. They do not modify
the data in the variables. Accessor methods are generally written in the form of
getXXXX( ) and hence they are also called gettermethods.
Mutator methods are the methods which not only read the data but also modify
them. They are written in the form of setXXXX( ) and hence they are also called
settermethods.
Example:
class Student:
def setName(self,n):
self.name = n
def setBranch(self,b):
self.branch = b
def getName(self):
return self.name
def getBranch(self):
return self.branch
s=Student()
name=input("Enter Name: ")
branch=input("Enter Branch:")
s.setName(name)
s.setBranch(branch)
print s.getName()
print s.getBranch()
b) Classmethods:
These methods act on class level. Class methods are the methods which act on
the class variables or static variables. These methods are written using
@classmethoddecorator above them. By default, the first parameter for class methods
is „cls‟ which refers to the class itself.
For example, „cls.var‟ is the format to the class variable. These methods are
generally called using classname.method( ). The processing which is commonly
needed by all the instances of class is handled by the class methods.
Example:
class Bird:
wings = 2
@classmethod
def fly(cls,name):
print name,"flieswith",cls.wings,"wings"
c) Static methods:
We need static methods when the processing is at the class level but we need
not involve the class or instances. Static methods are used when some processing is
related to the class but does not need the class or its instances to perform any work.
For example, setting environmental variables, counting the number of
instances of the class or changing an attribute in another class, etc. are the tasks
related to aclass.
Such tasks are handled by static methods. Static methods are written with
decorator @staticmethod above them. Static methods are called in the form of
classname.method ( ).
Example: class MyClass: n = 0
definit(self):
MyClass.n = Myclass.n + 1
def noObjects():
print "No. of instances created: ", MyClass.n
m1=MyClass()
m2=MyClass()
m3=MyClass()
MyClass.noObjects()
Inheritance:
def display(self):
definit(self,p1 = 0, p = 0):
Output: super().init(p1) self.property1
=p
def display(self):
isplay()
definit(self, x = 0):
self.x = x
def area(self):
definit(self, x = 0, y = 0):
super().init(x)
self.y = y def
area(self):
super().area()
r.area()
Output:
Area of square 25 Area
of Rectangle 80
Types of Inheritance:
There are mainly 2 types of inheritance.
a) Singleinheritance
b) Multipleinheritance
a) Single inheritance
Deriving one or more sub classes from a single base class is called „single
inheritance‟. In single inheritance, we always have only one base class, but there can
be n number of sub classes derived from it. For example, „Bank‟ is a single base clas
from where we derive „AndhraBank‟ and „StateBank‟ as sub classes. This is called
single inheritance.
Example:
class Bank:
cash = 100
@classmethoddefb
alance(cls):
printcls.cash
class AndhraBank(Bank):
cash = 500
@classmethod
def balance(cls):
cash = 300
@classmethoddef
balance(cls):
b) Multiple inheritance
Deriving sub classes from multiple (or more than one)base classes is called
„multiple inheritance‟. All the members of super classes are by default available to sub
classes and the sub classes in turn can have their own members.
The best example for multiple inheritance is that parents are producing the children and
the children inheriting the qualities of the parents.
Example:
class Father:
def height(self):
defcolor(self):
c
=
C
h
i
l
d
definit(self):
print"ClassA" Output:
classB(object): Class A
definit(self): ClassC
definit(self): super().init()
print "ClassC"
c1= C()
Example-2:
class A(object):
definit(self): super().init()
print"ClassA" Output:
classB(object): Class B
definit(self): Class A
super().init() ClassC
definit(self): super().init()
print "ClassC"
c1= C()
Method Overriding:
When there is a method in the super class, writing the same method in the sub class so
that it replaces the super class method is called „method overriding‟. The programmer
overrides the super class methods when he does not want to use them in sub class.
Example:
import math
class square:
Data hiding:
An object's attributes may or may not be visible outside the class definition. You need
to name attributes with a double underscore prefix, and those attributes then are not be
directly visible tooutsiders.
Example:
classJustCounter:
secretCount = 0
defcount(self):
self.secretCount += 1
print self.secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.secretCount
When the above code is executed, it produces the following result:
1
2
b) Runtime errors
When PVM cannot execute the byte code, it flags runtime error. For example,
insufficient memory to store something or inability of PVM to execute some
statement come under runtime errors. Runtime errors are not detected by the python
compiler. They are detected by the PVM, Only atruntime.
sal = increment(5000)
Output:
Salary after Increment is 750
From the above program the formula for salary is wrong, because only the
increment but it is not adding it to the original salary. So, the correct formula would
be:
sal = sal + sal * 15/100
Compile time errors and runtime errors can be eliminated by the programmer by
modifying the program sourcecode.
In case of runtime errors, when the programmer knows which type of error occurs, he
has to handle them using exception handlingmechanism.
Exceptions:
An exception is a runtime error which can be handled by the programmer.
That means if the programmer can guess an error in the program and he can do
somethingtoeliminatetheharmcaused bythaterror,thenitiscalledan„exception‟.
If the programmer cannot do anything in case of an error, then it is called an „error‟
and not anexception.
All exceptions are represented as classes in python. The exceptions which are already
available in python are called „built-in‟ exceptions. The base class for all built-in
exceptions is „BaseException‟class.
From BaseException class, the sub class „Exception‟ is derived. From Exception
class, the sub classes „StandardError‟ and „Warning‟ arederived.
All errors (or exceptions) are defined as sub classes of StandardError. An error should
be compulsory handled otherwise the program will notexecute.
Similarly, all warnings are derived as sub classes from „Warning‟ class. A warning
represents a caution and even though it is not handled, the program will execute. So,
warnings can be neglected but errors cannotneglect.
Just like the exceptions which are already available in python language, a programmer
can also create his own exceptions, called „user-defined‟exceptions.
Exception Handling:
Thepurposeofhandlingerrorsistomaketheprogramrobust.Theword„robust‟means
„strong‟. A robust program does not terminate in the middle.
Also, when there is an error in the program, it will display an appropriate message to the
user and continueexecution.
Designing such programs is needed in any softwaredevelopment.
For that purpose, the programmer should handle the errors. When the errors can be
handled, they are calledexceptions.
To handle exceptions, the programmer should perform the following four steps:
Step 1: The programmer should observe the statements in his program where there may be a
possibility of exceptions. Such statements should be written inside a „try‟ block. A try block
looks like as follows:
try:
statements
The greatness of try block is that even if some exception arises inside it, the program
will not be terminated. When PVM understands that there is an exception, it jumps into an
„except‟ block.
Step 2: The programmer should write the „except‟ block where he should display the
exception details to the user. This helps the user to understand that there is some error in the
program. The programmer should also display a message regarding what can be done to
avoid this error. Except block looks like asfollows:
except exceptionname:
statements
The statements written inside an except block are called „handlers‟ since they handle the
situation when the exception occurs.
Step 3: If no exception is raised, the statements inside the „else‟ block is executed. Else block
looks like as follows:
else:
statements
Step 4: Lastly, the programmer should perform clean up actions like closing the files and
terminating any other processes which are running. The programmer should write this code in
the finally block. Finally block looks like as follows:
finally:
statements
The speciality of finally block is that the statements inside the finally block are
executed irrespective of whether there is an exception or not. This ensures that all the opened
files are properly closed and all the running processes are properly terminated. So, the data in
the files will not be corrupted and the user is at the safe-side.
Here, the complete exception handling syntax will be in the following format:
try:
statements
exceptException1:
statements
exceptException2:
statements
else:
statements
finally:
statements
f = open('myfile.txt','r') s =
f.readline()
print s
f.close()
except IOError as e:
In the if the file is not found, then IOErroris raised. Then „except‟ block will display a
message: „I/O error‟. if the file is found, then all the lines of the file are read using
readline()method.
List of Standard Exceptions
Exception Name Description
Exception Base class for all exceptions
Raised when the next() method of an iterator does not point to
StopIteration
any object.
SystemExit Raised by the sys.exit() function.
Base class for all built-in exceptions except StopIteration and
StandardError
SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
Raised when a calculation exceeds maximum limit for a
OverflowError
numeric type.
FloatingPointError Raised when a floating point calculation fails.
Raised when division or modulo by zero takes place for all
ZeroDivisionError
numeric types.
AssertionError Raised in case of failure of the Assert statement.
AttributeError Raised in case of failure of attribute reference or assignment.
Raised when there is no input from either the raw_input() or
EOFError
input() function and the end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution, usually by
KeyboardInterrupt
pressing Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
Raised when an identifier is not found in the local or global
NameError
namespace.
Raised when trying to access a local variable in a function or
UnboundLocalError
method but no value has been assigned to it.
Base class for all exceptions that occur outside the Python
EnvironmentError
environment.
Raised when an input/ output operation fails, such as the print
IOError statement or the open() function when trying to open a file that
does not exist.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem, but when
SystemError
this error is encountered the Python interpreter does not exit.
Raised when Python interpreter is quit by using the sys.exit()
SystemExit function. If not handled in the code, causes the interpreter to
exit.
Raised when an operation or function is attempted that is
TypeError
invalid for the specified data type.
Raised when the built-in function for a data type has the valid
ValueError type of arguments, but the arguments have invalid values
specified.
RuntimeError Raised when a generated error does not fall into any category.
Raised when an abstract method that needs to be implemented
NotImplementedError
in an inherited class is not actually implemented.
The Except Block:
The „except‟ block is useful to catch an exception that is raised in the try block. When
there is an exception in the try block, then only the except block is executed. it is written in
various formats.
1. To catch the exception which is raised in the try block, we can write except block with
the Exceptionclass nameas:
except Exceptionclass:
2. We can catch the exception as an object that contains some description about the
exception.
except Exceptionclass as obj:
3. To catch multiple exceptions, we can write multiple catch blocks. The other way is to
use a single except block and write all the exceptions as a tuple inside paranthesesas:
except (Exceptionclass1, Exceptionclass2, ):
4. To catch any type of exception where we are not bothered about which type of
exception it is, we can write except block without mentioning any Exceptionclass name
as:
except:
Example:
try:
f = open('myfile.txt','w')
a=input("Enter a value ")
b=input("Enter a value ")
c=a/float(b)
s = f.write(str(c))
f.close()
Enter a value 1
Enter a value 5
Result is stored
Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (For example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the exception
argument is None.
For Example, If you need to determine whether an exception was raised but don‟t
intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:
try:
raise NameError('HiThere')
except NameError:
print 'An exception flew by!'
raise
User-Defined Exceptions:
Like the built-in exceptions of python, the programmer can also create his own
exceptionswhicharecalled„User-definedexceptions‟or„Customexceptions‟. Weknow
Python offers many exceptions which will raise in different contexts.
But, there may be some situations where none of the exceptions in Python are useful for
the programmer. In that case, the programme has to create his/her own exception and
raiseit.
For example, let‟s take a bank where customers have accounts. Each account is
characterized should by customer name and balanceamount.
The rule of the bank is that every customer should keep minimum Rs. 2000.00 as balance
amount in hisaccount.
The programmer now is given a task to check the accounts to know every customer is
maintaining minimum balance of Rs. 2000.00 ornot.
If the balance amount is below Rs. 2000.00, then the programmer wants to raise an
exception saying „Balance amount is less in the account of so and so person.‟ This will
be helpful to the bank authorities to find out thecustomer.
So, the programmer wants an exception that is raised when the balance amount in an
account is less than Rs. 2000.00. Since there is no such exception available in python, the
programme has to create his/her ownexception.
For this purpose, he/she has to follow thesesteps:
1. Since all exceptions are classes, the programmeis supposed to create his own
exceptionasaclass.Also,heshouldmakehisclassasasubclasstothein-built
„Exception‟ class.
class MyException(Exception):
definit(self, arg):
self.msg = arg
Here, MyException class is the sub class for „Exception‟ class. This class has a
constructor where a variable „msg‟ is defined. This „msg‟ receives a message passed
from outside through „arg‟.
2. The programmer can write his code; maybe it represents a group of statements or a
function. When the programmer suspects the possibility of exception, he should raise
his own exception using „raise‟ statementas:
raise MyException(‘message’)
Here, raise statement is raising MyException class object that contains the given
„message‟.
3. The programmer can insert the code inside a „try‟ block and catch the exceptionusing
„except‟ block as:
try:
code
except MyException as me:
print me
Here, the object „me‟ contains the message given in the raise statement. All these
steps are shown in below program.
Example:
class MyException(Exception): definit(self, arg):
self.msg = arg def check(dict):
for k,v in dict.items():
print "Name=",k,"Balance=",v if v<2000.00:
raise MyException("Balance amount is less in the account of "+k)
bank={"ravi":5000.00,"ramu":8500.00,"raju":1990.00} try:
check(bank)
except MyException as me: print me.msg
Output: