You are on page 1of 168

Python Programming 1

Core Python,
Advanced Python
&
Django
Framework

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 2

Core Python
Syllabus –
1. Language fundamentals
2. Operators
3. Input and Output statements
4. Flow Control
5. Strings
6. List Data Structure
7. Tuple Data Structure
8. Set Data Structure
9. Dictionary Data Structure
10. Functions
11. Modules
12. Packages

Advanced Python
Syllabus –
1. OOP’s
2. Exception Handling
3. File Handling
4. Multi-Threading
5. Regular Expressions
6. Web Scrapping
7. Python Data base Connectivity(PDBC)
8. Decorators
9. Generators
10. Logging Module
11. Assertions
12. Introduction to Web Application Development with DJango

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 3

CHAPTER
1

INTRODUCTION

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 4

Syllabus:
Introduction: History of Python, Need of Python Programming, Applications Basics
of Python Programming Using the REPL(Shell), Running Pythod Scripts, Variables,
Assignment, Keywords, Input-Output, Indentation

Python History:
 Python is an object-oriented, high level language, interpreted, dynamic and
multipurpose programming language.
 Python is easy to learn and powerful scripting language which makes it
attractive for Application Development.
 Python supports multiple programming pattern, including object-oriented
programming, imperative and functional programming or procedural styles.
 Python makes the development and debugging fast because there is no
compilation step included in python development and edit-test-debug cycle is
very fast.
Python is Interpreted: Python is processed at runtime by the interpreter. You do
not need to compile your program before executing it. This is similar to PERL and
PHP.
Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
o The design began in the late 1980s and was first released in February 1991.
o The implementation of Python was started in the December 1989 by Guido
Van Rossum at the National Research Institute for Mathematics and
Computer Science in the Netherland.
o Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, Unix shell, and other scripting languages.
o Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL).
o Why Python was created?
o In late 1980s, Guido Van Rossum was working on the Amoeba distributed
operating system group. He wanted to use an interpreted language like ABC
(ABC has simple easy-to-understand syntax) that could access the Amoeba
system calls. So, he decided to create a language that was extensible. This led
to a design of new language which was later named Python.

o Why the name Python?


o No. It wasn't named after a dangerous snake. Rossum was fan of a BBC
comedy series from late seventies. The name "Python" was adopted from the
same series "Monty Python's Flying Circus".

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 5
Python Features
There are a lot of features provided by python programming language.
 Simple and easy to learn
 Freeware and open source
 High level programming languages
 Platform independent
 Portability
 Dynamically typed programming language
 Both POP and OOPs
 Interpreted
 Extensible – other languages
 Embedded – other languages
 Extensive Library
1) Easy to Use:
Python is easy to very easy to use and high-level language. Thus, it is programmer-
friendly language.
2) Free and Open Source:
Python language is freely available (www.python.org).The source-code is also
available. Therefore, it is open source.
3) Expressive Language:
Python language is more expressive. The sense of expressive is the code is easily
understandable.
4) Interpreted Language:
Python is an interpreted language i.e. interpreter executes the code line by line at a
time. This makes debugging easy and thus suitable for beginners.
5) Cross-platform language:
Python can run equally on different platforms such as Windows, Linux, Unix,
Macintosh etc. Thus, Python is a portable language.
6) Object-Oriented language:
Python supports object-oriented language. Concept of classes and objects comes
into existence.
7) Extensible:
Suppose an application requires high performance. You can easily combine pieces
of C/C++ or other languages with Python code.
8) Large Standard Library:
Python has a large and broad library.
9) GUI Programming:
Graphical user interfaces can be developed using Python.
10) Integrated:
It can be easily integrated with languages like C, C++, JAVA etc.
Flavours of Python:
 CPython - Using C
 Jython or JPython - Using Java
 IronPython – using C#.net
 PyPy  PVM(Python Virtual Machine)  JIT Compiler (Just in Time)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 6
 RubyPython
 AnaCondaPython - Large – BigData and Hadoop Technologies
 Stackless - Python for concurrency

Python Version
Python programming language is being updated regularly with new features and
support. There are a lot of updation in python versions, started from 1994 to
current date.
A list of python versions with its released date is given below.
Python 1.0 -January 1994
Python 1.5 -31st Dec,1997
Python 1.6 -5th Sep,2000
Python 2.0 -Oct,2000
Python 2.1 -17th Apr,2001
Python 2.2 -21st Dec,2001
Python 2.3 -29th July,2003
Python 2.4 -30th Nov,2004
Python 2.5 -19th Sept,2006
Python 2.6 -1st Oct,2008 Python 3.0 – 3rd Dec, 2008
Python 2.7 -3rd Jul,2010 Python 3.1 -27th June,2009
Python 3.2 -20th Feb,2011
Python 3.3 -29th Sept,2012
Python 3.4 -16th Mar,2014
Python 3.5
Python 3.6 – June 2016
Python 3.7 – June 2018 (Lastest Version)

Python 2 and Python 3 Separate. Python 3 and Python 2 parallel versions.


In Python 2 => print “Hello”
In Python 3 => print (“Hello”)Separate. Python 3 and Python 2 parallel versions.

Where we can use in Python:


1. Desktop Applications
2. Web Applications – using Django and Flask
3. Database Applications
4. Network Applications
5. Gaming
6. Data Analysis
7. Machine Learning
8. AI
9. IOT applications

Python Applications
1) Console Based Application
Python can be used to develop console based applications. For example: IPython.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 7
2) Audio or Video based Applications
Python proves handy in multimedia section. Some of real applications are:
TimPlayer, cplay etc.
3) 3D CAD Applications
Fandango is a real application which provides full features of CAD.
4) Web Applications
You can create scalable Web Apps using frameworks and CMS (Content
Management System) that are built on Python. Some of the popular platforms for
creating Web Apps are: Django, Flask, Pyramid, Plone, Django CMS.
Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
5) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise
or an Organization. Some real time applications are: OpenErp, Tryton, Picalo etc.
6) Applications for Images
Using Python several application can be developed for image. Applications
developed are: VPython, Gogh, imgSeek etc.
7)Scientific and Numeric Computing
There are numerous libraries available in Python for scientific and numeric
computing. There are libraries like: SciPy and NumPy that are used in general
purpose computing. And, there are specific libraries like: EarthPy for earth science,
AstroPy for Astronomy and so on.

Limitations of Python:
1. Not suitable for Enterprise application
2. Not suitable for mobile applications
3. Performacne wise not up to the mark

User of Python:
Youtube,Dropbox, Yahoo, google,Zope Corporation, Ultraseek,Shopzilla,yum
 Youtube is orginally written in Python and mysql.
 Dropbox web-based file hosting service is implemented using Python.
Both the Dropbox server(running in the cloud) and desktop client software are
primarily written in Python.
 Yahoo Maps uses Python.
 Many components of the Google spider and search engine are written in Python.
 Python is now used in the Google search engine, in mission-critical projects at
NASA, and in transaction processing at the New York Stock Exchange. NASA,
Stock Exchange, NST(National Security)

Uses of Python in Data Analytics


Weather Forecasting, Scientific Analysis, Ad Targeting, Risk Management Analysis
standard library such as Pydoop, Pandas, Scipy etc

Python users for Data Analystics


ForecastWatch
appnexus

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 8
Altis
Los Alamos

HOW TO INSTALL PYTHON


1. To install Python, firstly download the Python distribution from
www.python.org/download.

2. Having downloaded the Python distribution now execute it. Double click on the
downloaded software. Follow the steps for installation:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 9

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 10

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 11

Click the Finish button and Python will be installed on your system.

SETTING PATH IN PYTHON


Before starting working with Python, a specific path is to set.
o Your Python program and executable code can reside in any directory of your
system, therefore Operating System provides a specific search path that index
the directories Operating System should search for executable code.
o The Path is set in the Environment Variable of My Computer properties:
o To set path follow the steps:
Right click on My Computer ->Properties ->Advanced System setting ->Environment
Variable ->New
In Variable name write path and in Variable value copy path up to C://Python(i.e.,
path where Python is installed). Click Ok ->Ok.
Path will be set for executing Python programs.
1. Right click on My Computer and click on properties.
2. Click on Advanced System settings

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 12

3. Click on Environment Variable tab.

4. Click on new tab of user variables.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 13

5. Write path in variable name

6. Copy the path of Python folder

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 14

7. Paste path of Python in variable value.

8. Click on Ok button:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 15

9. Click on Ok button:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 16
Python Example
Python code is simple and easy to run. Here is a simple Python code that will print
"Welcome to Python".
A simple python example is given below.
>>> a="Welcome To Avanthi"
>>> print a
Welcome To Avanthi
>>>
Explanation:
o Here we are using IDLE(Integrated Development and Learning Enivironment)
to write the Python code. Detail explanation to run code is given in Execute
Python section.
o A variable is defined named "a" which holds "Welcome To Python".
o "print" statement is used to print the content. Therefore "print a" statement
will print the content of the variable. Therefore, the output "Welcome To
Python" is produced.
Python 3.4 Example
In python 3.4 version, you need to add parenthesis () in a string code to print it.
>>> a=(" Welcome To Avanthi ")
>>> print a
Welcome To Avanthi
>>>
How to execute python
There are three different ways of working in Python:
1) Interactive Mode:
You can enter python in the command prompt and start working with Python.

Press Enter key and the Command Prompt will appear like:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 17

Now you can execute your Python commands.

Eg:

2) Script Mode:
Using Script Mode , you can write your Python code in a separate file using any
editor of your Operating System.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 18

Save it by .py extension.

Now open Command prompt and execute it by :

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 19
3) Using IDE: (Integrated Development Environment)
You can execute your Python code using a Graphical User Interface (GUI).
All you need to do is:
Click on Start button -> All Programs -> Python -> IDLE(Python GUI)

You can use both Interactive as well as Script mode in IDE.

1) Using Interactive mode:

Execute your Python code on the Python prompt and it will display result
simultaneously.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 20
2) Using Script Mode:
i) Click on Start button -> All Programs -> Python -> IDLE(Python GUI)
ii) Python Shell will be opened. Now click on File -> New Window.
A new Editor will be opened . Write your Python code here.

Click on file -> save as

Run then code by clicking on Run in the Menu bar.


Run -> Run Module
Result will be displayed on a new Python shell as:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 21
Run Python on Ubuntu

☛ You now first need to create environments to run Python. Go ahead and execute
the following commands.

$ mkdir environments
$ cd environments
$ python3 -m venv test_env

☛ Before you can use the <test_env>, you have to activate it first. The following
command will do the activation for you.

$ source test_env/bin/activate

Your prompt will now a little different than the standard one.

(test_env) techbeamers@techbeamers:~/environments$

This prefix indicates that the environment test_env is currently active. And you can
create programs to use the environment’s settings and packages.

☛ We have our virtual env set up, let’s write a simple “Hello, World!” script. To do
this, open up a command-line text editor such as vi and create a new file.

(test_env) techbeamers@techbeamers:~/environments$ vi world.py

The vi editor will open the text file in the terminal. Write the code given below. Press
“:wq” to save and exit from the editor.

print("Hello, World!")

☛ Once you exit out of vi and return to the shell, let’s run the script.

(test_env) techbeamers@techbeamers:~/environments$ python3 hello.py

# Output

Hello, World!

To log out of the environment, type the command “deactivate,” and it’ll return to
your original directory.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 22
REPL: Read-Eval-Print-Loop
Interactive shell that takes single statements, evaluates them, and returns the
result to the user
Primary prompt is >>>
Enables statement wise execution
To open type python in command prompt / terminal window
IDLE: Integrated DeveLopment Environment.

Python Variables
Variable is a name of the memory location where data is stored. Once a variable is
stored that means a space is allocated in memory.
Assigning values to Variable:
We need not to declare explicitly variable in Python. When we assign any value to
the variable that variable is declared automatically.
The assignment is done using the equal (=) operator.

Multiple Assignment:
Multiple assignment can be done in Python at a time.
There are two ways to assign values in Python:
1. Assigning single value to multiple variables:
Eg:
x=y=z=50
print x
print y
print z
Output:
>>>
50
50
50
>>>
2.Assigning multiple values to multiple variables:
Eg:
a,b,c=5,10,15
print a
print b

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 23
print c
Output:
>>>
5
10
15
>>>
Ex:
a,b,c,d,e=10,20,30,40,50
print(a,b,c,d,e,sep='...')
output:
10...20...30...40...50
Ex: Swap Two numbers
Temp=a
a=b
a=temp
in Python
a,b=10,20
print(a,b)
a,b=b,a
print(a,b)

Python Comments
In Python there are basically two ways to comment:
single line and multiple line.
Single line commenting is good for a short, quick comment (or for debugging) #
Multiple line comments are slightly different. Simply use 3 single quotes before and
after the part you want commented.
Multiplie Line ''' data
'''
input() function: The input() function is used to accept an input from a user. A
programmer can ask a user to input a value by making use of input()
variable name =input()
or
variable name=input(‘String’)

eval() function: The full form of eval function is to evaluate. It takes a string as
parameter and returns it as if it is a Python expression. For example, if we try to
run the statement eval(‘print(“Hello”)’) in Python interactive mode, it will actually
run the statement print(“Hello”).
eval(‘print(“Hello”)’)
Hello
The eval function takes a string and returns it in the type it is expected.
X=eval(‘123’)
123

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 24

Input-Output Statements:
Ex:
# Store input numbers:
a1 = input('Enter first number: ')
a2 = input('Enter second number: ')

# Add two numbers


sum = float(a1) + float(a2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(a1, a2, sum))

Ex:
a,b,c=10,20,30
print('a={},b={},c={}'.format(a,b,c))
print('a={2},b={0},c={1}'.format(a,b,c))
print('a={x},b={y},c={z}'.format(y=b,z=c,x=a))

Python program to find the area of a triangle


# Three sides of the triangle is a, b and c:
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Python program to solve quadratic equation


# import complex math module
import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 25
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Python program to swap two variables


# Python swap program
x = input('Enter value of x: ')
y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

Indentation:
Leading whitespace (spaces and tabs) at the beginning of locial line is used to
compute the identation leve lf the line, which in turn is used to determine the
grouping of statements.

Indentation is MUST in Python


 There are no braces to indicate blocks of code for class and function definitions
or flow control.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in in the indentation is variable, but all statements within
the block must be indented the same amount.
 Standard is to use 4 whitespaces as per official recommendation.
 Some editors automatically takes care of the indentation.

Getting Help in Python


help() or help('Object')
To exit the help press q
ex:
help() or help('for')
Note: Python programs are compiled automatically before being scanned by the
interpreter.The scanning process is hidden which makes Python faster than a pure
interpreter

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 26

CHAPTER
2

TYPES, OPERATORS
AND EXPRESSIONS

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 27
Syllabus:
Types,Operators and Expressions: Types – Integers, Strings, Booleans; Operators-
Airthmetic Opertors, Comparison(Relational) Operators, Assignment Operators,
Logical Operators, Bitwise Operators, Membership Operators, Identtiy Operators,
Expressions and order of evalutions. Control Flow – if, elif-else, for, while, break
continue, pass
Tokens and their types.
Tokens:
o Tokens can be defined as a punctuator mark, reserved words and each
individual word in a statement.
o Token is the smallest unit inside the given program.
There are following tokens in Python:
o Keywords.
o Identifiers.
o Literals.
o Operators.
o Delimters
Keywords
Keywords are special reserved words which convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation.
List of Keywords used in Python are: 33
o True, False, None
o And, or, not, is
o If, else, elif
o While, for, break, continue, return, in, yield
o Try, except, finally, raise, assert
o Import, from, as, class, def, pass, Global, nonlocal, lamda, del, with
Ex: import keyword
keyword.keylist
Identifiers
Identifiers are the names given to the fundamental building blocks in a program.
These can be variables, class, object, functions, lists, dictionaries etc.
There are certain rules defined for naming i.e., Identifiers.
I. An identifier is a long sequence of characters and numbers.
II.No special character except underscore ( _ ) can be used as an identifier.
III.Keyword should not be used as an identifier name.
IV.Python is case sensitive. So using case is significant.
V.First character of an identifier can be character, underscore ( _ ) but not digit.

Data Types:
Core Datatypes
int bytes
float bytearray
complex range
bool list
str tuple

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 28
set
dict
frozeset
None
All fundamental data types are immutable. Once we create an object, we are not
allowed to change the content of existing object. If we are trying to change the
content with those changes a new can be created.

Types or Literals:
Literals can be defined as a data that is given in a variable or constant.
Python support the following literals:
Numeric Literals
String Literals
Boolean Literals
special literals
Numeric Literals: -
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.

int(signed integers) Numbers( can be both positive and negative) with no


fractional part.eg: 100
long(long integers) Integers of unlimited size followed by lowercase or
uppercase L eg: 87032845L
float(floating point) Real numbers with both integer and fractional part eg: -
26.2
complex(complex) In the form of a+bj where a forms the real part and b
forms the imaginary part of complex number. eg: 3.14j
String literals:
String literals can be formed by enclosing a text in the quotes. We can use both
single as well as double quotes for a String.
Eg:
"Ramesh" , '12345'
Types of Strings:
There are two types of Strings supported in Python:
a).Single line String- Strings that are terminated within a single line are known as
Single line Strings.
Eg: text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as
Multiple line String.
There are two ways to create Multiline Strings:
Adding black slash at the end of each line.
Eg: text1='hello\
ramesh'
text1
'helloramesh'
2).Using triple quotation marks:-

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 29
Eg:
str2='''''welcome
to
AVANTHI'''
print str2
welcome
to
AVANTHI

Boolean literals:
A Boolean literal can have any of the two values: True or False.
Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for end of lists
in Python.
Eg:
val1=10
val2=None
val1
10
val2
print val2
None
bytes: A group of byte values
x=[10,20,30,40]
b=bytes(x)
The only allowed values are 0 to 255. It is immutable
bytearray: It can be used to represent binary information like images, video files,
audio files etc. It is exactly same as bytes. It is mutable
Type Casting or Type Coersion
int() : The int function converts a string or a number into whole number to integer.
The int function removes everything after the decimal point.
int(124.456) => 124
int(‘123’) => 123
float() : The float function converts a string into a floating point number
float(’10.23’) => 10.23
complex() : A complex number is number that can be expressed in the form a+bj
complex(10) => 10+0j
complex(10.5) => 10.5 + 0j
complex(true) => 1+0j
complex(false) => 0j
complex(‘10’) => 10+0j
complex(“ten”) => valueerror
complex(10,20) => 10+20j

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 30
bool() : The Boolean data type is represented in Python as type bool. It is a primitive
data type having one of the two values, viz. True or False. Internally, the True value
is represented as 1 and False as 0.
str() : A String literal or string in Python can be created using single, double and
triple quotes. The str function is used to convert a number into a string
str(12.5) => ’12.5’

Python escape sequence:


\’ Single Quote
\” Double Quote
\n Linefeed
\f Formfeed
\r Carriage return
\t Tab
\\ Backslash
\b Backsapce

Built-in Functions:
Built-n Functions are the functions which are built into(already available) Python
and can be accessed by end-users.
sorted() file()
abs() input()
all() int()
any() len()
basestring() open()
bin() raw_input()
boo()
enumerate()
eval()
print() -> print value of object
type() -> print type of object
id() -> print address of object
Every thing is an object in python

Python Inbuilt Mathematical functions:


Abs(x) Returns absolute value of x Abs(-2) = 2
Abs(4) = 4
Max(x1,x2,x3,..xn) Returns largest value among Max(10,20,30,40)
x1,x2,x3,…,xn 40
Min(x1,x2,x3,..xn) Returns smallest value among Min(10,20,30,40)
x1,x2,x3,…,xn 40
Pow(x,y) Return the Xy Pow(2,3) = 8
Round(x) Returns an integer nearest to the value Round(10.34) = 10
of x Round(10.89) = 11
Ceil(x) Round x to nearest ineger and returns Math.ceil(10.23) =11
that integer

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 31
Floor(x) Returns the largest value not greater Math.floor(18.9)=18
than X
Exp(x) Returns the exponential value ex Math.exp(1)
=2.718281828459045

ord(ch) function: - It return the ASCII value for a given character


ord(‘A’) = 65
chr(code) function: It returns the character corresponding to its code, i.e ASCII
value. chr(90) =z

Python Operators
Operators are particular symbols which operate on some values and produce an
output.The values are known as Operands.
Eg:
4+5=9
Here 4 and 5 are Operands and (+) , (=) signs are the operators. They produce the
output 9.
Python supports the following operators:
1. Arithmetic Operators. +, -, *, /, %, //, **
2. Relational Operators. <,<=,>,>=,==,!=
3. Assignment Operators and compound operators =,+=, -= ,*=, /=, %=
4. Logical Operators. and, or and not
5. Membership Operators. in, not in
6. Identity Operators. is, not is
7. Bitwise Operators. ~, &, |, ^, <<, >>
Arithmetic Operators:
Operators Description Example Output

// Perform Floor division(gives integer value print(12//5) 2


after division) print(12.0//5.0) 2.0
print(-19/5) -4
print(-20//3) -7.0

+ To perform addition print(a+b)

- To perform subtraction print(a-b)

* To perform multiplication print(a*b)

/ To perform division print(a/b)

% To return remainder after print(a%b)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 32
division(Modulus)

** Perform exponent(raise to power) print(a**b) 2**3


8

Relational Operators: for example a=100 b=200


Operators Description Example Output

< Less than print(a<b) True

> Greater than print(a>b) False

<= Less than or equal to print(a<=b) True

>= Greater than or equal to print(a>=b) False

== Equal to print(a==b) False

!= Not equal to print(a!=b) True

<> Not equal to(similar to !=) print(a<>b) True

Assignment Operators and compound assignement:


Operators Description

= Assignment

/= Divide and Assign

+= Add and assign

-= Subtract and Assign

*= Multiply and assign

%= Modulus and assign

**= Exponent and assign

//= Floor division and assign


eg:
>>> c=10

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 33
>>> c
10
>>> c+=5
>>> c
15
>>> c-=5
>>> c
10
>>> c*=2
>>> c
20
>>> c/=2
>>> c
10
>>> c%=3
>>> c
1
>>> c=5
>>> c**=2
>>> c
25
>>> c//=2
>>> c
12
>>>
Logical Operators:
Operators Description

and Logical AND(When both conditions are true output will be true)

or Logical OR (If any one condition is true output will be true)

not Logical NOT(Compliment the condition i.e., reverse)


eg:
a=5>4 and 3>2
print a
b=5>4 or 3<2
print b
c=not(5>4)
print c
Output:
>>>
True
True
False

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 34
>>>
Membership Operators:
Operators Description

in Returns true if a variable is in sequence of another variable,


else false.

not in Returns true if a variable is not in sequence of another


variable, else false.
eg:
a=10
b=20
list=[10,20,30,40,50];
if (a in list):
print "a is in given list"
else:
print "a is not in given list"
if(b not in list):
print "b is not given in list"
else:
print "b is given in list"
Output:
>>>
a is in given list
b is given in list
>>>
Identity Operators:
Operators Description

is Returns true if identity of two operands are same, else false

is not Returns true if identity of two operands are not same, else
false.
Example:
a=20
b=20
if( a is b):
print ?a,b have same identity?
else:
print ?a, b are different?
b=10
if( a is not b):
print ?a,b have different identity?
else:
print ?a,b have same identity?

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 35
Output:
>>>
a,b have same identity
a,b have different identity
>>>

Bit-wise operators: Bit-wise operators are used to manipulate the data at bit level.
It operates on integers only. It may not be applied to float. Bit-wise operators are
Operator Name
~ One’s complement
& Bitwise AND
| Bitwise Inclusive OR
^ Bitwise Exclusive OR
<< Left shift
>> Right shift
One’s complement(~): This operator performs negation operation on bits i.e.,
converting 0’s to 1’s and 1’s to 0’s
Ex: a=6 = 0000 0110
~a = = 1111 1001
Bitwise AND(&): This operator performs both operands bits 1’s it returns 1’s
otherwise 0’s
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0110
Bitwise Inclusive OR(|): This operator performs either one bit 1’s it returns 1’s
otherwise 0’s
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0111
Bitwise Exclusive OR(^): This operator performs all bits 1’s or 0’s it returns 0’s
otherwise 1’s.
Ex: a=6 =0000 0110
b=7 =0000 0111
a&b =0000 0001
Left Shift(<<): This operator performs the shift bits.
Ex: a=6 =0000 0110
a<<3 =0011 0000
Right Shift(>>): This operator performs the shift bits.
Ex: a=6 =0000 0110
a>>2 =0000 0001
Ternary Operator: -
Ex: max = a if a>b else b
min = a if a<b and a<c else b if b<c else c

Expression: - Expression is combination of operators and operands.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 36
Ex: a+b, a=b
Types of Expressions
Python supports different types of expressions that can be classified as
follows.
Based on the position of operators in an expression: These types of expressions
include:
Infix Expression: It is the most commonly used type of expression in which the
operator is placed in between the operands. Example : a=b-c
Prefix Expression: In this type of expression, the operator is placed before the
operands. Example: a=-bc
Postifix Expression: In this type of expression, the operator is placed after the
operands. Example: a=bc-
Based on the data type of the result obtained on evaluating an expression:
These types of expressions include:
Constant Expression: One that involves only constants. Ex: 8+9=17
Integra Expression: One that produces an integer result after evaluationg the
expression. Ex: a=10
b=5
c=a*b
Floating Point Expressions: One that produces floating point results. Ex : a*b /2
Relational Expressions: One that resturns either true or false value. Ex: c=>b
Logical Expression: One that combines two or more relational expressions and
return a value as true or false . Ex : a>b && y!=0
Bitwise Expressions: One that manipulates data at bit level. X=y &z
Assignment Expressions: One that assign a value to a variable . Ex : c=a+b or c=10
String Literals:
String literals in python are surrounded by either single quotation marks, or double
quotation marks.
s='ramesh' or
s="ramesh"
Using Triple Quotes(‘’’ ‘’’) you can specify multi-line strings using triple quotes. You
can use as many single quotes and double quotes as you want in a string within
triple quotes.
Note: All string methods returns new values. They do not change the original
string.
Concatenation: The process of combining two strings is called concatenation. Two
strings whether creaed using single or double quotes are concatenated in the same
way.
s1="ramesh "
s2="kumar"
print(s1+s2)
Multiplication(or String Repetition): you cannot add a string and a number but
you can definitely multiply a string and a number. When a string is multiplied with
an integer n, the string is repeated n times. Thus the * operator is also known as
string repetition operator.
print("ramesh "*5)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 37
ramesh ramesh ramesh ramesh Ramesh
Slice a String: you can extract subsets of strings by using the slice operator ([] and
[:]). You need to specify index or the range of index of characters to be extracted.
The index of the first character is 0 and the index of the last character is n-1, where
n I the number of characters in the string.
If you want to extract characters starting from the end of the string, then you
must specify the index as a negative number. For example, the index of the last
character is -1.
Get the character at position 1 (remember that the first character has the position
0): a = "Ramesh kumar"
print(a[1])  a
Substring. Get the characters from position 2 to position 5 (not included):
b = " Ramesh kumar "
print(b[2:5])  mes
Ex:
#String operations
s="Lucky is good girl !!!"
print(s)
print(s[0])
print(s[3:9])
print(s[4:])
print(s[-1])
print(s[:5])
print(s*2)
print(s+" hai ")
output:
Lucky is good girl !!!
L
ky is
y is good girl !!!
!
Lucky
Lucky is good girl !!!Lucky is good girl !!!
Lucky is good girl !!! hai

The len() method returns the length of a string:


a = " Ramesh Kumar"
print(len(a))  12
The lower() method returns the string in lower case:
a = " Ramesh Kumar"
print(a.lower())  ramesh kumar
The upper() method returns the string in upper case:
a = " Ramesh Kumar"
print(a.upper())  RAMESH KUMAR
The replace() method replaces a string with another string:
a = " Ramesh Kumar"

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 38
print(a.replace("R", "K"))  Kamesh Kumar
The capitalize() method returns a string where the first character is upper case.
a = "ramesh kumar"
print(a.capitalize())  Ramesh kumar
The casefold() method returns a string where all the characters are lower case.
This method is similar to the lower() method, but the casefold() method is stronger,
more aggressive, meaning that it will convert more characters into lower case, and
will find more matches when comparing two strings and both are converted using
the casefold() method.
txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)  hello, and welcome to my world!
The center() method will center align the string, using a specified character (space
is default) as the fill character.
string.center(length, character)
Parameter Description
Length Required. The length of the returned string
Optional. The character to fill the missing space on each side.
character
Default is " " (space)
Ex:
txt = "banana"
x = txt.center(20, "O")
print(x)
output: OOOOOOObananaOOOOOOO
The count() method returns the number of times a specified value appears in the
string.
string.count(value, start, end)
Parameter Description
value Required. A String. The string to value to search for
start Optional. An Integer. The position to start the search. Default is 0
Optional. An Integer. The position to end the search. Default is the
end
end of the string
Ex:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple", 10, 24)
print(x)
output:
1
The encode() method encodes the string, using the specified encoding. If no
encoding is specified, UTF-8 will be used.
string.encode(encoding=encoding, errors=errors)
encode(encoding='UTF-8',errors='strict')
ex:
s='ramesh'
s=s.encode('base64','strict')

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 39
print s
The decode() method decodes the string using the codec registered for Encoding.
decode(encoding='UTF-8',errors='strict'):
Ex: s=s.decode('base64','strict')
The startswith() method returns True if the string ends with the specified value,
otherwise False.
string.startswith(value, start, end)
Parameter Description
value Required. The value to check if the string ends with
Optional. An Integer specifying at which position to start the
start
search
end Optional. An Integer specifying at which position to end the search
txt = "Hello, welcome to my world."
x = txt.startswith("wel", 7, 20)
print(x)  True
The endswith() method returns True if the string ends with the specified value,
otherwise False.
string.endswith(value, start, end)
Parameter Description
value Required. The value to check if the string ends with
Optional. An Integer specifying at which position to start the
start
search
end Optional. An Integer specifying at which position to end the search
Ex:
txt = "Hello, welcome to my world."
x = txt.endswith("my world.", 5, 11)
print(x)  false
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is
that the index() method raises an exception if the value is not found. (See example
below)
string.find(value, start, end)
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
Optional. Where to end the search. Default is to the end of the
End
string
Ex:
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x)
output: 8

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 40
The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is
that the find() method returns -1 if the value is not found. (See example below)
string.index(value, start, end)
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
Optional. Where to end the search. Default is to the end of the
end
string
Ex:
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x)
output: 8
The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
Ex:
txt = "Company 12"
x = txt.isalnum()
print(x)
output: false
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.
txt = "Company"
x = txt.isalpha()
print(x)  True
The isdigit() or isnumeric() method returns True if all the characters are digits,
otherwise False.
Exponents, like ², are also considered to be a digit.
txt = "33535352"
x = txt.isdigit()
print(x)  True
The islower() method returns True if all the characters are in lower case, otherwise
False. Numbers, symbols and spaces are not checked, only alphabet characters.
txt = "ramesh"
x = txt.islower()
print(x)  True
The isupper() method returns True if all the characters are in upper case, otherwise
False. Numbers, symbols and spaces are not checked, only alphabet characters.
txt = "Ramesh"
x = txt.isupper()
print(x)  False

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 41
The isspace() method returns True if all the characters in a string are whitespaces,
otherwise False.
txt = " s "
x = txt.isspace()
print(x)  False
The istitle() method returns True if all words in a text start with a upper case letter,
AND the rest of the word are lower case letters, otherwise False. Symbols and
numbers are ignored.
txt = "Hello, And Welcome To My World!"
x = txt.istitle()
print(x)  True
The join() method takes all items in an iterable and joins them into one string. A
string must be specified as the separator.
string.join(iterable)
Parameter Description
Required. Any iterable object were all the returned values are
iterable
strings
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)  John#Peter#Vicky
Note: When using a dictionary as an iterable, the returned values are the keys, not
the values.
The lstrip() method removes any leading characters (space is the default leading
character to remove)
string.lstrip(characters)
Parameter Description
characters Optional. A set of characters to remove as leading characters
txt = ",,,,,ssaaww.....banana"
x = txt.lstrip(",.asw")
print(x)  banana
The rstrip() method removes any trailing characters (characters at the end a string),
space is the default trailing character to remove.
string.rstrip(characters)
Parameter Description
characters Optional. A set of characters to remove as trailing characters
txt = "banana,,,,,ssqqqww....."
x = txt.rstrip(",.qsw")
print(x)  banana
The strip() method removes any whitespace from the beginning or the end:
a = " Ramesh Kumar "
print(a.strip()) # returns "Ramesh Kumar"
The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method. See example below.
string.rfind(value, start, end)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 42
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
Optional. Where to end the search. Default is to the end of the
end
string
txt = "Hello, welcome to my world."
x = txt.rfind("e", 5, 10)
print(x) 8
The rindex() method finds the last occurrence of the specified value.
The rindex() method raises an exception if the value is not found.
The rindex() method is almost the same as the rfind() method. See example below.
string.rindex(value, start, end)
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
Optional. Where to end the search. Default is to the end of the
end
string
txt = "Hello, welcome to my world."
x = txt.rindex("e", 5, 10)
print(x) 8
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, Ramesh!"
print(a.split(",")) # returns ['Hello', ' Ramesh!']
The swapcase() method returns a string where all the upper case letters are lower
case and vice versa.
txt = "Hello My Name Is PETER"
x = txt.swapcase()
print(x)  hELLO mY nAME iS peter
The title() method returns a string where the first character in every word is upper
case. Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be
converted to upper case.
txt = "Welcome to my 2nd world"
x = txt.title()
print(x)  Welcome To My 2Nd World
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length. If the value of the len parameter is less than the length of the
string, no filling is done.
string.zfill(len)
Parameter Description
Required. A number specifying the position of the element you
len
want to remove
a = "hello"

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 43
b = "welcome to the jungle"
c = "10.000"
print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))
00000hello
welcome to the jungle
000010.000
max(str): it returs the max alphabetical character from the string str
txt = "Ramesh"
print(max(txt)) s
min(str): returs the min alphabetical character from the string str
txt = "ramesh"
print(min(txt)) a

Control structures: - It is divided into two types.


1. Conditional 2. Un conditional
Conditional statements divided into two types. Selection, repetition
Selection statements are if, elif, if-elif-else
Repetition statements are while, for.
Unconditional statements are break, continue, pass
Two-way selection: It is basically a two-way decision statement and is used in
conjunction with an expression.

Test
expression
False

True
Two-way selection statements are
1. Simple if statement
2. If…else statement
3. Nested if…else statement
4. Multi-way – if-elif-else statements
Python If Statements
The if statement in python is same as c language which is used test a condition. If
condition is true, statement of if block is executed otherwise it is skipped.

Simple If Statement: If is conditional control structure, if the condition is true


then statement or set of statements is executed.
Syntax:
if(condition): Test
statements expression

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute statements


of Engg. & Technology
Python Programming 44
True

a=10
if a==10:
print "Bhuvana Kruthi"
Output:
Bhuvana Kruthi

If…else Statement: - If is conditional control structure, if the condition is true then


statement or set of statements is executed if the condition is false then statement or
set of statements is executed.

Syntax:
if(condition):
Test
False
statements
expression
else:
statements
True
statements statements
Example-
year=2000
if year%4==0:
print "Year is Leap"
else:
print "Year is not Leap"
Output:
Year is Leap

Nested If…else Statement: When a series of if… else statements, if… else
statement within if… else statement called nested if.
Syntax: When we need to check for multiple conditions to be true then we use
elif Statement.
This statement is like executing a if statement inside a else statement.
Syntax:
If statement:
Body Test
elif statement: expression
Body
else:
Body
Example: statements
Test
a=10
if a>=20: expression
print "Condition is True"

statements statements
Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology
Python Programming 45
else:
if a>=15:
print "Checking second value"
else:
print "All Conditions are false"
Output:
All Conditions are false.
While Statement: - The while is an entry controlled loop statement. The test
condition is evaluated if the condition is true, then the body of the loop is executed.
After execution of the body, the test condition is once again evaluated and if it is
true, the body is executed once again. This process of repeated execution of the
body continues until the test condition finally becomes false and the control is
transferred out of the loop.
while Loop is used to execute number of statements or body till the condition
passed in while is true. Once the condition is false, the control will come out of the
loop.

Test
expression
False

True
statements

a=10
while a>0:
print "Value of a is",a
a=a-2
print "Loop is Completed"
Output:
Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed
Explanation:
 Firstly, the value in the variable is initialized.
 Secondly, the condition/expression in the while is evaluated. Consequently if
condition is true, the control enters in the body and executes all the statements .
If the condition/expression passed results in false then the control exists the
body and straight away control goes to next instruction after body of while.
 Thirdly, in case condition was true having completed all the statements, the
variable is incremented or decremented. Having changed the value of variable

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 46
step second is followed. This process continues till the expression/condition
becomes false.
 Finally Rest of code after body is executed.

range() function(Slice operation): The range function has one, two or three
parameters. The last two parameters in range() are optional.
range(begin, end, step)
The ‘begin’ is the first beginning number in the sequence at which the list
starts.
The ‘end’ is the limit, ie. The last number in the sequence.
The ‘Step’ is the difference between each number in the sequence.
Note: range doest not support item assignment. floating point value not read
range(5) [0,1,2,3,4]
range(1,5) [1,2,3,4]
range(1,10,2) [1,3,5,7,9]
range(5,0,-1) [5,4,3,2,1]
range(5,0,-2) [5,3,1]
range(-4,4) [-4,-3,-2,-1,0,1,2,3]
range(-4,4,2) [-4,-2,0,2]
range(0,1) [0]
range(1,1) Empty
range(0) Empty

For Statement: - The for loop is another entry-controlled loop that performs an
initialization step and then evaluates a test condition. If the test condition evaluates
to true, a given statement is executed and an increment expression is evaluated
repeatedly as long as the condition continues to evaluate to true.
for Loop is used to iterate a variable over a sequence (i.e., list or string) in the
order that they appear.
Syntax :
for <variable> in <sequence>:
Program to display table of Number:
num=2
for a in range (1,6):
print num * a
Output:
2
4
6
8
10
Program to find sum of Natural numbers from 1 to 10.
sum=0
for n in range(1,11):
sum+=n
print sum

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 47
Output:
55
Nested Loops
Loops defined within another Loop is called Nested Loop.
When an outer loop contains an inner loop in its body it is called Nested Looping.
Syntax:
for <expression>:
for <expression>:
Body
eg:
for i in range(1,6):
for j in range (1,i+1):
print i,
print
Output:
>>>
1
22
333
4444
55555
>>>
Explanation:
For each value of Outer loop the whole inner loop is executed.
For each value of inner loop the Body is executed each time.
Program to print Pyramid:
for i in range (1,6):
for j in range (5,i-1,-1):
print "*",
print
Output:
>>>
*****
****
***
**
*
Python Break
break statement is a jump statement that is used to pass the control to the end of
the loop.
When break statement is applied the control points to the line following the body of
the loop , hence applying break statement makes the loop to terminate and controls
goes to next line pointing after loop body.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 48

eg:
for i in [1,2,3,4,5]:
if i==4:
print "Element found"
break
print i,
Output:
>>>
1 2 3 Element found
>>>
Continue Statement
continue Statement is a jump statement that is used to skip the present iteration
and forces next iteration of loop to take place. It can be used in while as well as for
loop statements.

eg:
a=0
while a<=5:
a=a+1
if a%2==0:
continue
print a
print "End of Loop"
Output:
>>>
1
3
5
End of Loop
>>>

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 49
Python Pass
When you do not want any code to execute, pass Statement is used. It is same as
the name refers to. It just makes the control to pass by without executing any code.
If we want to bypass any code pass statement can be used.
The pass statement does nothing. It can be used when a statement is required
syntatically but the program requires no action.
Syntax:
pass
eg:
for i in [1,2,3,4,5]:
if i==3:
pass
print "Pass when value is",i
print i,
Output:
>>>
1 2 Pass when value is 3
345
>>>
Loops with else clause: Python supports to have an else statement associated with
a loop statement. If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
Ex:
list=[1,2,3,4,5]
# using else clause with for loop
for num in list:
if num==6:
print("Object found")
else:
print("No Object found")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 50

CHAPTER
3

DATA STRUCTURES

Syllabus:
Data Structures: Lists – Operations, Slicing, Methods; Tuples, Sets, Dictionaries,
Sequences, Comprehensions.
Python Collections (Arrays)
There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 51
 Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No
duplicate members.
Data Structure defines a particular way of storing and organizing data in a
computer so that it can be used efficiently.
Types of Data structures in Python are
1. List
2. Tuple
3. Set
4. Dictionaries
5. Sequeuces
1. List: - Python lists are the data structure that is capable of holding different type
of data. Python lists are mutable i.e., Python will not create a new list if we modify
an element in the list. It is a container that holds other objects in a given order.
Different operation like insertion and deletion can be performed on lists. A list can
be composed by storing a sequence of different type of values separated by commas.
A python list is enclosed between square([]) brackets. The elements are stored in the
index basis with starting index as 0.
Ex: data1=[1,2,3,4];
data2=['x','y','z'];
data3=[12.5,11.6];
data4=['bhuvana kruthi','sai sruthi'];
data5=[];
data6=['vanesh',10,56.4,'a'];
1.1 Access Values in Lists: -
A subpart of a list can be retrieved on the basis of index. This subpart is known as
list slice.
Similar to strings, lists can also be sliced and concatenated. To access values in
lists, square brackets are used to slice along with the index or indices to get value
stored at that index.
Note: If the index provided in the list slice is outside the list, then it raises an
IndexError exception.
Syntax : variable = list variable[start:stop:step]
Ex:
cse = [10,11,13,15,16,29,24,14,12]
print ("list items are",cse)
print ("first element in the list is ",cse[0])
print ("cse[2:5:] = ",cse[2:5:])
print ("cse[::2] = ",cse[::2])
print ("cse[1::3] = ",cse[1::3])
output : list items are [10, 11, 13, 15, 16, 29, 24, 14, 12]
first element in the list is 10
cse[2:5:] = [13, 15, 16]

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 52
cse[::2] = [10, 13, 16, 24, 12]
cse[1::3] = [11, 16, 14]

1.2 Updating values in List: - Once created, one or more elements of a list can be
easily updated by giving the slice on the left-hand side of the assignment operator.
You can add to elements in a list with the append() method.
Eg:
cse = [10,11,13,15,16,29,24,14,12]
print ("list items are",cse)
cse[5]=100
print ("list after updation is :",cse)
cse.append(200)
print ("list after appending a value is :",cse)
output:
list items are [10, 11, 13, 15, 16, 29, 24, 14, 12]
list after updation is : [10, 11, 13, 15, 16, 100, 24, 14, 12]
list after appending a value is : [10, 11, 13, 15, 16, 100, 24, 14, 12, 200]
1.3 Deleting Elements from a List: - del statement can be used to delete an
element from the list. It can also be used to delete all items from startIndex to
endIndex.
Eg:
cse = [10,11,13,15,16,29,24,14,12]
print ("list items are",cse)
del cse[3]
print ("List after deleting element is ",cse)
del cse[2:5]
print ("List after deleting elements is ",cse)
del cse[:]
print ("List after deleting all elements is ",cse)
output:
list items are [10, 11, 13, 15, 16, 29, 24, 14, 12]
List after deleting element is [10, 11, 13, 16, 29, 24, 14, 12]
List after deleting elements is [10, 11, 24, 14, 12]
List after deleting all elements is []

1.4 Nested List: - Nested List means a list within another list. We have already said
that a list has elements of different data types which can include event a list.
Eg:
cse = [10,11,13,15,[4,5.6,7.8],16,29,24,14,12]

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 53
print ("list items are",cse)
print ("sub list is",cse[4])
print ("sub list element is ",cse[4][2])
output:
list items are [10, 11, 13, 15, [4, 5.6, 7.8], 16, 29, 24, 14, 12]
sub list is [4, 5.6, 7.8]
sub list element is 7.8
1.5 Cloning List: - If you want to modify a list and also keep a copy of the original
list, then you should create a separate copy of the list (not just the reference). This
process is called Cloning.
Eg:
cse1 = [10,11,13,15,16,29,24,14,12]
cse2 = cse1
print ("List1 = ",cse1)
print ("List2 = ",cse2)
cse3 = cse1[2:6]
cse4 = cse2[2:6]
print ("List3 =",cse3)
print ("List4 =",cse4)
output:
List1 = [10, 11, 13, 15, 16, 29, 24, 14, 12]
List2 = [10, 11, 13, 15, 16, 29, 24, 14, 12]
List3 = [13, 15, 16, 29]
List4 = [13, 15, 16, 29]
1.6 Operations on Lists: -
Operation Description Example & Output
len It returns length of list Eg:
cse1 = [10,11,13,15,16,29,24,14,12]
print ("List length = ",len(cse1))
output:
List length = 9
concatenat Joins two lists. Eg:
ion(+) Note: '+'operator implies cse1 = [10,11,13,15,16,29,24,14,12]
that both the operands cse2 = [100,200,300,500,400,800,600]
passed must be list else print ("Joins two lists = ",cse1+cse2)
error will be shown. output:
Joins two lists = [10, 11, 13, 15, 16, 29, 24,
14, 12, 100, 200, 300, 500, 400, 800, 600]
repetation( Repeats elements in the Eg:
*) list. Replicating means cse1 = [10,11,13,15,16,29,24,14,12]
repeating print ("Final List = ",cse1*2)
output:
Final List = [10, 11, 13, 15, 16, 29, 24, 14,
12, 10, 11, 13, 15, 16, 29, 24, 14, 12]
MemberSh Checks if the value is Eg:
ip(in) present in the list cse1 = [10,11,13,15,16,29,24,14,12]

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 54
print ("result = ",13 in cse1)
output:
result = True
not in Checks if the value is Eg:
not present in the list cse1 = [10,11,13,15,16,29,24,14,12]
print ("result = ",13 not in cse1)
output:
result = False
max It returns maximum Eg:
value in the list cse1 = [10,11,13,15,16,29,24,14,12]
print ("maximum value = ",max(cse1))
output:
maximum value = 29
min It returns minimum Eg:
value in the list cse1 = [10,11,13,15,16,29,24,14,12]
print ("minimum value = ",min(cse1))
output:
minimum value = 10
sum Adds the values in the Eg:
list that has numbers cse1 = [10,11,13,15,16,29,24,14,12]
print ("sum value = ",sum(cse1))
output:
sum value = 144
all It returns true if all Eg:
elements of the list are cse1 = [10,11,13,15,16,29,24,14,12]
true print ("result value = ",all(cse1))
output:
result value = True
any It returns true if any Eg:
element of the list is cse1 = [10,11,13,15,16,29,24,14,12]
true. If the list empty, print ("result value = ",any(cse1))
return false output:
result value = True
sorted It returns a new sorted Eg:
list. The original list is cse1 = [10,11,13,15,16,29,24,14,12]
not sorted. print ("sorted value = ",sorted(cse1))
output:
sorted value = [10, 11, 12, 13, 14, 15, 16,
24, 29]

1.7 List Methods:


Method Description Syntax Example& Output
append() appends an element to list.append(obj) Eg:
the list. cse1 =
[10,11,13,15,12,16,29,12
,24,12,14,12]

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 55
cse1.append(200)
print("result list is=",cse1)
output:
result list is= [10, 11, 13,
15, 12, 16, 29, 12, 24,
12, 14, 12, 200]
count() Counts the number of list.count(obj) Eg:
times an element cse1 =
appears in the list [10,11,13,15,12,16,29,12
,24,12,14,12]
print("result=",cse1.count
(12))
output:
result=4
index() It returns the first list.index(obj) Eg:
occurrence of obj in the cse1 =
list. It gives a [10,11,13,15,12,16,29,12
ValueError if obj is not ,24,12,14,12]
present in the list print("result=",cse1.index(
12))
output:
result=4
insert() inserts obj at the list.insert(index, Eg:
specified index in the obj) cse1 =
list [10,11,13,15,12,16,29,12
,24,12,14,12]
cse1.insert(3,45)
print("list elements are
",cse1)
output:
list elements are [10, 11,
13, 45, 15, 12, 16, 29,
12, 24, 12, 14, 12]
reverse() Reverse the elements in list.reverse() Eg:
the list cse1 =
[10,11,13,15,12,16,29,12
,24,12,14,12]
cse1.reverse()
print("list elements are
",cse1)
output:
list1 elements are [12,
14, 12, 24, 12, 29, 16,
12, 15, 13, 11, 10]
sort() Sorts the elements in list.sort() Eg:
the list cse1 =

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 56
[10,11,13,15,12,16,29,12
,24,12,14,12]
cse1.sort()
print("list elements are
",cse1)
output:
list elements are [10, 11,
12, 12, 12, 12, 13, 14,
15, 16, 24, 29]
extend() Adds the elements in a list1.extend(list Eg:
list to the end of another 2) cse1 =
list. [10,11,13,15,12,16,29,12
,24,12,14,12]
cse2 = [45,55,65,75]
cse1.extend(cse2)
print("list elements are
",cse1)
output:
list elements are [10, 11,
13, 15, 12, 16, 29, 12,
24, 12, 14, 12, 45, 55,
65, 75]
remove()/ Removes or deletes obj list.remove(obj) Eg:
clear() from the list. ValueError cse1 =
is generated if obj is not [10,11,13,15,12,16,29,12
present in the list. If ,24,12,14,12]
multiple copies of obj cse1.remove(12)
exists in the list, then print("list elements are
the first value is deleted ",cse1)
output:
list elements are [10, 11,
13, 15, 16, 29, 12, 24,
12, 14, 12]
pop()/pop(i Removes the element at list.pop([index]) Eg:
ndex) the specified index from cse1 =
the list. Index is an [10,11,13,15,12,16,29,12
optional parameter. If ,24,12,14,12]
no index is specified, print("The pop element is
then removes the last ",cse1.pop())
object(or element) from output:
the list The pop element is 12
cmp() If elements are of the cmp(list1,list2) Eg:
same type, perform the list1=[101,981,'abcd','xyz'
comparison and return ,'m']
the result. If elements list2=['aman','shekhar',10
are different types, 0.45,98.2]

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 57
check whether they are list3=[101,981,'abcd','xyz'
numbers. ,'m']
print cmp(list1,list2)
o If numbers, perform print cmp(list2,list1)
comparison. print cmp(list3,list1)
o If either element is a output:
number, then the -1
other element is 1
returned. 0
o Otherwise, types are
sorted alphabetically
.

If we reached the end of


one of the lists, the
longer list is "larger." If
both list are same it
returns 0.
1.7 List Comprehensions:
List comprehension is used to create a new list from existing sequences. It is a tool
for transforming a given list into another list.
[<expression> for <element> in <sequence> if <conditional>]
Without list comprehension
List1=[10,20,30,40,50]
for i in range(0,len(list1)):
list1[i]=list1[i]+10
list1=[20.30,40,50,60]
With list comprehension:
List1=[10,20,30,40,50]
List1=[x+10 for x in list1]
list1=[20.30,40,50,60]

2. Tuple:
A tuple is a sequence of immutable objects. This means that while you can change
the value of one or more items in a list, you cannot change the values in a tuple.
The objects are enclosed within parenthesis and separated by comma.
Tuple is similar to list. Only the difference is that list is enclosed between square
bracket, tuple between parenthesis and List have mutable objects whereas Tuple
have immutable objects.
Syntax: Tuple variable = (val1,val2,val3,……) where values can be an integer,
a floating number, a character, or a string.
Tup1 = ( ) Output : ( ) Creates an empty tuple
Tup1 = (5) Output : (5) Creates a tuple with a single element
Tup1=(2,4,5,3) Output: (2,4,5,3) Creates a tuple of integers
Tup1=(‘a’,’b’,’c’,’d’) Output: (‘a’,’b’,’c’,’d’) Creates a tuple of characters
Tup1=(‘raj’,’kumar’,’ram’) Output: (‘raj’,’kumar’,’ram’)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 58
Creates a tuple of strings
Tup1=(1.5,2.5,3.1,4.5) Output: (1.5,2.5,3.1,4.5)
Creates a tuple of floating point numbers
Tup1=(1,”abc”,2.3,’d’) Output: (1,”abc”,2.3,’d’)
Creates a tuple of mixed values
NOTE: If Parenthesis is not given with a sequence, it is by default treated as Tuple.
If you want to create a tuple with a single element, then you must add a comma
after the element. In the absence of a comma, python treats the element as an
ordinary data type.
Once a type has been crated, we cannot add or delete elements, or even
shuffle their order. Hence, tuples are immutable. This means that once created,
they cannot be changed and their length is also fixed.
2.1 Access Values in Tuple: -
Tuple can be accessed in the same way as List.
Eg:
cse = (10,11,13,15,16,29,24,14,12)
print ("tuple items are",cse)
print ("first element in the list is ",cse[0])
print ("cse[2:5:] = ",cse[2:5:])
print ("cse[::2] = ",cse[::2])
print ("cse[1::3] = ",cse[1::3])
Output:
tuple items are (10, 11, 13, 15, 16, 29, 24, 14, 12)
first element in the list is 10
cse[2:5:] = (13, 15, 16)
cse[::2] = (10, 13, 16, 24, 12)
cse[1::3] = (11, 16, 14)

2.2 Updating values in Tuple: - Elements of the Tuple cannot be updated. This is
due to the fact that Tuples are immutable. Whereas the Tuple can be used to form a
new Tuple.
data=(10,20,30)
data[0]=100
print data

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 59
Traceback (most recent call last):
File "C:/Users/Admin/AppData/Local/Programs/Python/Python36-32/cse4.py",
line 2, in <module>
data[0]=100
TypeError: 'tuple' object does not support item assignment
Creating new tuple from existing:
Eg:
data1=(10,20,30)
data2=(40,50,60)
data3=data1+data2
print (data3)

Output:
(10, 20, 30, 40, 50, 60)
2.3 Deleting elements from Tuple: - Deleting individual element from a tuple is
not supported. However the whole of the tuple can be deleted using the del
statement.
Eg:
data=(10,20,'rahul',40.6,'z')
print (data)
del data[3]
del data #will delete the tuple data
print (data) #will show an error since tuple data is already deleted
Output:
(10, 20, 'rahul', 40.6, 'z')
Traceback (most recent call last):
File "C:/Users/Admin/AppData/Local/Programs/Python/Python36-
32/cse4.py", line 3, in <module>
del data[3]
TypeError: 'tuple' object doesn't support item deletion
2.4 Nested Tuple: - Python allows you to define a tuple inside another tuple. This
is called a Nested Tuple.
Eg:
cse = (10,11,13,15,(4,5.6,7.8),16,29,24,14,12)
print ("tuple items are",cse)
print ("sub tuple is",cse[4])
print ("sub tuple element is ",cse[4][2])
output:
tuple items are (10, 11, 13, 15, (4, 5.6, 7.8), 16, 29, 24, 14, 12)
sub tuple is (4, 5.6, 7.8)
sub tuple element is 7.8
2.5 Operations on Tuples:
Operation Description Example & Output
Len Gives the length of a Eg:
tuple cse = (10,11,13,15,16,29,24,14,12)
print ("tuple length =",len(cse))

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 60
output:
tuple length = 9
Concatena Tuple can be added by Eg:
tion(+) using the concatenation cse1 = (10,11,13,15,16,29,24,14,12)
operator(+) to join two cse2 = (19,20,25,"rajesh","ashok",18)
tuples. cse3 = cse1+cse2
print("concatenation of two tuples ",cse3)
output:
concatenation of two tuples (10, 11, 13, 15,
16, 29, 24, 14, 12, 19, 20, 25, 'rajesh',
'ashok', 18)
Repetaion( Repeats elements in the Eg:
*) tuple. Replicating cse1 = (10,11,13,15,16,29,24,14,12)
means repeating print("final tuple is =",cse1*2)
output:
final tuple is = (10, 11, 13, 15, 16, 29, 24,
14, 12, 10, 11, 13, 15, 16, 29, 24, 14, 12)
MemberSh Checks if the value is Eg:
ip(in) present in the tuple cse1 = (10,11,13,15,16,29,24,14,12)
print ("result = ",13 in cse1)
output:
result = True
Max It returns maximum Eg:
value in the tuple cse1 = (10,11,13,15,16,29,24,14,12)
print ("maximum value = ",max(cse1))
output:
maximum value = 29
Min It returns minimum Eg:
value in the tuple cse1 = (10,11,13,15,16,29,24,14,12)
print ("minimum value = ",min(cse1))
output:
minimum value = 10
cmp(tuple If elements are of the Eg:
1,tuple2) same type, perform the data1=(10,20,'rahul',40.6,'z')
comparison and return data2=(20,30,'sachin',50.2)
the result. If elements print (cmp(data1,data2))
are different types, print (cmp(data2,data1))
check whether they are data3=(20,30,'sachin',50.2)
numbers. print (cmp(data2,data3))
output:
o If numbers, -1
perform 1
comparison. 0
o If either element
is a number, then
the other element

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 61
is returned.
o Otherwise, types
are sorted
alphabetically .

If we reached the end of


one of the lists, the
longer list is "larger." If
both list are same it
returns 0.
tuple(sequ Converts the sequence Eg:
ence) into tuple. dat=[10,20,30,40]
data=tuple(dat)
print (data)
output:
(10, 20, 30, 40)
count() The count() method thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
returns the number of x = thistuple.count(5)
times a specified value print(x)
appears in the tuple. output
tuple.count(value) 2
index() The index() method thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
finds the first x = thistuple.index(8)
occurrence of the print(x)
specified value.
The index() method output
raises an exception if 3
the value is not found.
tuple.index(value)
Zip Function(): The zip() is an ibuilt function in Python. It takes items in sequence
from a number of collections to make a list of typles, where each tuple contains one
item from each collection. The function is often used to group items from a list
which has the same index.
Ex:
L1=['Laptop','Desktop','Mobile']
L2=[40000,30000,15000]
L3=tuple(list(zip(L1,L2)))
print(L3)

output: (('Laptop', 40000), ('Desktop', 30000), ('Mobile', 15000))

2.6 Advantages of Tuple over List: -


Tuples are similar to Lists, there are some advantages of implementing a tuple over
a list.
 Tuples are used to store values of different data types. List can however, store
data of similar data types.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 62
 Since tuples are immutable, iterating through tuples is faster than iterating
over a list. This means that a tuple performs better than alist.
 Tuples can be used as key for a dictionary but lists cannot be used as keys.
 Tuples are best suited for storing data that is write-protected(you can read
the data but cannot write to it).
 Tuples can be used in place of lists where the number of values is known and
small.
 Multiple values from a function can be returned using a tuple.
 Tuples are used to format strings.

3. Sets: - Sets is another data structure supported by Python. Basically, sets are
same as lists but with a difference that sets are lists with no duplicate entries.
Technically, a set is a mutable and an unordered collection of items. This mean that
we can easily add or remove items from it.
3.1 Creating a Set: - A set is created by placing all the elements inside curly
brackets { }, separated by comma or by using the built-in function set( ).
Set variable = {var1,var2,……}
Eg:
s={1,2.4,"abc",1}
print (s)
list1 = [1,2,4,5,6,5,4,3,2,1]
print(set(list1))
output:
{1, 'abc', 2.4}
{1, 2, 3, 4, 5, 6}
3.2 Set Operations:
Operation Description Example & Output
s.update(t) adds elements of set t in the set s Eg:
provided that all duplicates are s=set([1,2,3,4,5])
avoided t=set([6,7,8])
s.update(t)
print(s)
output:
{1, 2, 3, 4, 5, 6, 7, 8}
s.add(x) Adds element x to the set s Eg:
provided that all duplicates are s=set([1,2,3,4,5])
avoided s.add(6)
print(s)
output:
{1, 2, 3, 4, 5, 6}
s.remove(x) Removes element x from set s. Eg:
Return keyError if x is not s=set([1,2,3,4,5])
present s.remove(3)
print(s)
output:
{1, 2, 4, 5}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 63
s.discard(x) Same as remove() but does not Eg:
give an error if x is not present in s=set([1,2,3,4,5])
the set s.discard(3)
print(s)
output:
{1, 2, 4, 5}
s.pop() Removes an returns any arbitrary Eg:
element from s. keyError is raised s=set([1,2,3,4,5])
if s is empty s.pop()
print(s)
output:
{2, 3, 4, 5}
s.clear() Removes all elements from the set Eg:
s=set([1,2,3,4,5])
s.clear()
print(s)
output:
set()
len(s) Returns the length of set Eg:
s=set([1,2,3,4,5])
print(len(s))
output:
5
x in s Returns true is x is present in set Eg:
s and false otherwise s=set([1,2,3,4,5])
print(4 in s)
output:
True
x not in s Returns true is x is not present in Eg:
set s and false otherwise s=set([1,2,3,4,5])
print(6 not in s)
output:
True
s.issubset(t) Returns true if every element in Eg:
or s<=t set t and false otherwise s=set([1,2,3,4,5])
t=set([1,2,3,4,5,6,7,8,9,10])
print(s.issubset(t))
output:
True
s.issuperset Returns true if every element in t Eg:
(t) or s>=t is present in set s and False s=set([1,2,3,4,5])
otherwise t=set([1,2,3,4,5,6,7,8,9,10])
print(s.issuperset(t))
output:
False
s.union(t) or Returns a set s that has elements Eg:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 64
s|t from both sets s and t s=set([1,2,3,4,5])
t=set([1,2,3,4,5,6,7,8,9,10])
print(s.union(t))
output:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
s.intersectio Returns a new set that has Eg:
n(t) or s&t elements which are common to s=set([1,2,3,4,5])
both the sets s and t t=set([1,2,3,4,5,6,7,8,9,10])
z=s&t
print(z)
output:
{1, 2, 3, 4, 5}
s.intersectio Returns a set that has elements Eg:
n_update(t) which are common to both the s=set([1,2,3,4,5])
sets s and t t=set([1,2,3,4,5,6,7,8,9,10])
s.intersection_update(t)
print(s)
output:
{1, 2, 3, 4, 5}
s.difference( Returns a new set that has Eg:
t) or s-t elements in set s but not in t s=set([1,2,3,4,5,11,12])
t=set([1,2,3,4,5,6,7,8,9,10])
z=s-t
print(z)
output:
{11,12}
s.difference Removes all elements of another Eg:
_update(t) set from this set s=set([1,2,3,4,5,11,12])
t=set([1,2,3,4,5,6,7,8,9,10])
s.difference_update(t)
print(s)
output:
{11,12}
s.symmetric Returns a new set with elements Eg:
_difference(t either in s or in t but not both s=set([1,2,3,4,5,11,12])
) or s^t t=set([1,2,3,4,5,6,7,8,9,10])
z=s^t
print(z)
output:
{6, 7, 8, 9, 10, 11, 12}
s.copy() Returns a copy of set s Eg:
s=set([1,2,3,4,5,11,12])
t=set([1,2,3,4,5,6,7,8,9,10])
print(s.copy())
output:
{1, 2, 3, 4, 5, 11, 12}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 65
s.isdisjoint(t Returns true if two sets have a Eg:
) null intersection s=set([1,2,3,4,5,11,12])
t=set([6,7,8])
print(s.isdisjoint(t))
output:
True
all(s) Returns true if all elements in the Egg:
set are true and false otherwise s=set([0,1,2,3,4])
print(all(s))
output:
False
any(s) Returns true if any of the Egg:
elements in the set is True. s=set([0,1,2,3,4])
Returns false if the set is empty print(all(s))
output:
True
max(s) Returns the maximum value in a Egg:
set s=set([1,2,3,4,5,11,12])
print(max(s))
output:
12
min(s) Returns the minimum value in a Egg:
set s=set([1,2,3,4,5,11,12])
print(min(s))
output:
1
sum(s) Returns the sum of elements in Egg:
the set s=set([14,2,31,4,52,11,12])
print(sum(s))
output:
126
sorted(s) Returns a new sorted list from Egg:
elements in the set. It does not s=set([14,2,31,4,52,11,12])
sort the set as sets are print(sorted(s))
immutable. output:
[2, 4, 11, 12, 14, 31, 52]
s==t and S==t returns true if the two set
s!=t are equivalent and False
otherwise. s!=t returns true if
both sets are not equivalent and
False otherwise
symmetric_ The symmetric_difference() x = {"apple", "banana", "cherry"}
difference() method returns a set that y = {"google", "microsoft", "apple"}
contains all items from both set, z = x.symmetric_difference(y)
but not the items that are present print(z)
in both sets. output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 66
Meaning: The returned set {'cherry', 'microsoft', 'google',
contains a mix of items that are 'banana'}
not present in both sets.

4. Dictionaries: -
Dictionary is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon(:) and consecutive items are
separated by commas. The entire items in a dictionary are enclosed in curly
bracket({ }).
4.1 Creating a Dictionary: -
To create an empty dictionary, just write the following line of code.
d={}
print(d)
A dictionary can be also created by specified key-value pairs separated by a
colon in curly brackets as shown below.
Syntax: dictionary-name = {key_1:value_1,
key_2:value_2,
key_3:value_3,
…}
Dictionary keys are case-senstive.The pair i.e., key and value is known as
item.
Eg:
data={100:'Ravi' ,101:'Vijay' ,102:'Rahul'}
print (data)
output:
{100: 'Ravi', 101: 'Vijay', 102: 'Rahul'}
Note: -Dictionary is mutable i.e., value can be updated. Key must be unique and
immutable. Value is accessed by key. Value can be updated while key cannot be
changed.
Dictionary is known as Associative array since the Key works as Index and they are
decided by the user.
Eg:
cse={}
cse[1]='Ravi'
cse[2]='Manoj'
cse['name']='Hari'
cse[4]='Om'
print (cse[2])
print (cse['name'])
print (cse[1])
print (cse)
output:
Manoj
Hari
Ravi
{1: 'Ravi', 2: 'Manoj', 'name': 'Hari', 4: 'Om'}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 67

4.2 Accessing Values: -


Since Index is not defined, a Dictionaries value can be accessed by their keys.
Eg:
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
print ("Id of 1st employer is",data1['Id'])
print ("Id of 2nd employer is",data2['Id'])
print ("Name of 1st employer:",data1['Name'])
print ("Profession of 2nd employer:",data2['Profession'])
output:
Id of 1st employer is 100
Id of 2nd employer is 101
Name of 1st employer: Suresh
Profession of 2nd employer: Trainer

4.3 Updating Values: -


The item i.e., key-value pair can be updated. Updating means new item can be
added. The values can be modified.
Eg:
data1={'Id':100, 'Name':'Suresh', 'Profession':'Developer'}
data2={'Id':101, 'Name':'Ramesh', 'Profession':'Trainer'}
data1['Profession']='Manager'
data2['Salary']=20000
data1['Salary']=15000
print (data1)
print (data2)
output:
{'Id': 100, 'Name': 'Suresh', 'Profession': 'Manager', 'Salary': 15000}
{'Id': 101, 'Name': 'Ramesh', 'Profession': 'Trainer', 'Salary': 20000}

4.4 Deleting Items:


del statement is used for performing deletion operation. An item can be deleted from
a dictionary using the key. To delete or remove all the items in just one statement,
use the clear() function. Finally, to remove an entire dictionary from the memory,
we can use the del statement.
Eg:
data={100:'Ram', 101:'Suraj', 102:'Alok'}
del data[102]
print (data)
del data
print (data) #will show an error since dictionary is deleted.
output:
Traceback (most recent call last):
File "C:/Users/Admin/AppData/Local/Programs/Python/Python36-
32/cse4.py", line 5, in <module>

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 68
print (data) #will show an error since dictionary is deleted.
NameError: name 'data' is not defined
Note: - Keys must have unique values. Not even a single key can be duplicated in a
dictionary. If you try to add a duplicate key, then the last assignment is retained.

4.5 Nested Dictionaries: -


You can also define a dictionary inside another dictionary.
Eg:
students = {'Bhuvana' : {'DS':89,'Python':93,'DLD':92},
'Sai':{'DS':99,'Python':91,'DLD':78},
'Vanesh':{'DS':77,'Python':84,'DLD':98}}
print ("total dictionary =",students)
print (" one element =",students['Vanesh'])
print (" sub element =",students['Vanesh']['Python'])
output:
total dictionary = {'Bhuvana': {'DS': 89, 'Python': 93, 'DLD': 92}, 'Sai': {'DS': 99,
'Python': 91, 'DLD': 78}, 'Vanesh': {'DS': 77, 'Python': 84, 'DLD': 98}}
one element = {'DS': 77, 'Python': 84, 'DLD': 98}
sub element = 84
4.6 Methods and Functions of Dictionaries: -
Operation Description Example & Output
len(dict) Returns the length of Eg:
dictionary. That is, number of data={100:'Ram', 101:'Suraj',
items(key-value paris) 102:'Alok'}
print (data)
print (len(data))
output:
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
3
dict.clear() Deletes all entires in the Eg:
dictionary data={100:'Ram', 101:'Suraj',
102:'Alok'}
print (data)
data.clear()
print (data)
output:
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
{}
dict.copy() Returns a shallow copy of the Eg:
dictionary, i.e., the dictionary data={'Id':100 , 'Name':'Aakash' ,
returned will not have a 'Age':23}
duplicate copy of dict but will data1=data.copy()
have the same reference print (data)
print (data1)
data1['Age']=33
print (data)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 69
print (data1)
data['Name']='Ramesh'
print (data)
print (data1)
output:
{'Id': 100, 'Name': 'Aakash', 'Age': 23}
{'Id': 100, 'Name': 'Aakash', 'Age': 23}
{'Id': 100, 'Name': 'Aakash', 'Age': 23}
{'Id': 100, 'Name': 'Aakash', 'Age': 33}
{'Id': 100, 'Name': 'Ramesh', 'Age':
23}
{'Id': 100, 'Name': 'Aakash', 'Age': 33}
str(dictionar Gives the string representation Eg:
y) of a string. data1={100:'Ram', 101:'Suraj',
102:'Alok'}
print (str(data1))
output:
{100: 'Ram', 101: 'Suraj', 102: 'Alok'}
dict.keys() Returns a list of keys in the Eg:
dictionary data1={100:'Ram', 101:'Suraj',
102:'Alok'}
print (data1.keys())
output:
dict_keys([100, 101, 102])
dict.values() Returns a list of values in Eg:
dictionary data1={100:'Ram', 101:'Suraj',
102:'Alok'}
print (data1.values())
output:
dict_values(['Ram', 'Suraj', 'Alok'])
dict.items() Returns a list of tuples(key – Eg:
value pair) data1={100:'Ram', 101:'Suraj',
102:'Alok'}
print (data1.items())
output:
dict_items([(100, 'Ram'), (101,
'Suraj'), (102, 'Alok')])
dict.get(key) Returns the value for the key Eg:
passed as argument. If the key data={'Id':100 , 'Name':'Aakash' ,
is not present in dictionary, it 'Age':23}
will return the default value. If print (data.get('Age'))
no default value is specified print (data.get('Email'))
then it will return None output:
23
None
fromkeys(se Creates a new dictionary with Eg:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 70
quence)/ keys from seq and values set to subjects =['Ds','C++','MFCS','DLD']
fromkeys(se val. If no val is specified then, marks=dict.fromkeys(subjects,20)
q,value) None is assigned as default print(marks)
value output:
{'Ds': 20, 'C++': 20, 'MFCS': 20,
'DLD': 20}
dict1.updat Adds the key-value pairs of Eg:
e(dict2) dict2 to the key-value pairs of data1={100:'Ram', 101:'Suraj',
dict1 102:'Alok'}
data2={103:'Sanjay'}
data1.update(data2)
print (data1)
print (data2)
output:
{100: 'Ram', 101: 'Suraj', 102: 'Alok',
103: 'Sanjay'}
{103: 'Sanjay'}
in and not Checks whether a given key is Eg:
in present in dictionary or not data1={100:'Ram', 101:'Suraj',
102:'Alok'}
print (101 in data1)
print (104 in data1)
output:
True
False
Note: Slicing and concatenation on dict doesn't work because you can fetch values
only by key, not by position.
5. Difference between a List and Dictionary:
 A list is an ordered set of items. But, a dictionary is a data structure that is used
for matching one item(key) with another(value).
 In lists, you can use indexing to access a particular item. But, these indexes
should be a number. In dictionaries, you can use any type(immutable) of value
as an index. For example, when we write Dict[‘Name’], Name acts as index but it
is not a number but a string.
 Lists are used to look up a value whereas a dictionary is used to take one value
and look up another value. Dictionary is also known as a lookup table.
 The key-value pair may not be displayed in the order in which it was specified
while defining the dictionary. This is because python uses complex
algorithms(called hashing) to provide fast access to the items stored in the
dictionary.
The main advantage of a dictionary is that you don’t need to search for a value
one by one in the entire set of values, you can find a value instantly.
6. When to use which data structure?:-
 Use lists to store a collection of data that does not need random access.
 Use lists if the data has to be modified frequently.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 71
 Use a set if you want to ensure that every element in the data structure must be
unique.
 Use tuples when you want that your data should not be altered.
7.List Vs Tuple Vs Dictionary Vs Set: -
 Tuples are lists which cannot be edited. While tuples are immutable, lists on the
other hand are mutable. Hence, they can be easily edited. Tuples have fixed
size, so you cannot add or delete items from it. But you can easily add or delete
elements in a list.
 Due to the mutability difference, tuples are easier on memory and processor in
comparison to lists. This means that you can easily achieve performance
optimization by using tuples, wherever possible. Moreover, tuples are best used
as heterogeneous collections while lists are best used as homogenous collections
(where heterogeneous means that the items contained in a tuple may belong to
different types or concepts).
 Sets are used to store unordered values and do not have index. Unlike tuples
and lists, sets can have no duplicate data. However, like lists and unlike tuples,
you can use the add() function to add an element to a set and the update()
function to edit the elements in the set.
 Dictionary is used to store key-value pairs. Its underlying concept and usage is
absolutely different from that of list, tuple or set. Dictionaries are best data
structure for frequent lookup operations.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


How to Choose a DRM Software to protect your document?
Python Programming 1

CHAPTER
4

Functions, Modules and


Python Packages

Syllabus:
Functions - Defining Functions, Calling Functions, Passing Arguments, Keyword
Arguments, Default Arguments, Variable-length arguments, Anonymous Functions,
Fruitful Functions(Function Returning Values), Scope of the Variables in a Function
- Global and Local Variables.
Modules: Creating modules, import statement, from. Import statement, name
spacing

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 2
Python packages, Introduction to PIP, Installing Packages via PIP, Using Python
Packages
Functions: - A function is a self-contained block of one or more statements that
performs a special task when called.
Syntax: def function_name(parameters): <-Function Header
Statement1
Statement2
---- Function Body
----
----
Statementn
The syntax for the Python function contains a header and body. The function
header begins with the ‘def’ keyword. The def keyword signifies the beginning of the
function definition. The name of the function is followed by the def keyword. The
function header may contain zero or more number of parameters. These parameters
are called formal parameters. If a function contains more than one parameter then
all the prarameters are separated by commas. A function’s body is a block of
statements.
Ex:
def Display():
print("Welcome to Python Programming")

Display()

Parameters and arguments in a function:


Parameters are used to give inputs to a function. They are specified with a pair of
parentheses in the function definition. When a programmer calls a function, they
values are also passed to the function.
Ex:
def add(n):
sum=0
for i in range(1,n+1):
sum=sum+i
print("sum value=",sum)

n=int(input("enter n value"))
add(n)

Positional Arguments: - The parameters are assigned by default according to their


psotion, i.e. the furst argument I the call statement is assigned to the first
parameter listed in the function definition. Similarly, the second argument in the
call statement is assigned to the second parameter listed in the function’s definition
and so on.
Ex:
def display(Name,age):
print("Name =",Name,"age=",age)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 3
display("Ramesh",40)
display(35,"suresh")
Note: Python will show an error when an incorrect number of arguments are passed
to the function call. The arguments must match the prameters in order, number
and type as defined in the function.

Keyword Arguments: - A programmer can pass a keyword argument to a function


by using its corresponding parameter name rather than its position. This can be
done by simply typing Parameter_name=value in the function call.
Syntax to call a function using keyword argument is
Name_of_function(keyword1=value,keyword2=vaule…)
Ex:
def display(Name,age):
print("Name =",Name,"age=",age)
display("Ramesh",40)
display(age=35,Name="suresh")

Parameter with Default Values: Parameters within a function’s definition can have
default values. We can provide default value to a parameter by using assignment(=)
operator.
Ex:
def display(name,msg="Welcome to Python"):
print("Hello",name,msg)
display("Ramesh")

Ex: Write a program to calculate the area of a circle using the formula
Area=pi*(r)2
def area_circle(pi=3.14,radius=1):
area=pi*radius*radius
print("radius =",radius)
print("the area of Circle =",area)
area_circle()
area_circle(radius=5)
Ex:
def disp_values(a,b=10,c=20):
print("a= ",a," b= ",b,"c= ",c)
disp_values(15)
disp_values(50,b=30)
disp_values(c=80,a=25,b=35)
The Local and Global Scope of a Variable: variables and parameters that are
initialized within a function including parapeters, are said to exist in that function’s
local scope. Variables that exist in local scope are called local variables. Variables
that are assigned outside functions are said to exist in global scope. Thefore,
variables that exist in global scope are called global variables.
Ex:
p=20 #global variable p

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 4
def demo():
q=10 #local variable q
print("The value of Local variable q:",q)
#Access global variable p witin this function
print("the value of Global variables p:",p)
demo()
#Access global variable p outside the function demo
print("The value of global variable p:",p)
output:
The value of Local variable q: 10
the value of Global variables p: 20
The value of global variable p: 20

Note: Accessing a local variable outside the scope will cause an error

The global statement: -


a=20
def display():
global a
a=30
print("The value of a in function =",a)
display()
print("The value of an outside function =",a)
output:
The value of a in function = 30
The value of an outside function = 30
The global keyword has been used before the name of the variable to change the
value of the local variable. Since the value of the global variable is changed within
the function, the value of ‘a’ outside the function will be the most recent value of ‘a’

The return statement: The return statement is used to return value from the
function. It is lso used to return from a function, i.e., break out of the function.
Returning multiple values: It is possible to return multiple values in Python.
Assign returned multiple values to variable: - It is also possible for a function to
perform certain operations, return multiple values and assign the returned multiple
values to multiple variable.
def compute(n):
print("number =",n)
return (n*n,n*n*n)
square,cube=compute(4)
print("Square =",square,"Cube =",cube)
output:
number = 4
Square = 16 Cube = 64

Recursive Functions: - Function calls itself is called recursive function.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 5
Ex:
def fact(n):
if n==0:
return 1
else:
return n*fact(n-1)

n=int(input("enter n value"))
print("factorial value=",fact(n))
output:
enter n value5
factorial value= 120
Ex: Write a recursive function which computes the nth Fibnacci numbers are
defined as
Fib(0) = 1
Fib(1) = 1
Fib(n) = fib(n-1)+fib(n-2)
Write this as a python code and then find the 8th Fibonacci number
def fib(n):
if n==0 :
return 1
if n==1 :
return 1
return fib(n-1)+fib(n-2)
print("The value of 8th Fib number =",fib(8))
output:
The value of 8th Fib number = 34

Lambda Function: - These are also known as anonymous functions. Such kind of
functions are not bound to a name. They only have a code to execute that which is
associated with them.
A lambda function can take any number of arguments, but can only have one
expression.
The basic syntax for a lambda function is:
Name = lambda(variable):Code
lambda arguments : expression
Ex: without lambda function
def funct(x):
return x*x*x
print(funct(3))
Ex: with lambda function
cube=lambda x:x*x*x
print(cube(2))
Note: a) A lambda function does not contain a return statement
b) It contains a single expression as a body and not a block of statements as a
body.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 6

Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument will
be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number
you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

Modules: Modules contain definitions of functions, classes and variables which can
be utilized in other programs.
Some python modules are written in languages other than Python, most commonly
C or C++. Such a module is called an Extension Module.
Writing a module is like writing a simple python program in a file and saving
it in .py extension.
temp.py
def display(name):
print("Hello ",name," Welcome to python world")
Use a Module
The python import keyword lets you to include other modules in your program.
Now we can use the module we just created, by using the import statement:
main.py
import temp
temp.display("Ramesh")
output:
Hello Ramesh Welcome to python world
Note: The module which we have imported and the file, in which we have used the
import statement, should be in the same dictory.

The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):
temp.py
person1 = {
"name": "Ramesh",
"age": 36,
"country": "India"
}
main.py
import temp

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 7
a=temp.person1["age"]
print(a)
output:
36
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
import temp as t1
a=t1.person1["age"]
print(a)

Built-in Modules
There are several built-in modules in Python, which you can import whenever you
like.
import platform
x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import From Module


You can choose to import only parts from a module, by using the from keyword.
From modulename import */module
temp.py
def display(name):
print("Hello ",name," Welcome to python world")

person1 = {
"name": "Ramesh",
"age": 36,
"country": "India"
}
main.py
from temp import person1
print (person1["age"])
Note: When importing using the from keyword, do not use the module name when
referring to elements in the module.
Example: person1["age"], not temp.person1["age"]

Packages: -
A package is a collection of related modules stored in a directory or subdirectories.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 8
A package is basically a directory with python file and file with the name __init__.py.
In short, every directory inside the python path which contains a file name
__init__.py, will be treated as a package by python.
Import by full name:
import graphics.effects.invert
Import using from:
from graphics.filters.noise import edges
Import all items from a package:
From graphics import *

Creating Package:
Ex:
Temp
__init__.py
a.py
b.py
step1: Let us create a package(folder). The name of the package, say “temp”.
step2: Create __init__.py file inside the created package, viz “temp”. The directory
should contain a file named __init__.py. This file can be empty or it may contain
valid python code. Let keep it as empty file.
step3: Inside the package, let us create two different .py files, i.e. a.py and b.py.
step4: write python code inside a.py and b.py files. Thus, the contents of a.py and
b.py files are as follows.
#a.py
def display1():
print("Hello Ramesh")
def display2():
print("Hello Suresh")
#b.py
def display3():
print("Hello ashok")

#main.py
from temp import a,b
a.display1()
a.display2()
b.display3()

What is PIP?
PIP is a package manager for Python packages, or modules if you like.
Note: If you have Python version 3.4 or later, PIP is included by default.
Check if PIP is Installed
C:\Users\YRamesh>pip --version
pip 10.0.1 from c:\python37\lib\site-packages\pip (python 3.7)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 9

C:\Users\YRamesh>pip list
Package Version
--------------------- -------
Django 2.1.3
pip 10.0.1
pytz 2018.7
setuptools 39.0.1
virtualenv 16.1.0
virtualenvwrapper-win 1.2.5
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip'
command.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 1

CHAPTER
5

OOP’s in Python
Error and Exceptions

Syllabus:
OOPs in Python: Classes, ‘self variable’, Methods, Constructor Method,
Inheritance, Overriding Methods, Data hiding
Error and Exceptions: Difference between an error and Exception, Handling
Exception, try except block, Raising Exceptions, User Defined Exceptions

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 2

OOP’s Concepts:
The OOP’s (Object Oriented Programming System) Concepts are
1. Class
2. Object
3. Data Abstraction
4. Data Encapsulation
5. Inheritance
6. Polymorphism
Class: A Class is user defined data type it contains data and functions. The data is
called member data and functions are called member functions or methods.
Syntax : class classname:
Intilization
attributes
methods()
-------
Statementn
In Python, a class is defined by using a keyword class like a function definition
begins with the keyword def.
Object: It is instance of class. Object is an entity that has state and behavior.
Dot Operator:
The dot Operator(.) is used to access the instance variables and methods of class
objects.
Stud1.getdata( );
Stud1.name
It is also used to access classes and sub-packages from a package.
Data Abstraction: - Accessing the Data. The Access specifiers are private and
public
Data Encapsulation: - Wrapping up of data into single unit is called Data
Encapsulation.
Ex: Class
It is used to restrict access to methods and variables. In encapsulation, code
and data are wrapped together within a single unit from being modified by accident.
Inheritance: - It means acquire the properties of existing class. Main class is called
Base class, sub class class is called Derived class.
It specifies that one object acquires all the properties and behaviors of parent
object. By using inheritance, you can define a new class with a little or no changes
to the existing class. The new class is known as derived class or child class and
from which it inherits the properties is called base class or parent class.
It provides re-usability of the code.
Polymorphism: - Polymorphism is made by two words "poly" and "morphs". Poly
means many and Morphs means form, shape. It defines that one task can be
performed in different ways.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 3

Object-oriented vs Procedure-oriented Programming languages


Index Object-oriented Programming Procedural Programming
Object-oriented programming is an Procedural programming uses a list
1. approach to problem solving where of instructions to do computation
computation is done by using objects. step by step.
In procedural programming, It is not
It makes development and
2. easy to maintain the codes when
maintenance easier.
project becomes lengthy.
It doesn't simulate the real world. It
It simulates the real world entity. So
works on step by step instructions
3. real world problems can be easily
divided in small parts called
solved through oops.
functions.
It provides data hiding. so it is more
Procedural language doesn't provide
secure than procedural languages. You
4. any proper way for data binding so it
cannot access private data from
is less secure.
anywhere.
Example of object-oriented
Example of procedural languages
5. programming languages are: C++,
are: C, Fortran, Pascal, VB etc.
Java, .Net, Python, C# etc.

Creating Objects: Once a class is defined, the next job is to crate an object(or
instance) of that class. The object can then access class variables and class
methods using the dot operator(.).
objectname=classname()
Creating an object or instance of a class known as class instantiaton.
Ex:
class avanthi:
x=10
t1=avanthi()
print(t1.x)
output: 10
Note: Functions defined inside a class are called class methods.

Self Variable:
self is a reference variable which is alway pointing to current object. Within the
python class to refer current object we should use self variable

class Student:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 4
def __init__(self):
print(id(self))
s=Student()
print(id(s))
 The first argument to the constructor and instance method should be self.
 PVM is respobsible to provide value for self argument and we are not required to
provide explicitly.
 By using self, we can declare instance variables
 By using self, we can access instance variables
 Instead of self we can use any name... but recommedned to use self

Class Method and ‘self’ Argument: - Class methods(or functions defined in the
class) are exactly same as ordinary functions that we have been defining so far with
just one small difference. Class methods must have the first argument named as
self . This is the first argument that is added to the beginning of the parameter list.
You do not pass a value for this parameter when you call the method. Python
provides its value automatically. The self argument refers to the object itself. That
is, the object that has called the method. This means that even if a method that
takes no arguments, it should be defined to accept the self.
Ex:
class avanthi:
x=10
def display(self):
print("value=",self.x)
t1=avanthi()
t1.display()
output: value= 10
Ex: parameterized class method
class avanthi:
x=10
def display(self,k):
self.x=k
print("value=",self.x)
t1=avanthi()
t1.display(25)
output: value=25
Note: The statement inside the class definition must be properly indented.
Class methods or functions that begins with double underscore(__) are
special functions with a predefined and special meaning.

Constructor(The __init__()method: - It is a special member function It is


automatically called at the time of object creation. In python __init__() method is
constructor method. The __init__()method is automatically executed when an object
of a class is created. The method is useful to initialize the variables of the class
object. Note the __init__() is prefixed as well as suffixed by double underscores. The
__init__() method can be declared as,

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 5
def __init__(self,[args….]).
Ex:
class avanthi:
def __init__(self):
self.x=20
def display(self):
print("value=",self.x)

t1=avanthi()
t1.display()

Ex: parametrized constructor

class avanthi:
def __init__(self,k):
self.x=k
def display(self):
print("value=",self.x)

t1=avanthi(40)
t1.display()

Ex:
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print "rollno : ", self.rollno, ", name: ", self.name
emp1 = Student(121, "Bhuvana Kruthi")
emp2 = Student(122, "Sai Sruthi")
emp1.displayStudent()
emp2.displayStudent()
Output:
1. rollno : 121 , name: Bhuvana Kruthi
2. rollno : 122 , name: Sai Sruthi

Passing an object as parameter to a method:


Ex:
class test:
a=b=0
def __init__(self,x,y):
self.a=x
self.b=y
def equals(self,obj):
if(obj.a==self.a and obj.b==self.b):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 6
return True
else:
return False

t1=test(20,30)
t2=test(20,30)
t3=test(50,60)
print("Object1 == Object2 ",t1.equals(t2))
print("Object1 == Object3 ",t1.equals(t3))
Output:
Object1 == Object2 True
Object1 == Object3 False

Note: Constructor Overloading & Method overloading not available in python


Method Overloading: It simply refers to having multiple methods with the same
name which accept different sets of arguments.
Ex:
class sample:
def add(self,a,b):
print(a+b)
def add(self,a,b,c):
print(a+b+c)
t1=sample()
t1.add(5,10)
t1.add(5,10,5)
output:
Traceback (most recent call last):
File "E:\sample\main1.py", line 7, in <module>
t1.add(5,10)
TypeError: add() missing 1 required positional argument: 'c
This is because Python understand the last definition of the method add(self,a,b,c)
which takes only three arguments apart from self. Therefore, while calling the add()
method it is forced to pass three arguments. In other words, it forgets the previous
definition or method add()
Note: C++ and java support method overloading. Both the laguages allow more than
one method with same name and different signature. The type of method argument
defines the signature. In case of overloading, the signature determines which
method is actually being invoked.
However, Python does not allow method overloading based on type as it is not
strongly typed language.

Built-in Class Attributes: - Every class defined in Python has some built-in
attributes associated with it. Like other attributes, these attributes can also be
accessed using dot operator.
.__dict__: The attributes gives a dictionary containing the class’s or object’s(with
whichever it is accessed) namespace.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 7
.__doc__: The attribute gives the class documentation string if specified. In case the
documentation string is not specified, then the attribute returns None.
.__name__: The attribute returns the name of the class
.__module__: The attribute gives the name of the module in which the class(or the
object) is defined.
.__base__: The attribute is used to in inheritance to return the base classes in the
order of their occurrence in the base class list. As for now, it returns an empty
tuple.
Ex:
class Sample:
def __init__(self,x,y):
self.x=x
self.y=y
def display(self):
print("The value 1 is ",self.x)
print("The value 2 is ",self.y)
t1=Sample(20,30.5)
t1.display()
print("object.__dict__ = ",t1.__dict__)
print("object.__doc__ = ",t1.__doc__)
print("class.__name__ = ",Sample.__name__)
print("object.__module__ = ",t1.__module__)
print("class.__base__ = ",Sample.__base__)
output:
The value 1 is 20
The value 2 is 30.5
object.__dict__ = {'x': 20, 'y': 30.5}
object.__doc__ = None
class.__name__ = Sample
object.__module__ = __main__
class.__base__ = <class 'object'>

Display Class Attributes and Methods: There are two ways to determine the
attributes in class. One way is by using the inbuilt function dir() .
dir(name_of_class) or
dir(instance_of_class)
Ex:
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print ("rollno : ", self.rollno, ", name: ", self.name)
emp1 = Student(121, "Bhuvana Kruthi")
print(dir(emp1))
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 8
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__',
'__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'displayStudent',
'name', 'rollno']
An alternate way to display the attributes of a class is by suing a special class
attribute __dict__. The syntax to display of the attrubutes and methods of an
existing class using __dict__ is
Classname.__dict__
Ex:
class Student:
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print ("rollno : ", self.rollno, ", name: ", self.name)
emp1 = Student(121, "Bhuvana Kruthi")
print(emp1.__dict__)
output:
{'rollno': 121, 'name': 'Bhuvana Kruthi'}

Types of Variables:
1. Instance variables (Object level variables)
2. static variables (Class level variables)
3. Local Variables (Method level variables)
1. Instance variables/Object level variables: separate copy, which are declared by
self
2. static variables/class level variable: in class variable directly is called static
variable
3. local variables: the variable in side a method for temparory requirement/method
variable.
Instance variable: -If the value of a variable is varied from object to object. for every
object a separate copy will be created
where we have to declare instance variables:
1. Inside constructor by using self variable
2. Inside instance method by using self variable
3. From Outside of the class by using object reference variable
How to access instance variables:
1. within the class by using self
2. from outside of the class by using object reference
object.variable name
How to delete instance variables:
1. with in the class
del self.variablename
2. outside the class
del objectreference.variablename

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 9
static variable: - only one copy will be created at class level
Ex:
class Test:
a=10
def __init__(self):
self.b=20

t1=Test()
t1.b=777
Test.a=888
t2=Test()
print(t1.a,t1.b)
print(t2.a,t2.b)
Note: by object reference if we access : instance
by class name if we access : static
various places to declare static variables:
1. inside class directly
2. inside constructor by using class name
3. inside instance method by using class name
4. inside class method by using cls variable or classname
5. inside static method by using class name
6. from outside of the class also
How to access static variables:
1. inside constructor : either by self or by classname
2. inside instance method : either by self or by classname
3. inside class method: either by cls or by class name
4. inside static method : by classname
5. outside of class : either by object reference or by classname
How to delete static variables:
del classname.variablename
But inside class method
del classname.variablename
del cls.variablename

Class Variables and Object Variables(Instance Variables):


Variables are two types : Class Variables and Object Variables
Class variables are owned by the class and object variables are owned by the
object.
 If a class has n objects, then there will be n separate copies of the object
variable as each object will have its own object variable.
 The object variable is not shared between objects.
 A change made to the object variable by one object will not reflected in other
objects.
 If a class has one class variable, then there will be one copy only for that
variable. All the objects of that class will share the class variable.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 10
 Since there exists a single copy of the class variable, any change made to the
class variable by an object will be reflected in all other objects.
Ex:
class avanthi:
x=0
def __init__(self,k):
avanthi.x=avanthi.x+1
self.k=k
print("The object value is : ",k)
print("The value of class variable is :",avanthi.x)
t1=avanthi(10)
t2=avanthi(20)
t3=avanthi(30)
output:
The object value is : 10
The value of class variable is : 1
The object value is : 20
The value of class variable is : 2
The object value is : 30
The value of class variable is : 3

Class variables are shared by all instances.


Instance variable are unique to each instance.

Ex:
class Sample:
domain="Big Data Analystics"
def SetCourse(self,name):
#Defining an instance variable
self.name=name
#Declaring an Instance of class Sample
ob1=Sample()
#Declaring another Instance of class Sample
ob2=Sample()

ob1.SetCourse('Python')
ob2.SetCourse('Hadoop')

#class variable is hared by both instances ob1 and ob2


print(ob1.domain)
print(ob2.domain)

#Instance variable is unique to each instance


print(ob1.name)
print(ob2.name)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 11
output:
Big Data Analystics
Big Data Analystics
Python
Hadoop

Accessibility: - In Python, there are no keywords like public, protected or private.


All attributes and methods are public by default.
There in one way to define private in Python. The syntax to define private
attribute and methods is
__Attribute
__methodname()
To make an attribute and a method private, we need to add two underscores,
i.e. “__” in from of the attribute and the method’s name

Ex:
class person:
def __init__(self):
self.name="ramesh" # public attribute
self.__regno=123 # private attribute
def display(self):
print("Name =",self.name)
print("Regd No=",self.__regno)

p=person()
#access public attribute outside class
print("Name=",p.name)
p.display()
#try to access private variable outside class but fails
print("Regd no=",p.__regno)
p.display()
output:
Name= ramesh
Name = ramesh
Regd No= 123
Traceback (most recent call last):
File "E:\sample\main1.py", line 14, in <module>
print("Regd no=",p.__regno)
AttributeError: 'person' object has no attribute '__regno'
Ex: Public,Protected, private example
class Sample():
def __init__(self):
self.__pri ="I am Private"
self._pro = "I am Protected"
self.pub = " I am public"
#creating an Instance of class Sample

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 12
ob= Sample()
#Accessing public attribute and changing it s value
print(ob.pub)
ob.pub=ob.pub+"and my value cab be changed"
print(ob.pub)
#Accessing protected attribute
print(ob._pro)
#Accessing private attribute
print(ob.__pri)
Output:
I am public
I am publicand my value cab be changed
I am Protected
Traceback (most recent call last):
File "E:\sample\main1.py", line 15, in <module>
print(ob.__pri)
AttributeError: 'Sample' object has no attribute '__pri'
Ex:
cname='RameshSoft' public
_cname='RameshSoft' private
__cname='RameshSoft' Protected

Private Methods in Python:


When the attributes of an object can only be accessed inside the class, it is called
Private. Python use two underscores to hide a Method. Two underscores can also be
used to hid a Variable.
class Sample:
#Defining a Private method
def __pri(self):
print ("this is a private method")
#defining a public method
def pub(self):
print("This a public method")

If we try to use the private method, we will get error


ob=Sample()
ob.__pri()
But we can access Private methods using One undersocre('_') with class name
#private methods can be accessed like below
ob._Sample__pri()
This is a private method

Types of Methods:
1. Instance Methods
2. Class methods
3. Static methods

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 13
Instance Methods:
Instance methods must have self as a parameter, but you don’t need to pass this in
every time. Self is another Python special term. Inside any instance method, you
can use self to access any data or methods that may reside in your class. You won’t
be able to access them without going through self.
Ex:
class Student:
def __init__(self,name,marks):
self.name=name
self.marks=marks
#instance method
def display(self):
print("Hi",self.name)
print("Your Marks are: ",self.marks)
#instance method
def grade(self):
if self.marks>=60:
print("You got First Grade")
elif self.marks>=50:
print("You got Second Grade")
elif self.marks>=35:
print("You got Third Grade")
else:
print("Your are Failed")

s=Student("ramesh",70)
s.display()
s.grade()
Ex:
class Kls(object):
def __init__(self, data):
self.data = data
#instance method
def printd(self):
print(self.data)

ik1 = Kls('arun')
ik2 = Kls('seema')

ik1.printd()
ik2.printd()
Output:
arun
seema

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 14

After looking at the code sample and diagram:


 In 1 and 2, the arguments are passed to the method.
 On 3, the self argument refers to the instance.
 At 4, we do not need to provide the instance to the method, as it is handled
by the interpretor itself.

Class method: - Class methods are little different from these ordinary methods.
First, they are called by a class (not by instance of the class). Second, the first
argument of the class method is cls, not the the self.
Inside method implementation if we are using only static variables (without
instance variables) then we should go for class methods
atleast one instance variables --> instance method
not using any instance variable just we are using only static variables: class
methods
@classmethod --- decorator
cls means class cls must be required
Ex:
class Animal:
legs=4

@classmethod
def walk(cls,name):
print("{} walks with {} legs ".format(name,cls.legs))

Animal.walk("Dog")
Animal.walk("Cat")

Ex:
class Test:
count=0
def __init__(self):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 15
Test.count=Test.count+1
@classmethod
def noOfObjectsCreated(cls):
print("The number of Objects created :",Test.count) # Test.count or
cls.count

t1=Test()
t2=Test()
t3=Test()
Test.noOfObjectsCreated()
t1= noOfObjectsCreated()
t2= noOfObjectsCreated()
t3= noOfObjectsCreated()

Ex:
class rect:
def __init__(self,length,breadth):
self.length=length
self.breadth=breadth
def area(self):
return self.length*self.breadth
@classmethod
def square(cls,side):
return cls(side,side)
s=rect.square(10)
print("area=",s.area())
output:
area= 100

Static method: - Static methods are similar to class methods. The only difference
is that a static method does not receive any additional arguments.
Inside method if we are not using instance variables and static variables
General utility methods ---> static methods
@staticmethod --- decorator/anotation
calling using object or classname
without using decorator the function calling classobject.method name
Remember that, a static method does not use the self variable and is defined
using a built-in function named staticmethod.
Python has a handy syntax, called a decorator, to make it easier to apply the
staticmethod function to the method function definition. The syntax for using
staticmethod decorator is given as
@staticmethod
def name(args…):
statements
 Simple functions with no 'self' argument. Nested inside a class

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 16
 It is a function that has nothing to do with the instance but still belongs to
the class
 Works on Class attributes and not on Instance attribute
 Can be called through both Class and Instance
 Decorator @staticmethod is used to create a static method
A static method can be called either on the class or on an instance. When it
is called with an instance, the instance is ignored except for its class.
Ex:
class Choice:
def __init__(self,subjects):
self.subjects=subjects
@staticmethod
def validate_subject(subjects):
if "EEE" in subjects:
print("This option is no longer available. ")
else:
return True
subjects = ["CSE","ECE","EEE","MECH"]
if all(Choice.validate_subject(i) for i in subjects):
ch=Choice(subjects)
print("You have been allotted the subjects :",subjects)
Output: This option is no longer available.
Ex:
class Sample:
@staticmethod
def add(x,y):
print("The Sum:",x+y)
@staticmethod
def mul(x,y):
print("The Mul:",x*y)
@staticmethod
def average(x,y):
print("The average:",(x+y)/2)

Sample.add(10,20)
Sample.mul(10,20)
Sample.average(10,20)
Ex:
class Sample:
@staticmethod
def show1(attr):
print(attr)

#classing the static method


Sample.show1("This is a static method")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 17
Note:
instance variable --> instance methods
static variables ---> class methods
instance variables + static variables --> instance method
instance variables + local variables ---> instance method
static variables + local variables ---> class methods
local variabels ---> static methods

instance methods/object related methods


class methods/class related
static methods/utility methods
Instance Method Class Method Static Method
The most common method Can access limited Cannot access anything
type. Able to access data methods in the class. Can else in the class. Totally
and properties unique to modify class specific self-contained code.
each instance. details.
It is Object related It is Class related methods It is Utility methods
methods
A class method takes cls static method needs no
as first parameter specific parameters
A class method can access static method can’t access
or modify class state or modify it
No decorator @classmethod(mandatory) @staticmethod(optional)
class methods must have static methods know
class as parameter nothing about class state.
They are utility type
methods that take some
parameters and work
upon those parameters
If we are using atleast one If we are using only static If we are not using any
instance variable-instance variables but not instance instance or static variable-
method variables-class method static method
Inside method body if we Inside method body if we
are using atlease one are using only static
instance than compulsory variables then highly
we should declare that recommended to declare
method as instance that method as class
method method
The first argument to the The fist argument to the
instance method should classmethod should be
be self, whcih is reference cls, whcih is reference to
to current object and by current object and by
using self, we can access using self, we can access
instance variable inside instance variable inside
method method

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 18
Inside instance method we Inside classmethod we can
can access both instance access only static
and static variables variables and we cannot
access instance variables
we can call instance we can call classmethod
method by using object either by using object
reference reference or by using class
name, but recommendned
by use classname
Ex:
# Python program to demonstrate
# use of class method and static method.
from datetime import date

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

# a class method to create a Person object by birth year.


@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)

# a static method to check if a Person is adult or not.


@staticmethod
def isAdult(age):
return age > 18

person1 = Person('mayank', 21)


person2 = Person.fromBirthYear('mayank', 1996)

print (person1.age)
print (person2.age)

# print the result


print (Person.isAdult(22))
output:
21
22
True

How to access members of one to another class


Ex:
class Employee:
def __init__(self,eno,ename,esal):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 19
self.eno=eno
self.ename=ename
self.esal=esal
def display(self):
print("Employee number :", self.eno)
print("Employee Name :", self.ename)
print("Employee Salary :", self.esal)

class Test:
def modify(emp):
emp.esal=emp.esal+10000
emp.display()

e=Employee(100,"Ramesh",60000)
Test.modify(e)
Output:
Employee number : 100
Employee Name : Ramesh
Employee Salary : 70000

Inner Class: An inner class or nested class is a defined entirely within the body of
another class. If an object is created using a class, the object inside the root class
can be used. A class can have more than one inner classes. Without existing one
type of object if there is no change of existing another type of object, then we should
go for inner classes
Ex:
class Outer:
def __init__(self):
print("Outer class object creation")

class Inner:
def __init__(self):
print("Inner class Object creation..")
def m1(self):
print("Inner class method")

o=Outer()
i=o.Inner()
i.m1()
or
i=Outer().Inner()
i.m1()
Ex:
class Person:
def __init__(self,name,dd,mm,yyyy):
self.name=name

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 20
self.dob=self.Dob(dd,mm,yyyy)

def display(self):
print("Name =",self.name)
self.dob.display()

class Dob:
def __init__(self,dd,mm,yyyy):
self.dd=dd
self.mm=mm
self.yyyy=yyyy

def display(self):
print("DOB={}/{}/{}".format(self.dd,self.mm,self.yyyy))

p=Person("ramesh",8,5,1978)
p.display()

Ex:
class Human:
def __init__(self):
self.name = 'Ramesh'
self.head = self.Head()
self.brain = self.Brain()
class Head:
def talk(self):
return 'talking...'
class Brain:
def think(self):
return 'thinking...'

t = Human()
print (t.name)
print (t.head.talk())
print (t.brain.think())
output:
Ramesh
talking...
thinking...

Calling a Class method from another method[Nested Method]:


You can call a class method from antoher class method by using the self.
Ex:
class avanthi:
def __init__(self,k):
self.k=k

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 21
def display(self):
print("The value is =",self.k)
def add(self):
self.k=self.k+5
self.display()
t1=avanthi(10)
t1.add()
Output: The value is = 15

Setter and Getter Methods:


The getters and setters methods are used in many object oriented programming
languages to provide data encapsulation (binding data and functions in a single
entity). There are also known as mutator methods. While getter method is used for
retrieving data, setter method, on the other hand, is sused to set a new value for the
data(for changing the data).
Setter methods to set values to the instance variables
Getter methods to get values of instance variables
Syntax:
def setVariableName(self,variablename):
self.variableName=variable

def getVariableName(self):
return self.variableName
Ex:
class Student:
def setName(self,name):
self.name=name
def getName(self):
return self.name
def setMarks(self,marks):
self.marks=marks
def getMarks(self):
return self.marks

l=[]
n=int(input("enter the number of students:"))
for i in range(n):
s=Student()
name=input("enter Name of the student: ")
marks=int(input("enter Marks of the student: "))
s.setName(name)
s.setMarks(marks)
l.append(s)

for s in l:
print("Student Name: ",s.getName())

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 22
print("Student Marks: ",s.getMarks())
print()

Ex:
class Sample:
def __init__(self,val):
self.val=val
def get_val(self):
return self.val
def set_val(self,val):
self.val=val

s=Sample(10)
s.set_val(20)
print(s.get_val())
output:
20

However, there is no data encapsulation in the above code. Data can be


openly accessed from anywhere in the program. In C++ and Java, private attributes
are used with getters and and setters. But to support encapsulation in the true
sense, Python supports a class with a @property and @setter decorators.
Ex:
class Sample:
def __init__(self,val):
self.val=val
@property
def val(self):
return self.__val
@val.setter
def val(self,val):
self.__val=val

s=Sample(10)
s.val=20
print(s.val)
output:
20
Note: A method which is used for getting a value is decorated with @property.
Similarly, the method which sets a value of an instance variable – setter is
decorated with @x. setter, where x is the name of the function.
Another way:
Ex:
class Sample:
def __init__(self,val):
self.val=val

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 23

def get_val(self):
return self.__val

def set_val(self,val):
self.__val=val

val=property(get_val,set_val)
s=Sample(10)
s.val=20
print(s.val)
Ex: private getter and setter methods
class Sample:
def __init__(self,val):
self.val=val

def __get_val(self):
return self.__val

def __set_val(self,val):
self.__val=val

val=property(__get_val,__set_val)
s=Sample(10)
s.val=20
print(s.val)
Ex:
class Student:
def __init__(self,first_name,last_name):
self.__first_name=first_name
self.__last_name=last_name
@property
def name(self):
return ("%s %s" %(self.__first_name,self.__last_name))
s=Student("Ramesh","Kumar")
print(s.name)
The Key role of a delete is to delete the attribute from our object. However, note that
the getter,setter and delete methods must all have the same name as shonw in the
program given below
Ex:
class Sample:
def __init__(self,val):
self.val=val
@property
def val(self):
return self.__val

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 24
@val.setter
def val(self,val):
self.__val=val
@val.deleter
def val(self):
del self.val
s=Sample(20)
s.val=10
print(s.val)

Garbage Collection (Destroying Objects):


Python performes automatic garbage collection. This means that it deletes all the
objects(built-in types or users defined like class objects) automatically that are no
longer needed and that have gone out of scope to free the memory space. The
process by which Python periodically reclaims unwanted memory is known as
garbage collection.
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
If object does not contain any reference variable. Eligible for GC.
gc module
1.gc.isenabled()
2.gc.disable()
3.gc.enable()
job of Destructor is not to destory object just perform clean up activities destroying
an object is the responsibility of GC
Ex:
import time
class Test:
def __init__(self):
print("Object Initializtion ... ")
def __del__(self):
print("Fulfilling Last wish and performing cleanup activities...")

t1=Test()
print("Using t1 based on our requirement")
time.sleep(5)
print("Work with t1 completed making eligible for gc")
t1=None
time.sleep(10)
print("End of applicaton")

output:
Object Initializtion ...

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 25
Using t1 based on our requirement
Work with t1 completed making eligible for gc
Fulfilling Last wish and performing cleanup activities...
End of applicaton

The __del__()method:
The __del__()method is automatically called when an object is goint out of
scope. This is the time when an object will no longer be used and its occupied
resources are returned back to the system so that they can be reused as and when
required.
The __del__() method is analogous to destructors in C++ and Java
Ex:
class avanthi:
x=0
def __init__(self,k):
avanthi.x=avanthi.x+1
self.k=k
print("The object value is : ",k)
print("The value of class variable is :",avanthi.x)
def __del__(self):
avanthi.x=avanthi.x-1
print("Object with value %d is going out of scope"%self.k)
t1=avanthi(10)
t2=avanthi(20)
t3=avanthi(30)
del t1
del t2
del t3
Output:
The object value is : 10
The value of class variable is : 1
The object value is : 20
The value of class variable is : 2
The object value is : 30
The value of class variable is : 3
Object with value 10 is going out of scope
Object with value 20 is going out of scope
Object with value 30 is going out of scope
Ex:
class Sample:
def __init__(self,name):
self.name=name
def __del__(self):
print("Destrcutor started")

#creating instance of class Edureka

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 26
ob1=Sample("Python")
ob2=ob1
#Calling del method
del ob1
del ob2

Operator Overloading:
the same built-in operator or function shows different behavior for objects of
different classes, this is called Operator Overloading.
Ex:
# Python program to show use of
# + operator for different purposes.

print(1 + 2)

# concatenate two strings


print("Ramesh"+"Kumar")

# Product two numbers


print(3 * 4)

# Repeat the String


print("Ramesh"*4)
Output:
3
RameshKumar
12
RameshRameshRameshRamesh

we have to add two objects with binary ‘+’ operator it throws an error, because
compiler don’t know how to add two objects. So we define a method for an operator
and that process is called operator overloading. We can overload all existing
operators but we can’t create a new operator. To perform operator overloading,
Python provides some special function or magic function that is automatically
invoked when it is associated with that particular operator. For example, when we
use + operator, the magic method __add__ is automatically invoked in which the
operation for + operator is defined.
Ex:
class Sample:
def __init__(self,x):
self.x=x

x1=Sample(10)
x2=Sample(20)
print(x1+x2)
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 27
Traceback (most recent call last):
File "E:\sample\main1.py", line 7, in <module>
print(x1+x2)
TypeError: unsupported operand type(s) for +: 'Sample' and 'Sample'

Overloading binary + operator in Python :


When we use an operator on user defined data types then automatically a special
function or magic function associated with that operator is invoked. Changing the
behavior of operator is as simple as changing the behavior of method or function.
You define methods in your class and operators work according to that behavior
defined in methods. When we use + operator, the magic method __add__ is
automatically invoked in which the operation for + operator is defined. There by
changing this magic method’s code, we can give extra meaning to the + operator.
Ex:
class Sample:
def __init__(self,x):
self.x=x
#special function or magic function
def __add__(self,other):
return self.x+other.x
x1=Sample(10)
x2=Sample(20)
print(x1+x2)
output:
30
Python magic methods or special functions for operator overloading
Operation Special Method Description
X+Y __add__(self,other) Add X and Y
X-Y __sub__(self,other) Subtract X and Y
X*Y __mul__(self,other) Product of X and Y
X/Y __truediv__(self,other) Y divides X and it shows the
quotient as its output
X//Y __floordiv__(self,other) Floored quotient of X and Y
X%Y __mod__(self,other) X mod Y gives a remainder when
dividing X by Y
-X __neg__(self) Arithmetic negation of X
X**Y __pow__(self,other) Power

X==Y __eq__(self,other) Is X equal to Y?


X<Y __lt__(self,other) Is X less than Y?
X>Y __gt__(self,other) Is X greater than Y
X<=Y __le__(self,other) Is X less than or equal to Y?
X>=Y __ge__(self,other) Is X greater than or equal to Y?
X!=Y __ne__(self,other)
abs(x) __abs__(self) Absolute value of X

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 28
float(x) __float__(self) Float equivalent of X
str(x) __str__(self) String representation of X
iter(x) __itr__(self) Iterator of X
hash(x) __hash__(self) Generates an integer hash code
for X
len(x) __len__(self) Length of X

X+=Y __iadd__(self,other) X=X+Y


X-=Y __isub__(self,other) X=X-Y
X*=Y __imul__(self,other) X=X*Y
X/=Y __idiv__(self,other) X=X/Y
X**=Y __ipow__(self,other) X=pow(x,y)
X%=Y __imod__(self,other) X=X%Y

X&Y __and__(self,other)
X|Y __or__(self,other)
X^Y __xor__(self,other)
~X _invert(self)
X<<Y __lshift__(self,other)
X>>Y __rshift__(self,other)

X&=Y __iand__(self,other)
X|=Y __ior__(self,other)
X^=Y __ixor__(self,other)
~=X _iinvert(self)
X<<=Y __ilshift__(self,other)
X>>=Y __irshift__(self,other)

in __contains__(self, value) Membership operator


[index] __getitem__(self, index) Item at index

Ex: Write a program to perform the following operations on complex numbers


a) Addition
b) Subtraction
c) Multiplication
d) Check if two complex numbers or equal or not
e) Check if C1>=C2
f) Check if C1<=C2

class Complex:
def __init__(self,real,imag):
self.real=real
self.imag=imag

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 29
def display(self):
print("(",self.real,"+i",self.imag,")")

def __add__(self,other):
return Complex(self.real+other.real,self.imag+other.imag)

def __sub__(self,other):
return Complex(self.real-other.real,self.imag-other.imag)

def __mul__(self,other):
m=self.real*other.real-self.imag*other.imag
n=self.real*other.imag+self.imag*other.real
return Complex(m,n)

def __eq__(self,other):
return self.real==other.real and self.imag==other.imag

def __le__(self,other):
return self.real<other.real and self.imag<other.imag

def __ge__(self,other):
return self.real>other.real and self.imag>other.imag

a=int(input("enter the first complex number real value"))


b=int(input("enter the first complex number imag value"))
c=int(input("enter the second complex number real value"))
d=int(input("enter the second complex number imag value"))
c1=Complex(a,b)
c2=Complex(c,d)
c3=Complex(0,0)

print("The first complex number")


c1.display()

print("The second complex number")


c2.display()

print("Additon value : ")


c3=c1+c2
c3.display()

print("Subtraction value : ")


c3=c1-c2
c3.display()

print("Multiplication value : ")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 30
c3=c1*c2
c3.display()

print("Compare two Complex numbers : ")


print((c1==c2))

print("Checking if c1 is Greater than c2: ")


print(c1>=c2)

print("Checking if c1 is Less than c2: ")


print(c1<=c2)

output :
enter the first complex number real value2
enter the first complex number imag value1
enter the second complex number real value5
enter the second complex number imag value6
The first complex number
( 2 +i 1 )
The second complex number
( 5 +i 6 )
Additon value :
( 7 +i 7 )
Subtraction value :
( -3 +i -5 )
Multiplication value :
( 4 +i 17 )
Compare two Complex numbers :
False
Checking if c1 is Greater than c2:
False
Checking if c1 is Less than c2:
True

Inheritance: It means acquire the properties of super class. The technique of


creating a new class from an existing class is called inheritance. The concept of
inheritance is therefore, frequently used to implement the “is-a” relationship.
In top-down approach, generalized classes are designed first and then
specialized classes are dervived by inheriting/extending the generalized classes.
Generalized class
Person

Top-down
Doctor Patient approach

Dentist Kumar, HOD of CSE,


Y. Ramesh Surgeon
Avanthi Institute of Engg. & Technology
Python Programming 31

Specialized class

Types of Inheritance:
The five types of inheritance are:
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Multipath inheritance
6. Hybrid inheritance
1. In single inheritance there is only one base class (super class) and only one
derived class(super class)
X

Y
2. In multiple inheritance there is only one derived class that is derived from
several base classes i.e., there are several base classes but only one derived
class.
X Y

3. In multi level inheritance the class is derived from the derived class

Z
4. In hierarchical inheritance there is only one base class but many derived
classes. These derived classes are derived only from one base class.

W Y Z
Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology
Python Programming 32

5. In Multipath inheritance
X

W Z

Y
Note: Every class in Python is derived from the object class. The object class is
defined in the Python library.
What is object class?
Like Java Object class, in Python (from version 3.x), object is root of all classes.
In Python 3.x, “class Test(object)” and “class Test” are same.
In Python 2.x, “class Test(object)” creates a class with object as parent (called new
style class) and “class Test” creates old style class (without object parent).
Syntax:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>
Ex:
class avanthi1:
def assign1(self,x):
self.x=x
class avanthi2(avanthi1):
def assgin2(self,y):
self.y=y
def display(self):
print("x value=",self.x,"y value=",self.y)
t1=avanthi2()
t1.assign1(5)
t1.assgin2(20)
t1.display()
output: x value= 5 y value= 20

Ex:
class sample:
def setValues(self,x,y):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 33
self.x=x
self.y=y

class sample1(sample):
def display(self):
print("X value=",self.x,"Y value=",self.y)

t1=sample1()
t1.setValues(20,30)
t1.display()
output:
X value= 20 Y value= 30

Ex:
class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
d=Dog()
d.eat()
d.bark()
Output:
1. Eating...
2. Barking...

Multilevel Inheritance Example


Syntax:
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Ex:
class Animal:
def eat(self):
print 'Eating...'
class Dog(Animal):
def bark(self):
print 'Barking...'
class BabyDog(Dog):
def weep(self):
print 'Weeping...'
d=BabyDog()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 34
d.eat()
d.bark()
d.weep()

Output:
Eating...
Barking...
Weeping

How to check if a class is subclass of another?


Python provides a function issubclass() that directly tells us if a class is subclass of
another class.
Ex:
class Base(object):
pass # Empty Class

class Derived(Base):
pass # Empty Class

# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))

d = Derived()
b = Base()

# b is not an instance of Derived


print(isinstance(b, Derived))

# But d is an instance of Base


print(isinstance(d, Base))
output:
True
False
False
True

Multiple Inheritance:
Syntax :
class Base1:
statement block
class Base2:
statement block
class Derived(Base1,Base2):
statement block

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 35
Python supports multiple inheritance also. You can derive a child class from more
than one base (parent) class.
The multiderived class inherits the properties of both class base1 and base2.
Syntax:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
Or
class Base1:
pass

class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Example:
class MySuperClass1():

def method_super1(self):
print("method_super1 method called")

class MySuperClass2():

def method_super2(self):
print("method_super2 method called")

class ChildClass(MySuperClass1,MySuperClass2):

def child_method(self):
print("child method")

c = ChildClass()
c.method_super1()
c.method_super2()

output:
method_super1 method called
method_super2 method called

Ex:
class First(object):
def __init__(self):
super(First, self).__init__()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 36
print("first")

class Second(object):
def __init__(self):
super(Second, self).__init__()
print("second")

class Third(Second, First):


def __init__(self):
super(Third, self).__init__()
print("third")

Third();
Output:
first
second
third

Method Overriding:
In a class hierarchy, when a method in a sub class has the same name nd same
header as that of a super class then the method in the sub class is said to override
the method in the super class. When an overridden method is called, it always
invokes the method defined by its subclass. The same method defined by the super
class is hidden.
Ex:
class avanthi1:
def display(self):
print("Hai Students")
class avanthi2(avanthi1):
def display(self):
print("Hello Students")
t1=avanthi2()
t1.display()
output:
Hello Students
Ex: using super() key word call the super class method
class avanthi1:
def display(self):
print("Hai Students")
class avanthi2(avanthi1):
def display(self):
print("Hello Students")
super().display()
t1=avanthi2()
t1.display()
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 37
Hello Students
Hai Students

Multipath Inheritance:

MRO (Method Resolution Order):


In multi-level inheritance scenario, any specified attribute is first searched in the
current class (Dervided Class 2). It is not found there, then the Derived class 1 is
searched, if it is not found even there then the Base class is searched. If the
attribute is still not found, then finally the object class is checked. This order is also
called linearization of Derived class 2. Correspondingly, the set of rules used to find
this linearization order is called Method Resolution Order (MRO).
The Diamond Problem or the, deadly diamond of death''

The "diamond problem" (sometimes referred to as the "deadly diamond of death") is


the generally used term for an ambiguity that arises when two classes B and C
inherit from a superclass A, and another class D inherits from both B and C. If
there is a method "m" in A that B or C (or even both of them)) has overridden, and
furthermore, if does not override this method, then the question is which version of
the method does D inherit? It could be the one from A, B or C.

Let's look at Python. The first Diamond Problem configuration is like this: Both B
and C override the method m of A:
class A:
def m(self):
print ("m of A called")

class B(A):
def m(self):
print ("m of B called")

class C(A):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 38
def m(self):
print ("m of C called")

class D (B, C):


pass

x=D()
x.m()
If you call the method m on an instance x of D, i.e. x.m(), we will get the output "m
of B called". If we transpose the order of the classes in the class header of D in
"class D (C, B):", we will get the output "m of C called".

The case in which m will be overridden only in one of the classes B or C, e.g. in C:
class A:
def m(self):
print("m of A called")

class B(A):
pass

class C(A):
def m(self):
print("m of C called")

class D(B,C):
pass

x = D()
x.m()
Principially, two possibilities are imaginable: "m of C" or "m of A" could be used

We call this script with Python2.7 (python) and with Python3 (python3) to see
what's happening:
$ python diamond1.py
m of A called
$ python3 diamond1.py
m of C called

super and MRO


We have seen in our previous implementation of the diamond problem, how Python
"solves" the problem, i.e. in which order the base classes are browsed through. The
order is defined by the so-called "Method Resolution Order" or in short MRO.
We will extend our previous example, so that every class defines its own method m:
class A:
def m(self):
print("m of A called")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 39

class B(A):
def m(self):
print("m of B called")

class C(A):
def m(self):
print("m of C called")

class D(B,C):
def m(self):
print("m of D called")
Let's apply the method m on an instance of D. We can see that only the code of the
method m of D will be executed. We can also explicitly call the methods m of the
other classes via the class name, as we demonstrate in the following interactive
Python session:
>>> from super1 import A,B,C,D
>>> x = D()
>>> B.m(x)
m of B called
>>> C.m(x)
m of C called
>>> A.m(x)
m of A called

Now let's assume that the method m of D should execute the code of m of B, C and
A as well, when it is called. We could implement it like this:
class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)
A.m(self)

The output is what we have been looking for:


>>> from mro import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of C called
m of A called

But it turns out once more that things are more complicated than it seems. How
can we cope with the situation, if both m of B and m of C will have to call m of A as

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 40
well. In this case, we have to take away the call A.m(self) from m in D. The code
might look like this, but there is still a bug lurking in it:
class A:
def m(self):
print("m of A called")

class B(A):
def m(self):
print("m of B called")
A.m(self)

class C(A):
def m(self):
print("m of C called")
A.m(self)

class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)

The bug is that the method m of A will be called twice:


>>> from super3 import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of A called
m of C called
m of A called

One way to solve this problem - admittedly not a Pythonic one - consists in splitting
the methods m of B and C in two methods. The first method, called _m consists of
the specific code for B and C and the other method is still called m, but consists
now of a call "self._m()" and a call "A.m(self)". The code of the method m of D
consists now of the specific code of D 'print("m of D called")', and the calls
B._m(self), C._m(self) and A.m(self):
class A:
def m(self):
print("m of A called")

class B(A):
def _m(self):
print("m of B called")
def m(self):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 41
self._m()
A.m(self)

class C(A):
def _m(self):
print("m of C called")
def m(self):
self._m()
A.m(self)

class D(B,C):
def m(self):
print("m of D called")
B._m(self)
C._m(self)
A.m(self)

Our problem is solved, but - as we have already mentioned - not in a pythonic way:
>>> from super4 import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of C called
m of A called

The optimal way to solve the problem, which is the "super" pythonic way, consists
in calling the super function:
class A:
def m(self):
print("m of A called")

class B(A):
def m(self):
print("m of B called")
super().m()

class C(A):
def m(self):
print("m of C called")
super().m()

class D(B,C):
def m(self):
print("m of D called")
super().m()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 42

It also solves our problem, but in a beautiful design as well:


>>> from super5 import D
>>> x = D()
>>> x.m()
m of D called
m of B called
m of C called
m of A called

The super function is often used when instances are initialized with the __init__
method:
class A:
def __init__(self):
print("A.__init__")

class B(A):
def __init__(self):
print("B.__init__")
super().__init__()

class C(A):
def __init__(self):
print("C.__init__")
super().__init__()

class D(B,C):
def __init__(self):
print("D.__init__")
super().__init__()

We demonstrate the way of working in the following interactive session:


>>> from super_init import A,B,C,D
>>> d = D()
D.__init__
B.__init__
C.__init__
A.__init__
>>> c = C()
C.__init__
A.__init__
>>> b = B()
B.__init__
A.__init__
>>> a = A()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 43
A.__init__

The question arises how the super functions makes its decision. How does it decide
which class has to be used? As we have already mentioned, it uses the so-called
method resolution order(MRO). It is based on the "C3 superclass linearisation"
algorithm. This is called a linearisation, because the tree structure is broken down
into a linear order. The mro method can be used to create this list:
>>> from super_init import A,B,C,D
>>> D.mro()
[<class 'super_init.D'>, <class 'super_init.B'>, <class 'super_init.C'>, <class
'super_init.A'>, <class 'object'>]
>>> B.mro()
[<class 'super_init.B'>, <class 'super_init.A'>, <class 'object'>]
>>> A.mro()
[<class 'super_init.A'>, <class 'object'>]

super () keyword:
Ex: Without super keyword
class demo:
a=b=c=0
def __init__(self,x,y,z):
self.a=x
self.b=y
self.c=z
def display(self):
print(self.a,self.b,self.c)

class demo1(demo):
d=0
def __init__(self,x,y,z,l):
self.a=x
self.b=y
self.c=z
self.d=l
def display(self):
print(self.a,self.b,self.c,self.d)

b1=demo(100,200,300)
print("Contents of Base class ")
b1.display()
b2=demo1(10,20,30,40)
print("Contents of Derived class")
b2.display()
output:
Contents of Base class
100 200 300

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 44
Contents of Derived class
10 20 30 40
Super to call super class constructor:
Any subclass can call the constructor, i.e., the __init__method defined by its super
class by making use of super.
super().__init__(Parameters of super class constructor)
Ex:
class demo:
a=b=c=0
def __init__(self,x,y,z):
self.a=x
self.b=y
self.c=z
def display(self):
print(self.a,self.b,self.c)

class demo1(demo):
d=0
def __init__(self,x,y,z,l):
self.d=l
super().__init__(x,y,z)
def display(self):
print(self.a,self.b,self.c,self.d)

b1=demo(100,200,300)
print("Contents of Base class ")
b1.display()
b2=demo1(10,20,30,40)
print("Contents of Derived class")
b2.display()
output:
Contents of Base class
100 200 300
Contents of Derived class
10 20 30 40
Super() keyword:
class A:
def m1(self):
print("A Class Method")
class B(A):
def m1(self):
print("B Class Method")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 45
class C(B):
def m1(self):
print("C Class Method")
class D(C):
def m1(self):
print("D Class Method")
class E(D):
def m1(self):
super().m1()

e=E()
e.m1()
output:
D Class Method

class A:
def m1(self):
print("A Class Method")
class B(A):
def m1(self):
print("B Class Method")
class C(B):
def m1(self):
print("C Class Method")
class D(C):
def m1(self):
print("D Class Method")
class E(D):
def m1(self):
B.m1(self)

e=E()
e.m1()
output:
B Class Method

Another way:
super(D,self).m1() call to D super class
Note:
1. From child class by using super() we cannnot call parent class instance variables
we should use self only.
2. From child class by using super() method we can call parent class static variables

class P:
def __init__(self):
print("Parent constructor")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 46
def m1(self):
print("Parent instance method")
@classmethod
def m2(cls):
print("Parent class method")
@staticmethod
def m3():
print("Parent static method")

class C(P):
def __init__(self):
super().__init__()
super().m1()
super().m2()
super().m3()

c=C()
output:
Parent constructor
Parent instance method
Parent class method
Parent static method

Ex:
class P:
def __init__(self):
print("Parent constructor")
def m1(self):
print("Parent instance method")
@classmethod
def m2(cls):
print("Parent class method")
@staticmethod
def m3():
print("Parent static method")

class C(P):
def method1(self):
super().__init__()
super().m1()
super().m2()
super().m3()

c=C()
c.method1()
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 47
Parent constructor
Parent constructor
Parent instance method
Parent class method
Parent static method

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 to outsiders.
Ex:
class avanthi:
__x = 0
def count(self):
self.__x += 1
print (self.__x)
t1 = avanthi()
t1.count()
t1.count()
print (t1.__x)
output:
1
2
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\add.py",
line 9, in <module>
print (t1.__x)
AttributeError: 'avanthi' object has no attribute '__x'
Python protects those members by internally changing the name to include the
class name. You can access such attributes as object._className__attrName. If you
would replace your last line as following, then it works for you:
print (t1._avanthi__x)
.

Exception Handling:
Errors: The errors can be divided into two types : compilation errors and runtime
errors
Compilation Errors:
Errors that occur during compilation are called compilation errors or syntax errors.
These errors are usually easy to detect because the compiler tells you where they
are (including line numbers) and the reasons for them.
Runtime Errors:
Runtime errors are the errors that cause a program to terminate abnormally. The
following are the main reasons for runtime errors:
a) Input errors b) System errors or Hardware errors c)Logical errors
a) Input Errors:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 48
An input error occurs when the user enters an unexpected input the program
cannot handle. If the program expects to read number, but instead the user enters
a string. This causes data-type (or data parsing) error to occur in the program. To
avoid the input error, the program should prompt the user to enter the correct type
of values.
b) System Errors or Hardware Errors:
System errors rarely happen. Unreliable system software and hardware
malfunctions can cause a program to abort. System errors are beyond a
programmer’s control and there is little that he can do when such errors are
encountered. For mission-critical applications, fault tolerance computers can be
deployed to improve system reliability.
c) Logical errors:
Logical errors cause the program to either generate incorrect results or terminate
abnormally. There are many causes for logical errors. The errors are called bugs.
The process of finding errors is called debugging. A common approach to
debugging is to use a combination of methods to narrow down to the part of the
program where the bug is. Debugging a large program can be daunting task.

Most common run time errors are


 Dividing an integer by zero
 Accessing an element that s out of the bounds of an array
 Trying to store a value in to an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclass
 Passing a parameter that is not in a valid range of value for method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array
 Using a null object reference as a legitimate object reference to access a
method or a variable
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
 And many more
Ex:
a=10
b=5
c=5
x=a/(b-c)
print(x)
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python36-32\add.py",
line 4, in <module>
x=a/(b-c)
ZeroDivisionError: division by zero
Exception: - An exception is a condition that is caused by a runtime error in the
program. When the python interpreter encounters an error such as dividing an
integer by zero, it creates an exception object and throws it. (that is informs use
that an error as occurred);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 49
If the exception object is not caught and handled properly, the interpreter will
display an error message as shown in the output of above program and will
terminate the program. If we want the program we continue with the execution of
the remaining code, then we should try to catch the exception object thrown by the
error condition and they display an appropriate message for taking corrective
actions. This task is known is Exception Handling.
The purpose of exception handling mechanism is to provide a means to detect
and report an “exceptional circumstance” so that appropriate action can be taken.
The mechanism suggests incorporation of separate error handling code that
performs the following tasks.
 Find the problem (hit the exception)
 Inform that an error has occurred (throw the exception)
 Receive the error has occurred (catch the exception)
 Take corrective actions. (handle the exception)
 Syntax of exception handling code: - The basic concepts of exception
handling are throwing an exception and catching it.

Handling Exceptions: -
Exception can be said to be any abnormal condition in a program resulting to the
disruption in the flow of the program.
Whenever an exception occurs the program halts the execution and thus further
code is not executed. Thus exception is that error which python script is unable to
tackle with.
Exception in a code can also be handled. In case it is not handled, then the code is
not executed further and hence execution stops when exception occurs.
We can halndle exception in our program by using try block and except block. Ac
critical operation which can raise exception is placed inside the try block and the
code that handles exception is written in excpeton block.
try:
statements
except ExceptionName:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 50
statements

Ex:
a=10
b=5
c=5
try:
x=a/(b-c)
print(x)
except ZeroDivisionError:
print("Divison by zero")
Ex:
try:
a=10/0
print (a)
except ArithmeticError:
print ("This statement is raising an exception")
else:
print ("Welcome")

Hierarchy Of Exception:
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when end of file is reached and yet operations are being
performed
etc..

Except with no Exception:


Except statement can also be used without specifying Exception.
Syntax:
try:
code
except:
code to be executed in case exception occurs.
else:
code to be executed in case exception does not occur.
eg:
try:
a=10/0;
except:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 51
Arithmetic Exception

Multiple Except Blocks:


Python allows you to have multiple expect blocks for a single try block. The block
which matches exception generated will get executed. A try block can be associated
with more than one except block to specify handlers for different exceptions.
However, only one halder will be executed. Exception handlers only handle
exceptions that occur in the corresponding try block.
try:
code
except exceptoin1:
code
except exception2:
code
------------
except exceptionn:
code
Ex:
try:
a=10/0
print (a)
except ArithmeticError:
print ("This statement is raising an exception")
except ZeroDivisionError:
print ("Zero Division Exception")
except ValueError:
print ("Value Error")
Mulitple Exceptions in a Single Block:
An Except clause may name multiple exceptions as a parenthesized tuple, as shown
in the program given below. So whatever exception is raised, out of the three
excpetions specified, the same except block will be executed.
Ex:
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:Arithmetic Exception
Except Block without Exception:
You can even specify an exceptblock without mentioning any exception(i.e., except:)
This type of except block if present should be the last one that can serve as a
wildcard(when multiple except blocks are present).

try:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 52
code
except:
code
else:
code
The except block can be used along with other exception handlers which
handle some specific types of the exceptions but those exceptions that are not
handled y these specific handlers can be handled by the except:
Ex:
try:
a=10/0
print (a)
except IOError:
print ("This statement is raising an exception")
except ValueError:
print ("Zero Division Exception")
except :
print ("Final Except")

The else Clause: - The try… except block can optionally have an else caluse, which
when present, must follow all except blocks. The statements in the else block is
executed only if the try clause doest not raise an exception.
try:
code
except:
code
else:
code

Finally Block:
In case if there is any code which the user want to be executed, whether exception
occurs or not then that code can be placed inside the finally block. Finally block will
always be executed irrespective of the exception.
Syntax:
try:
Code
finally:
code which is must to be executed.
Ex:
try:
a=10/0;
print "Exception occurred"
finally:
print "Code to be executed"

Output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 53
>>>
Code to be executed
Traceback (most recent call last):
File "C:/Python27/noexception.py", line 2, in <module>
a=10/0;
ZeroDivisionError: integer division or modulo by zero
>>>

In the above example finally block is executed. Since exception is not handled
therefore exception occurred and execution is stopped.

Raising Exceptions:
You can expclictly throw an exception in Python using raise statement. raise will
cause an exception to occur and thus execution control will stop in case it is not
handled.
Syntax:
raise[Exception[,args[,traceback]]]
Ex:
try:
a=10
print a
raise NameError("Hello")
except NameError as e:
print "An exception occurred"
print e
Output:

10
An exception occurred
Hello

Explanation:
i) To raise an exception, raise statement is used. It is followed by exception class
name.
ii) Exception can be provided with a value that can be given in the parenthesis.
(here, Hello)
iii) To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.

Re-Raising Excepiton:
Python allows programmers to re-raise an exception. For example, an exception
thrown from the try block can be handled as well as re-raised in the except block
using the keyword raise.
Exceptions are two types
i) Built-in Exceptions
ii) User-defined Exceptions

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 54

Built-in Exception:
Python Built-in Exceptions
Exception Cause of Error
AssertionError Raised when assert statement fails.
AttributeError Raised when attribute assignment or reference fails.
EOFError Raised when the input() functions hits end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raise when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when system operation causes system related error.
OverflowError Raised when result of an arithmetic operation is too large to be represented.
Raised when a weak reference proxy is used to access a garbage collected
ReferenceError
referent.
RuntimeError Raised when an error does not fall under any other category.
Raised by next() function to indicate that there is no further item to be
StopIteration
returned by iterator.
SyntaxError Raised by parser when syntax error is encountered.
IndentationError Raised when there is incorrect indentation.
TabError Raised when indentation consists of inconsistent tabs and spaces.
SystemError Raised when interpreter detects internal error.
SystemExit Raised by sys.exit() function.
TypeError Raised when a function or operation is applied to an object of incorrect type.
Raised when a reference is made to a local variable in a function or method,
UnboundLocalError
but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translating.
ValueError Raised when a function gets argument of correct type but improper value.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 55
ZeroDivisionError Raised when second operand of division or modulo operation is zero.

Custom Exception(User defined Exception):


Creating your own Exception class or User Defined Exceptions are known as
Custom Exception.
Ex:
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print ("Received error:", ae.data)

Output:

Received error : 2000

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 1

CHAPTER
6

Brief Tour of the


Standard Library,
Testing

Syllabus:
Brief Tour of the Standard Library - Operating System Interface - String Pattern
Matching, Mathematics, Internet Access, Dates and Times, Data Compression,
Multithreading, GUI Programming, Turtle Graphics Testing: Why testing is required

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 2
?, Basic concepts of testing, Unit testing in Python, Writing Test cases, Running
Tests.

OS Module:
Operating system interface:
 The OS module in Python provides a way of using operating system
dependent functionality.
 The functions that the OS module provides allows you to interface with the
underlying operating system that Python is running on – be that Windows,
Mac or Linux.
 You can find important information about your location or about the process.
OS functions
1. Executing a shell command
os.system()
2. Returns the current working directory.
os.getcwd()
3. Return the real group id of the current process.
os.getgid()
4. Return the current process‟s user id.
os.getuid()
5. Returns the real process ID of the current process.
os.getpid()
6. Set the current numeric umask and return the previous umask.
os.umask(mask)
7. Return information identifying the current operating system.
os.uname()
8. Change the root directory of the current process to path.
os.chroot(path)
9. Return a list of the entries in the directory given by path.
os.listdir(path)
10. Create a directory named path with numeric mode mode.
os.mkdir(path)
11. Remove (delete) the file path.
os.remove(path)
12. Remove directories recursively.
os.removedirs(path)
13. Rename the file or directory src to dst.
os.rename(src, dst)
Examples:
1. getcwd()
import os
print(os.getcwd())
output: D:\pyexamples
2. listdir(), mkdir()
import os
os.mkdir("D:\\pyexamples\\ramesh2")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 3
print(os.listdir("D:\\pyexamples"))
output: ['ramesh', 'ramesh1', 'ramesh2', 'sample.py']
3. remove()
import os
print(os.listdir("D:\\pyexamples"))
os.remove("D:\\pyexamples\\sample1.py")
print(os.listdir("D:\\pyexamples"))
output: ['ramesh', 'ramesh1', 'ramesh2', 'sample.py', 'sample1.py']
['ramesh', 'ramesh1', 'ramesh2', 'sample.py']

String Pattern Matching: [Regular Expression – re module]


The re module provides various methods to perform operation on input string. The
most commonly used methods of re module are as follows:
re.match(pattern,string, flags=0)
Note: Use 'r' at the start of the pattern string - It designates a python "raw" string
The match() method returns zero or more characters which match the pattern at
the beginning of string. The match() function returns none if the string does not
matches the pattern.
Example:
import re
t=re.match("Python","Python programming language")
print(t)
output: <re.Match object; span=(0, 6), match='Python'>
Example:
import re
t=re.match("Python","Python programming language")
print(t)
output: None
The method group() on match returns the matching string.
group(num=0) : This method returns entire match (or specific subgroup num)
groups() : This method returns all matching subgroups in a tuple (empty if there
weren't any)
r.group() - It returns the string matched
r.start() - It returns the index of the match start
r.end() - It returns the index of match end
r.span() - It returns the Tupe of (start,end)
Example :
import re
t=re.match("Python","Python programming language")
print(t)
print(t.group(0))
output: <re.Match object; span=(0, 6), match='Python'>
Python
The search() method same as that of match() method of regular expression. The
main advantage of search() method is that it does not restrict us to find matches at
the beginning of the string only.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 4
re.search(pattern,string, flags=0)
The search() method is able to find a pattern from any position of the string.
But it returns only first occurrence of matched string.
Example:
import re
t=re.search(r"Good","If Good Programmer then you can be Good Developer")
print(t)
print(t.group(0))
output: <re.Match object; span=(3, 7), match='Good'>
Good
The findall() method The string is scanned from left to right and the pattern is to be
searched if matched ones are returned in the order they are found. Finally, it
returns the list of all matching patterns from the string.
Example :
import re
t=re.findall("Good","If Good Programmer then you can be Good Developer")
print(t)
output:
['Good', 'Good']
The split() method split the string by the occurrens of pattern
Example:
import re
t=re.split("y","Python")
print(t)
output:
['P', 'thon']
Example:
import re
t=re.split("-","978-92-95055-02-5")
print(t)
output:
['978', '92', '95055', '02', '5']
Example:
import re
t=re.split("-","978-92-95055-02-5",maxsplit=3)
print(t)
output:
['978', '92', '95055', '02-5']
The sub() method helps us to search a pattern and replace with new sub-strings. If
the pattern to be searched is not found, then the original string will remain
unchanged.
re.sub(pattern,repl,string)
Example:
import re
t=re.sub("Python","India","I Love Python")
print(t)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 5
output:
I Love India

Regular Expression containing Operators and Symbols:


Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters
match themselves. You can escape a control character by preceding it with a
backslash.
Following table lists the regular expression syntax that is available in Python −
Pattern Description
^ Matches beginning of line.
$ Matches end of line.
Matches any single character except newline. Using m
.
option allows it to match newline as well.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
re* Matches 0 or more occurrences of preceding expression.
re+ Matches 1 or more occurrence of preceding expression.
re? Matches 0 or 1 occurrence of preceding expression.
re{ n} Matches exactly n number of occurrences of preceding
re{ n,} expression.
Matches n or more occurrences of preceding expression.
re{ n, m} Matches at least n and at most m occurrences of preceding
a| b expression.
Matches either a or b.
(?#...) Comment.
(?= re) Specifies position using a pattern. Doesn't have a range.
(?! re) Specifies position using pattern negation. Doesn't have a
(?> re) range.
Matches independent pattern without backtracking.
\w Matches word characters.
\W Matches nonword characters.
\s Matches whitespace. Equivalent to [\t\n\r\f].
\S Matches nonwhitespace.
\d Matches digits. Equivalent to [0-9].
\D Matches nondigits.
\A Matches beginning of string.
\Z Matches end of string. If a newline exists, it matches just
\z before
Matchesnewline.
end of string.
\G Matches point where last match finished.
\B Matches nonword boundaries.
\n, \t, etc. Matches newlines, carriage returns, tabs, etc.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 6
\1...\9 Matches nth grouped subexpression.
Matches nth grouped subexpression if it matched already.
\10
Otherwise refers to the octal representation of a character
code.
[^x] matches any one character that is not included in x
"[^abc]" matches any single character except 'a','b' or 'c'
Parentheses can be used for grouping
"(abc)+" matches 'abc','abcabc','abcabcabc', etc
x|y matches x or y
"here|there" matches 'here' and 'there', but not 'herethere'

x* matches zero or more x's


"d*" matches '','d','dd','ddd' etc

x+ matches one or more x's


"d+" matches 'd','dd','ddd' etc

x? matches zero or one x's


"d?" matches ' ' or 'd'

x{m,n} matches i x's, where m<=i<=n


"d{2,3}" matches 'dd' or 'ddd'

Example 1: Extract each character from the given string


import re
t=re.findall(".","If Good Programmer then you can be Good Developer")
print(t)
output:
['I', 'f', ' ', 'G', 'o', 'o', 'd', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r', ' ', 't', 'h', 'e', 'n', ' ', 'y',
'o', 'u', ' ', 'c', 'a', 'n', ' ', 'b', 'e', ' ', 'G', 'o', 'o', 'd', ' ', 'D', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r']

Note: In above problem, space is also extracted as a character. To avaid it \w is


used instead of “.”
import re
t=re.findall("\w","If Good Programmer then you can be Good Developer")
print(t)
output:
['I', 'f', 'G', 'o', 'o', 'd', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r', 't', 'h', 'e', 'n', 'y', 'o', 'u', 'c',
'a', 'n', 'b', 'e', 'G', 'o', 'o', 'd', 'D', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r']

Example 2: Extract words from given string.


import re
t=re.findall("\w*","If Good Programmer then you can be Good Developer")
print(t)
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 7
['If', '', 'Good', '', 'Programmer', '', 'then', '', 'you', '', 'can', '', 'be', '', 'Good', '',
'Developer', '']

Note: In the above problem, it returns the space as word because ‘*’ returns zero or
more different matches. In order to remove space, we will go with ‘+’
import re
t=re.findall("\w+","If Good Programmer then you can be Good Developer")
print(t)
output:
['If', 'Good', 'Programmer', 'then', 'you', 'can', 'be', 'Good', 'Developer']
Example 3: Extract only first word from the sentence.
import re
t=re.findall("^\w+","If Good Programmer then you can be Good Developer")
print(t)
output:
['If']

Example 4: Extract last word from the sentence


import re
t=re.findall("\w+$","If Good Programmer then you can be Good Developer")
print(t)
output:
['Developer']

Example 5: Extract date from the string


import re
t=re.findall("\d{2}-\d{2}-\d{4}","Bhuvana Kruthi 17-12-2009")
print(t)
output:
['17-12-2009']

Example: Extract the gmail email id from the given string


import re
gmails=re.findall(r'[\w\.-]+@gmail[\w\.-]+',"yrameshkumar123@gmail.com
rameshkumar123y@gmail.com hodcse@aietta.ac.in
ramesh.cse@avanthi.edu.in")
for email in gmails:
print (email)
output:
yrameshkumar123@gmail.com
rameshkumar123y@gmail.com
Date and Time Module: Python datetime module supplies classes for manipulating
date and time in both simple and complex ways.
Date - Stores clanedar date(year,month,day) using Gregorian calendar
Time - Stores time of days as hours,minutes,seconds and microseconds
Datetime - Stores both date and time

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 8
Timedelta- Represents the difference between two date time values.
Tzinfo - This is a basic type for stroing time-zone information.
Example:
import datetime
t=datetime.date.today()
print(t)
print("Today date ",t.day)
print("Today month ",t.month)
print("Today Year ",t.year)
output:
2019-10-13
Today date 13
Today month 10
Today Year 2019
Example:
import datetime
t=datetime.datetime.now()
print(t)
output:
2019-10-13 23:56:53.168541
Date Formats: The default date format is “YYYY-MM-DD”. Python makes the use of
strftime() to format dates.
%d Represents the day of month
%B Represents full month’s name
%b Represents the month
%Y Represents the year
%y Represents two digit years
%a Represents abbreviated day of the week
%A Represents full name of the day
Example
import datetime
t=datetime.date.today()
print(t.strftime("Date Formatting : %d %B %Y"))
output:
Date Formatting : 14 October 2019

The time Module: There is a popular time module available in Python which
provides functions for working with times and for converting between
representations. Here is the list of all available methods:
Sr.
No. Function with Description
time.ctime([secs])
1 Like asctime(localtime(secs)) and without arguments is like asctime(
)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 9
time.localtime([secs])
2 Accepts an instant expressed in seconds since the epoch and
returns a time-tuple t with the local time (t.tm_isdst is 0 or 1,
depending on whether DST applies to instant secs by local rules).
time.sleep(secs)
3 Suspends the calling thread for secs seconds.
time.time( )
4 Returns the current time instant, a floating-point number of
seconds since
time.clock( ) the epoch.
5 The method returns the current processor time as a floating
point numberexpressed in seconds on Unix.
time.asctime([tupletime])
6 Accepts a time-tuple and returns a readable 24-character string
such as 'Tue Dec 11 18:07:14 2008'.
Example:
import time
print ("time: ",time.time())
print ("ctime: ",time.ctime())
time.sleep(5)
print ("ctime: ",time.ctime())
print ("localtime: ",time.localtime())
print ("asctime: ",time.asctime( time.localtime(time.time()) ))
print ("clock: ",time.clock())
output:
time: 1570991872.2517312
ctime: Mon Oct 14 00:07:52 2019
ctime: Mon Oct 14 00:07:57 2019
localtime: time.struct_time(tm_year=2019, tm_mon=10, tm_mday=14, tm_hour=0,
tm_min=7, tm_sec=57, tm_wday=0, tm_yday=287, tm_isdst=0)
asctime: Mon Oct 14 00:07:57 2019
clock: 5.496352
The calendar Module:
 The calendar module supplies calendar-related functions, including
functions to print a text calendar for a given month or year.
 By default, calendar takes Monday as the first day of the week and Sunday as
the last one. To change this, call calendar.setfirstweekday() function.
Sr. Function with Description
No. calendar.calendar(year,w=2,l=1,c=6)
1 Returns a multiline string with a calendar for year formatted
into three columns separated by c spaces. w is the width in
characters of each date; each line has length 21*w+18+2*c. l is
the number of lines for each week.
calendar.isleap(year)
2 Returns True if year is a leap year; otherwise, False.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 10
calendar.setfirstweekday(weekday)
3 Sets the first day of each week to weekday code weekday.
Weekday codes are 0 (Monday) to 6 (Sunday).

calendar.leapdays(y1,y2)
4 Returns the total number of leap days in the years within
range(y1,y2).
calendar.month(year,month,w=2,l=1)
5 Returns a multiline string with a calendar for month of year, one
line per week plus two header lines. w is the width in characters
of each date; each line has length 7*w+6. l is the number of
lines for each week.
Example:
import calendar
print ("Here it is the calendar:")
print (calendar.month(2019,10))
calendar.setfirstweekday(6)
print (calendar.month(2019,10))
print ("Is 2019 is leap year?",calendar.isleap(2019))
print ("No.of Leap days",calendar.leapdays(2000,2019))
print ("1990-November-12 is",calendar.weekday(1990,11,12))
Output:
Here it is the calendar:
October 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

October 2019
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

Is 2019 is leap year? False


No.of Leap days 5
1990-November-12 is 0
The Math Module: The math module is a standard module in Python and is
always available. To use mathematical functions under this module, you have
to import the module using import math.
Function Description

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 11
ceil(x) Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x) Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x) Returns the mantissa and exponent of x as the pair (m, e)
fsum(iterable) Returns an accurate floating point sum of values in the
iterable
isfinite(x) Returns True if x is neither an infinity nor a NaN (Not a
Number)
ldexp(x, i) Returns x * (2**i)
modf(x) Returns the fractional and integer parts of x
trunc(x) Returns the truncated integer value of x
exp(x) Returns e**x
expm1(x) Returns e**x - 1
log(x[, base]) Returns the logarithm of x to the base (defaults to e)
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
atan2(y, x) Returns atan(y / x)
cos(x) Returns the cosine of x
hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
sin(x) Returns the sine of x
tan(x) Returns the tangent of x
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
acosh(x) Returns the inverse hyperbolic cosine of x
asinh(x) Returns the inverse hyperbolic sine of x
atanh(x) Returns the inverse hyperbolic tangent of x
cosh(x) Returns the hyperbolic cosine of x
sinh(x) Returns the hyperbolic cosine of x
tanh(x) Returns the hyperbolic tangent of x
erf(x) Returns the error function at x

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 12
erfc(x) Returns the complementary error function at x
gamma(x) Returns the Gamma function at x
Returns the natural logarithm of the absolute value of
lgamma(x)
the Gamma function at x
Mathematical constant, the ratio of circumference of a
pi
circle to it's diameter (3.14159...)
e mathematical constant e (2.71828...)

Internet Access:
 Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending
e-mail and routing e-mail between mail servers.
 Python provides smtplib module, which defines an SMTP client session
object that can be used to send mail to any Internet machine with an SMTP
or ESMTP listener daemon.
 Here is a simple syntax to create one SMTP object, which can later be used
to send an e- mail:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
 Here is the detail of the parameters:
 host: This is the host running your SMTP server. You can specify IP
address of the host or a domain name like tutorialspoint.com. This is
optional argument.
 port: If you are providing host argument, then you need to specify a
port, where SMTP server is listening. Usually this port would be 25.
 local_hostname: If your SMTP server is running on your local machine,
then you can specify just localhost as of this option.
An SMTP object has an instance method called sendmail, which is typically
used to do the work of mailing a message. It takes three parameters:
 The sender - A string with the address of the sender.
 The receivers - A list of strings, one for each recipient.
 The message - A message as a string formatted as specified in the various
RFCs.
import smtplib
from email.mime.text import MIMEText
body="The message you want to send........"
msg=MIMEText(body)
fromaddr="rameshkumar123y@gmail.com"
toaddr="yrameshkumar123@gmail.com"
msg['From']=fromaddr

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 13
msg['To']=toaddr
msg['Subject']="Subject of mail"
server=smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(fromaddr,"fromAddressPassword")
server.sendmail(fromaddr,toaddr,msg.as_string())
print ("Mail Sent.......")
server.quit()
Output:
Mail Sent..........
Note: To send a mail to others you have to change “Allow less secure apps: ON”
in from address mail. Because Google has providing security for vulnerable attacks

Data compression [zlib Module]:


Common data archiving and compression formats are directly supported by
the modules including: zlib, gzip, bz2, lzma, zipfile and tarfile.
Example: write a program to zip the three files into one single “.zip” file
import zipfile
FileNames=['README.txt','NEWS.txt','LICENSE.txt']
with zipfile.ZipFile('reportDir1.zip', 'w') as myzip:
for f in FileNames:
myzip.write(f)
The Zlib Library: Python “zlib” library allows compression and decompression for
applications that requires data compression. The most frequently used in built
functions supported by zlib library are as follows.
Compress(String,[level]) Compressdata in a string, returns string containing
compressed data. The level indicates the level of compressions from 0 to 9. Level 1
is fastest and produces the least compression, while level 9 is the slowest and
produces the most.
Decompress(data) Decompress bytes in data. It returns bytes object cotnaing the
uncompressed data.

The Threading Module:


The threading module exposes all the methods of the thread module and
provides some additional methods:
 threading.activeCount(): Returns the number of thread objects that are
active.
 threading.currentThread(): Returns the number of thread objects in the
caller's thread control.
 threading.enumerate(): Returns a list of all thread objects that are currently
active.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 14
In addition to the methods, the threading module has the Thread class that
implements threading. The methods provided by the Thread class are as follows:
 run(): The run() method is the entry point for a thread.
 start(): The start() method starts a thread by calling the run method.
 join([time]): The join() waits for threads to terminate.
 isAlive(): The isAlive() method checks whether a thread is still executing.
 getName(): The getName() method returns the name of a thread.
 setName(): The setName() method sets the name of a thread.

Creating Thread Using Threading Module:


To implement a new thread using the threading module, you have to do the
following:
 Define a new subclass of the Thread class.
 Override the init_(self [,args]) method to add additional arguments.
 Then, override the run(self [,args]) method to implement what the thread
should do when started.
Once you have created the new Thread subclass, you can create an instance of
it and then start a new thread by invoking the start(), which in turn calls run()
method.

Example:
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def init (self, threadID, name, counter):
threading.Thread.init(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting ") + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print (threadName, time.ctime(time.time()))
counter -= 1

# Create new threads


thread1 = myThread(1, "Thread-1", 1)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 15
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print ("Exiting Main Thread")
output:
Starting Thread-1Starting Thread-2Exiting Main Thread
Thread-1 Sun Oct 01 22:26:17 2017
Thread-1 Sun Oct 01 22:26:18 2017
Thread-2 Sun Oct 01 22:26:18 2017
Thread-1 Sun Oct 01 22:26:19 2017
Thread-1Thread-2 Sun Oct 01 22:26:20 2017Sun Oct 01 22:26:20 2017
Thread-1 Sun Oct 01 22:26:21 2017 Exiting
Thread-1
Thread-2 Sun Oct 01 22:26:22 2017
Thread-2 Sun Oct 01 22:26:24 2017
Thread-2 Sun Oct 01 22:26:26 2017 Exiting
Thread-2
Synchronizing Threads
 The threading module provided with Python includes a simple-to-
implement locking mechanism that allows you to synchronize threads. A
new lock is created by calling the Lock() method, which returns the new lock.
 The acquire(blocking) method of the new lock object is used to force
threads to run synchronously. The optional blocking parameter enables you
to control whether the thread waits to acquire the lock.
 If blocking is set to 0, the thread returns immediately with a 0 value if the
lock cannot be acquired and with a 1 if the lock was acquired. If blocking is
set to 1, the thread blocks and waits for the lock to be released.
 The release() method of the new lock object is used to release the lock
when it is no longer required.

GUI Programming
Python provides various options for developing graphical user interfaces
(GUIs). Most important are listed below:
 Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python..
 wxPython: This is an open-source Python interface for wxWindows
http://wxpython.org.
 JPython: JPython is a Python port for Java which gives Python scripts
seamless access to Java class libraries on the local machine
http://www.jython.org.
There are many other interfaces available, which you can find them on the net.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 16
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined
with Tkinter provides a fast and easy way to create GUI applications. Tkinter
provides a powerful object- oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need
to do is perform the following steps:
 Import the Tkinter module.
 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the
user.
 Write a program to display the tkinter window
from tkinter import Tk
root = Tk()
root.mainloop()


 Write a program to display the Tkinter window with title
from tkinter import Tk
root = Tk()
root.title("CSE Students window")
root.mainloop()

 Window Full Screen


from tkinter import Tk
root = Tk()
root.title("CSE Students window")
root.attributes('-fullscreen',True)
root.mainloop()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 17
Tkinter Widgets
 Tkinter provides various controls, such as buttons, labels and text boxes
used in a GUI application. These controls are commonly called widgets.
 There are currently 15 types of widgets in Tkinter. We present these widgets
as well as a brief description in the following table:
Operator Description
Button The Button widget is used to display buttons in your
application.
The Canvas widget is used to draw shapes, such
Canvas
as lines, ovals, polygons and rectangles, in your
The Checkbutton widget is used to display a
Checkbutton
number of options as checkboxes. The user can
The Entry widget is used to display a single-line text field
Entry
for accepting values from a user.
The Frame widget is used as a container widget to
Frame
organize other widgets.
The Label widget is used to provide a single-line
Label
caption for other widgets. It can also contain
Listbox The Listbox widget is used to provide a list of options to a
Menubutton user.Menubutton widget is used to display menus in your
The
application.
The Menu widget is used to provide various commands to
Menu
a user. These commands are contained inside
The Message widget is used to display multiline
Message
text fields for accepting values from a user.
The Radiobutton widget is used to display a number of
Radiobutton options as radio buttons. The user can select only one
option at a time. Scale The Scale widget is used to
The Scrollbar widget is used to add scrolling
Scrollbar
capability to various widgets, such as list boxes.
Text The Text widget is used to display text in multiple lines.
Toplevel The Toplevel widget is used to provide a separate window
container.
The Spinbox widget is a variant of the standard Tkinter
Spinbox
Entry widget, which can be used to select from a fixed
A PanedWindow is a container widget that may contain
PanedWindow
any number of panes, arranged horizontally or
A labelframe is a simple container widget. Its primary
LabelFrame
purpose is to act as a spacer or container for complex
tkMessageBox This module is used to display message boxes in your
1. Label: applications.
import tkinter
MainWindow = tkinter.Tk()

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 18
l1=tkinter.Label(MainWindow,text="hello CSE students")
l1.pack()

The pack method is then called to organize the geometry of the control (label)

2. Customize Label
import tkinter
MainWindow = tkinter.Tk()
s1="Hello, CSE students very good, but \n results very ?"
l1=tkinter.Label(MainWindow,text=s1,fg="red",bg="yellow",font="Arial 10 bold")
l1.pack()

3. Button
import tkinter
MainWindow = tkinter.Tk()
b1=tkinter.Button(MainWindow,text="Close",width=20,command=MainWindo
w.destroy)
b1.pack()

4. ListBox
import tkinter
MainWindow = tkinter.Tk()
l1=tkinter.Listbox(MainWindow,width=20)
countries=['Italy','Brazil','Germany','France','Argentina','Spain']
l1.pack()
for i in countries:
l1.insert(l1.size(),i)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 19

ListBox with multiple Items selection


import tkinter
MainWindow = tkinter.Tk()
l1=tkinter.Listbox(MainWindow,width=20,selectmode='multiple')
countries=['Italy','Brazil','Germany','France','Argentina','Spain']
l1.pack()
for i in countries:
l1.insert(l1.size(),i)

5. Spin Box
import tkinter
MainWindow = tkinter.Tk()
l1=tkinter.Label(MainWindow,text="Choose Month:",font='Arial 10 bold')
l1.pack()
sb1=tkinter.Spinbox(MainWindow,from_=1,to_=12,width=15)
sb1.pack()

6. Combo Box
The combobox is a dropdown list that provides a graphical way for the user to select
one value of the list. To use the Combobox control, we need to import the tkinter.ttk
module.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 20
import tkinter
from tkinter import ttk
MainWindow = tkinter.Tk()
weekdays={'Sat','Sun','Mon','Tue','Wed','Thu','Fri'}
cb1=ttk.Combobox(MainWindow.values=weekdays)
cb1.pack()
7. Radio Button
import tkinter
from tkinter import ttk
root = tkinter.Tk()
l1=tkinter.Label(root,text="Gender:",font="Arial 10 bold")
rb1=ttk.Radiobutton(root,text="Male",value=1)
rb2=ttk.Radiobutton(root,text="Female",value=2)
l1.pack()
rb1.pack()
rb2.pack()

8. Entry
import tkinter
root = tkinter.Tk()
l1=tkinter.Label(root,text="Enter Your Name",font="Arial 10 bold")
l1.pack(side="left")
e1=tkinter.Entry(root)
e1.pack(side="right")

Example:
import tkinter
from tkinter import *
def DisplayMsg(self):
root.tkMessageBox.showinfo("Your Name","Welcome "+e1.get()+" "+e2.get())

root=Tk()
Label(root,text="Frist Name").grid(row=0)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 21
Label(root,text="Last Name").grid(row=1)

e1=Entry(root)
e2=Entry(root)

e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e1.focus()

Button(root,text="Disp",command=DisplayMsg).grid(row=3,column=0)
Button(root,text="Close",command=root.destroy).grid(row=3,column=1)
mainloop()
output:

Example:
import tkinter
import tkMessageBox
top = tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
output:

Example: Write a GUI for an Expression Calculator using tk


from tkinter import *
from math import *
root=Tk()
root.title("Calculator")

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 22
root.geometry("210x200")
e=Entry(root,bd=8,width=30)
e.grid(row=0,column=1,columnspan=5)
def setText(txt):
l=len(e.get())
e.insert(l,txt)
def clear1():
txt=e.get()
e.delete(0,END)
e.insert(0,txt[:-1])
def clear():
e.delete(0,END)
def sqroot():
txt=sqrt(float(e.get()))
e.delete(0,END)
e.insert(0,txt)
def negation():
txt=e.get()
if txt[0]=="-":
e.delete(0,END)
e.insert(0,txt[1:])
elif txt[0]=="+":
e.delete(0,END)
e.insert(0,"-"+txt[1:])
else:
e.insert(0,"-")

def equals():
try:
s=e.get()
for i in range(0,len(s)):
if s[i]=="+" or s[i]=="-" or s[i]=="*" or s[i]=="/" or s[i]=="%":
expr=str(float(s[:i]))+s[i:]
break
elif s[i]==".":
expr=s
break
e.delete(0,END)
e.insert(0,eval(expr))
except Exception:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 23
e.delete(0,END)
e.insert(0,"INVALID EXPRESSION")

back1=Button(root,text="<--",command=lambda:clear1(),width=10)
back1.grid(row=1,column=1,columnspan=2)

sqr=Button(root,text=u'\u221A',command=lambda:sqroot(),width=4)
sqr.grid(row=1,column=5)

can=Button(root,text="C",command=lambda:clear(),width=4)
can.grid(row=1,column=3)

neg=Button(root,text="+/-",command=lambda:negation(),width=4)
neg.grid(row=1,column=4)

nine=Button(root,text="9",command=lambda:setText("9"),width=4)
nine.grid(row=2,column=1)

eight=Button(root,text="8",command=lambda:setText("8"),width=4)
eight.grid(row=2,column=2)

seven=Button(root,text="7",command=lambda:setText("7"),width=4)
seven.grid(row=2,column=3)

six=Button(root,text="6",command=lambda:setText("6"),width=4)
six.grid(row=3,column=1)

five=Button(root,text="5",command=lambda:setText("5"),width=4)
five.grid(row=3,column=2)

four=Button(root,text="4",command=lambda:setText("4"),width=4)
four.grid(row=3,column=3)

three=Button(root,text="3",command=lambda:setText("3"),width=4)
three.grid(row=4,column=1)

two=Button(root,text="2",command=lambda:setText("2"),width=4)
two.grid(row=4,column=2)

one=Button(root,text="1",command=lambda:setText("1"),width=4)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 24
one.grid(row=4,column=3)

zero=Button(root,text="0",command=lambda:setText("0"),width=10)
zero.grid(row=5,column=1,columnspan=2)

dot=Button(root,text=".",command=lambda:setText("."),width=4)
dot.grid(row=5,column=3)

div=Button(root,text="/",command=lambda:setText("/"),width=4)
div.grid(row=2,column=4)

mul=Button(root,text="*",command=lambda:setText("*"),width=4)
mul.grid(row=3,column=4)

minus=Button(root,text="-",command=lambda:setText("-"),width=4)
minus.grid(row=4,column=4)

plus=Button(root,text="+",command=lambda:setText("+"),width=4)
plus.grid(row=5,column=4)

mod=Button(root,text="%",command=lambda:setText("%"),width=4)
mod.grid(row=2,column=5)

byx=Button(root,text="1/x",command=lambda:setText("%"),width=4)
byx.grid(row=3,column=5)

equal=Button(root,text="=",command=lambda:equals(),width=4,height=3)
equal.grid(row=4,column=5,rowspan=2)

root.mainloop()
output:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 25

Turtle Graphics
 Graphics is the discipline that underlies the representation and display of
geometric shapes in two and three-dimensional space.
 A Turtle graphics library provides an enjoyable and easy way to draw
shapes in a window and gives you an opportunity to run several functions
with an object.
 Turtle graphics were originally developed as part of the children‟s
programming language called
Logo, created by Seymour Papert and his colleagues at MIT in the late 1960s.

 Imagine a turtle crawling on a piece of paper with a pen tied to its tail.
 Commands direct the turtle as it moves across the paper and tells it to lift
or lower its tail, turn some number of degrees left or right and move a
specified distance.
 Whenever the tail is down, the pen drags along the paper, leaving a trail.
 In the context of computer, of course, the sheet of paper is a window on a
display screen and the turtle is an invisible pen point.
 At any given moment of time, the turtle coordinates. The position is
specified with (x, y) coordinates.
 The coordinate system for turtle graphics is the standard Cartesian system,
with the origin (0, 0) at the centre of a window. The turtle‟s initial position is
the origin, which is also called the home.
Turtle Operations:
Turtle is an object; its operations are also defined as methods. In the below
table the list of methods of Turtle class.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 26

Turtle Methods WHAT IT DOES


home Moves the turtle to the origin – coordinates (0, 0) –
and set its heading to its start-orientation.

fd | forward Moves the turtle forward for a specified distance, in


the direction where the turtle is headed.

bk | backward Moves the turtle backward for a specified distance,


in the direction where the turtle is headed. Do not
change the turtle‟s heading.

right | rt Turns the turtle right by angle units. Units are by


default degrees, but can be set via the degrees ( ) and
radians ( ) functions.
left | lt Turns the turtle left by angle units. Units are by
default degrees, but can be set via the degrees ( ) and
radians ( ) functions.
setx Set the turtle‟s first coordinate to x, leaves the second
coordinate unchanged.

sety Set the turtle‟s second coordinate to y, leaves the first


coordinate
unchanged.
goto Moves the turtle to an absolute position. If the pen
is down,
draws a line. Do not change the turtle‟s orientation.
degrees Set the angle measurement unit to radians.
Equivalent to degrees (2 * math.pi )

radians Set the angle measurement unit, i.e., set the number
of degrees for a full circle. The default value is 3600.
seth Sets the orientation of the turtle to to_angle.
Turtle Object:
t=Turtle( ) creates a new turtle object and open sits window. The window‟s
drawing area is 200 pixels wide and 200 pixels high.
t=Turtle( width, height ) creates a new turtle object and open sits window. The
window‟s drawing area has given width and height.
Instructions Meaning
turtle.forward(number) Move forward
turtle.back(number) Move backward

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 27
turtle.right(angle) Turn clockwise
turtle.left(angle) Turn anti-clockwise
turtle.pencolor(colour string) Drawing colour
turtle.pensize(number) Choosing size of pen nib
turtle.circle(radius) Drawing a circle
turtle.speed(number) Choosing speed - 1 to 10
turtle.write(message,font) Writing on the screen
turtle.ht() Hiding the turtle
turtle.setpos(x,y) Changing the position of turtle
Example: Write a Program to move the turtle forward and then backward after a delay of 2 seconds
import turtle
import time
turtle.forward(50)
time.sleep(2)
turtle.backward(20)

Example: Write a program to draw a square


import turtle
import time
turtle.forward(100)
turtle.left(90)
time.sleep(1)
turtle.forward(100)
turtle.left(90)
time.sleep(1)
turtle.forward(100)
turtle.left(90)
time.sleep(1)
turtle.forward(100)
turtle.left(90)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 28

Example: Write a Program to draw red color triangle


import turtle
import time
turtle.color("red")
turtle.forward(70)
turtle.left(120)

turtle.forward(70)
turtle.left(120)

turtle.forward(70)
output:

Example: Write a program to draw a red color thick pen on a yellow background
import turtle
c=["red","green","blue"]
i=0
turtle.pensize(5)
for angle in range(0,360,30):
if i>2:
i=0
turtle.color(c[i])
turtle.seth(angle)
turtle.circle(50)
i=i+1

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 29

Example:
import turtle
for i in range(36):
for j in range(4):
turtle.forward(70)
turtle.left(90)
turtle.left(10)

Testing: Why testing is required?


Software testing is necessary because we all make mistakes. Some of those
mistakes are unimportant, but some of them are expensive or dangerous. We
need to check everything and anything we produce because things can always go
wrong-humans make mistakes all the time.
Software testing is very important because of the following reasons:
1. Software testing is really required to point out the defects and errors that
were made during the development phases.
2. It‟s essential since it makes sure of the customer‟s reliability and their
satisfaction in the application.
3. It is very important to ensure the quality of the product. Quality product
delivered to the customers helps in gaining their confidence.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 30
4. Testing is necessary in order to provide the facilities to the customers like
the delivery of high quality product or software application which requires
lower maintenance cost and hence results into more accurate, consistent
and reliable results.
5. Testing is required for an effective performance of software application or
product.
6. It‟s important to ensure that the application should not result into any
failures because it
can be very expensive in the future or in the later stages of the development.
7. It‟s required to stay in the business.

Basic concepts of testing:


Basics Summary

Learn how software quality is defined and what it means. Software


Softwar
quality is the degree of conformance to explicit or implicit
e
requirements and expectations.
Quality
Dimensions Learn the dimensions of quality. Software quality has dimensions
of Quality such as Accessibility, Compatibility, Concurrency, Efficiency …

Software Learn what it means and what its relationship is with Software
Quality Quality Control. Software Quality Assurance is a set of activities
Assuranc for ensuring quality in software engineering processes.
e
Learn what it means and what its relationship is with Software
Software
Quality Assurance. Software Quality Control is a set of activities
Quality
for ensuring quality in software products.
Control
Learn the differences between Software Quality Assurance and
SQA and
Software Quality Control. SQA is process-focused and prevention-
SQC
oriented but SQC is product-focused and detection-oriented.
Differences
Software Learn what SDLC means and what activities a typical SDLC model
Developmen comprises of. Software Development Life Cycle defines the
t Life Cycle steps/stages/phases in the building of software.

Software Learn what STLC means and what activities a typical STLC model
Testing comprises of. Software Testing Life Cycle (STLC) defines the
Life Cycle steps/ stages/ phases in testing of software.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 31
Definition Learn the various definitions of the term „test‟. Merriam Webster
of Test defines Test as “a critical examination, observation, or evaluation”.

Just as every field has its myths, so does the field of Software
Software
Testing. We explain some of the myths along with their related
Testing
facts.
Myths
Unit testing in Python:
The first unit testing framework, JUnit was invented by Kent Back and Erich
Gamma in 1997, for testing Java programs. It was so successful that the
framework has been implemented again in every major programming language.
Here we discuss the python version, unit test.
Unit testing is nothing but testing individual „units‟, or functions of a
program. It does not have a lot to say about system integration, whether the
various parts of a program fit together. That‟s a separate issue.
The goals of unit testing framework are:
 To make it easy to write tests. All a „test‟ needs to do is to say that, for this
input, the
function should give that result. The framework takes care of running the
tests.
 To make it easy to run tests. Usually this is done by clicking a single
button or typing a single keystroke (F5 in IDLE). Ideally, you should be
comfortable running tests after every change in the program, however
minor.
 To make it easy to tell if the tests passed. The framework takes care of
reporting results; it either simply indicates that all tests passed, or it
provides a detailed list of failures.
Writing and Running Test cases
 Your object is to write test and not to prove that your program works, it‟s
to try to find out where it doesn‟t! Test every „extreme‟ case you can think
of.
 For example, if you were to write and test a function to sort a list, then the
first and last elements get moved to correct position? Can you sort a 1-
element list without getting an error? How about an empty list?
 While you can put as many tests as you like into one test method that you
shouldn‟t test methods should be short and single-purpose. If you are
testing different aspects of a function, they should be in separate tests.
 Here are the rules for writing test methods:
o The name of a test method must start with the letters „test‟, otherwise
it will be
ignored.
o This is so that you can write „helper‟ methods you can call from your
tests, but
are not directly called by the test framework.
o Every test method must have exactly one parameter, which is

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 32
nothing but self‟. You must put self in front of every built-in
assertionmethod you call.
o The tests must be independent of one another, because they may be
run in any order.
o Do not assume they will execute in the order they occur in the
program.
 Here are some of the built-in test methods you can call. Each has an
optional message parameter, to be printed if the test fails.

Method Checks that


assertEqual(a, b) a == b

assertNotEqual(a, b) a != b

assertTrue(x) bool(x) is True

assertFalse(x) bool(x) is False

assertIs(a, b) a is b

assertIsNot(a, b) a is not b

assertIsNone(x) x is None

assertIsNotNone(x) x is not None

assertIn(a, b) a in b

assertNotIn(a, b) a not in b

assertIsInstance(a, b) isinstance(a, b)

assertNotIsInstance(a, b) not isinstance(a, b)


Example:
import unittest
def add(a,b):
if isinstance(a,int) and isinstance(b,int):
return a+b
elif isinstance(a,str) and isinstance(b,str):
return int(a)+int(b)
else:
raise Exception('Invalid arguments')

class TestAdd(unittest.TestCase):

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Python Programming 33
def test_add(self):
self.assertEqual(5,add(2,3))
self.assertEqual(15,add(-6,21))
self.assertRaises(Exception,add,4.0,5.0)

unittest.main()
output:
.
----------------------------------------------------------------------
Ran 1 test in 0.017s

OK

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology

You might also like