0% found this document useful (0 votes)
456 views120 pages

Python Programming

Uploaded by

Charath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
456 views120 pages

Python Programming

Uploaded by

Charath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 120

PYTHON

UNIT-I
Introduction:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum during 1985 – 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL).Python is named after a TV Show called ‘Monty Python’s Flying Circus’ and not
after Python-the snake.
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been back ported to
beCompatible with the version 2.7.

 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.
 Python is a Beginner's Language: Python is a great language for the
beginner-level
programmers and supports the development of a wide range of applications
from simple text processing to WWW browsers to games.
History of Python:
Python was developed by Guido van Rossum in the late eighties and early nineties
at the National Research Institute for Mathematics and Computer Science in the
Netherlands.

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

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

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


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

Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.

Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.

Department of CSE Page 1


PYTHON

Python Features:

Python's features include-


Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a student to pick up the language quickly.

Easy-to-read: Python code is more clearly defined and visible to the eyes.

Easy-to-maintain: Python's source code is fairly easy-to-maintain.

A broad standard library: Python's bulk of the library is very portable and
crossplatform compatible on UNIX, Windows, and Macintosh.

Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.

Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

Databases: Python provides interfaces to all major commercial databases.

GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC,Macintosh, and the X Window system of Unix.

Scalable: Python provides a better structure and support for large programs than
shell scripting.

Apart from the above-mentioned features, Python has a big list of good features.

A few are listed below-


It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Need of Python Programming/Who uses Python?

 On-line games
 Web services
 Applications

Department of CSE Page 2


PYTHON

 Science
 Instrument control
 Embedded systems

Python is used for everything! For example:


“massively multiplayer online role-playing games” like Eve Online, science fiction’s
answer to World of Warcraft, web applications written in a framework built on Python
called “Django”, desktop applications like Blender, the 3-d animation suite which
makes considerable use of Python scripts, the Scientific Python libraries (“SciPy”),
instrument control and embedded systems

Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on
www.python.org/downloads/windows

The following different installation options are available.


 Windows x86-64 embeddable zip file
 Windows x86-64 executable installer
 Windows x86-64 web-based installer
 Windows x86 embeddable zip file
 Windows x86 executable installer
 Windows x86 web-based installer
Note:
In order to install Python 3.5.1, minimum OS requirements are Windows 7 with
SP1.For versions 3.0 to 3.4.x, Windows XP is acceptable.

Setting Path at Windows


To add the Python directory to the path for a particular session in Windows-
At the command prompt : type
path %path%;C:\Python and press Enter.
Note: C:\Python is the path of the Python directory.

Python Environment Variables


Here are important environment variables, which are recognized by Python-

Variable Description
It has a role similar to PATH. This variable tells the Python
interpreter where to locate the module files imported into a
PYTHONPATH program. It should include the Python source library
directory and the directories containing Python source code.
PYTHONPATH is sometimes, preset by the Python installer.
It contains the path of an initialization file containing Python
PYTHONSTARTUP source code. It is executed every time you start the interpreter. It
is named as .pythonrc.py in Unix and it contains commands that
load utilities or modify PYTHONPATH.

Department of CSE Page 3


PYTHON

It is used in Windows to instruct Python to find the first case


PYTHONCASEOK insensitive match in an import statement. Set this variable to any
value to activate it.
It is an alternative module search path. It is usually embedded in
PYTHONHOME the PYTHONSTARTUP or PYTHONPATH directories to make
switching module libraries easy.

Applications for Python


Python is used in many application domains. Here's a sampling.

 The Python Package Index lists thousands of third party modules for Python.

1. Web and Internet Development


Python offers many choices for web development:

 Frameworks such as Django and Pyramid.

 Micro-frameworks such as Flask and Bottle.

 Advanced content management systems such as Plone and django CMS.


Python's standard library supports many Internet protocols:

 HTML and XML

 JSON

 E-mail processing.

 Support for FTP, IMAP, and other Internet protocols.

 Easy-to-use socket interface.


And the Package Index has yet more libraries:

 Requests, a powerful HTTP client library.

 BeautifulSoup, an HTML parser that can handle all sorts of oddball HTML.

 Feedparser for parsing RSS/Atom feeds.

 Paramiko, implementing the SSH2 protocol.

 Twisted Python, a framework for asynchronous network programming.

Department of CSE Page 4


PYTHON

2. Scientific and Numeric


Python is widely used in scientific and numeric computing:

 SciPy is a collection of packages for mathematics, science, and engineering.

 Pandas is a data analysis and modeling library.

 IPython is a powerful interactive shell that features easy editing and recording of
a work session, and supports visualizations and parallel computing.

 The Software Carpentry Course teaches basic skills for scientific computing,
running bootcamps and providing open-access teaching materials.

3. Education
Python is a superb language for teaching programming, both at the introductory
level and in more advanced courses.

 Books such as How to Think Like a Computer Scientist, Python Programming: An


Introduction to Computer Science, and Practical Programming.

 The Education Special Interest Group is a good place to discuss teaching issues.

4. Desktop GUIs
The Tk GUI library is included with most binary distributions of Python.

Some toolkits that are usable on several platforms are available separately:

 wxWidgets

 Kivy, for writing multitouch applications.

 Qt via pyqt or pyside


Platform-specific toolkits are also available:

 GTK+

 Microsoft Foundation Classes through the win32 extensions

5. Software Development
Python is often used as a support language for software developers, for build
control and management, testing, and in many other ways.

 SCons for build control.

Department of CSE Page 5


PYTHON

 Buildbot and Apache Gump for automated continuous compilation and testing.

 Roundup or Trac for bug tracking and project management.

Running Python Scripts:

There are three different ways to start Python-

1. Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a
command line interpreter or shell window.
Enter python the command line.
Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS

Here is the list of all the available command line options-


Option Description

-d provide debug output


-o generate optimized bytecode (resulting in .pyo files)
-s do not run import site to look for Python paths on startup
-v verbose output (detailed trace on import statements)
-x disable class-based built-in exceptions (just use strings); obsolete
starting with version 1.6
-c cmd run Python script sent in as cmd string
file run Python script from given file

2. Script from the Command-line


A Python script can be executed at the command line by invoking the interpreter on
your application, as shown in the following example.

$python script.py # Unix/Linux


or
python% script.py # Unix/Linux
or
C:>python script.py # Windows/DOS

3. Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if
you have a GUI application on your system that supports Python.
 Unix: IDLE is the very first Unix IDE for Python.

Department of CSE Page 6


PYTHON

 Windows: PythonWin is the first Windows interface for Python and is an


IDE with a GUI.
 Macintosh: The Macintosh version of Python along with the IDLE IDE is
available from the main website, downloadable as either MacBinary or
BinHex'd files.

The Python language has many similarities to Perl, C, and Java. However, there are
some definite differences between the languages.
First Python Program
Let us execute the programs in different modes of programming.
Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the
following prompt-

on Linux:

$ python

Python 3.3.2 (default, Dec 10 2013, 11:35:01) [GCC 4.6.3]

Type "help", "copyright", "credits", or "license" for more information.


>>>

On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit
(Intel)] on win32

Type "copyright", "credits" or "license()" for more information.


>>>

Type the following text at the Python prompt and press Enter-

>>> print ("Hello, Python!")

If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result-

Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.
Let us write a simple Python program in a script. Python files have the
extension.py. Type the following source code in a test.py file.

Department of CSE Page 7


PYTHON

print("Hello, Python!")

On Linux

$ python test.py

This produces the following result-


Hello, Python!

On Windows

C:\Python34>Python test.py
This produces the following result-
Hello, Python!

Variables:
Variables are nothing but reserved memory locations to store values. It means that
when you create a variable, you reserve some space in the memory.
Based on the data type of a variable, the interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data
types to the variables, you can store integers, decimals or characters in these
variables.

Assigning Values to Variables:


Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal
sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example-
#!/usr/bin/python3

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string

print (counter)
print (miles)
print (name)

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and

Department of CSE Page 8


PYTHON

name variables, respectively. This produces the following result.

100
1000.0
John

Multiple Assignment:

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


For example

a= b = c = 1
Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
For example:

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

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

Keywords/Reserve Words:
The following list shows the Python keywords. These are reserved words and you
cannot use them as constants or variables or any other identifier names. All the
Python keywords contain lowercase letters only.
and exec not

as finally or

assert for pass

break from print

class global raise

continue If return

def import try

del in while

Department of CSE Page 9


PYTHON

elif is with

else lambda yield

except

Lines and Indentation

Python does not use 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 the indentation is variable, but all statements within the
block must be indented the same amount. For example

if True:
print ("True")
else:
print ("False")

However, the following block generates an error

If True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with the same number of spaces
would form a block.

Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the
use of the line continuation character (\) to denote that the line should continue.
For example

total = item_one + \
item_two + \
item_three

The statements contained within the [], {}, or () brackets do not need to use the
line continuation character. For example

Department of CSE Page 10


PYTHON

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

Quotation in Python

Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all
the following are legal

word = 'word'
sentence = "This is a sentence."
Paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python

A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment
and the Python interpreter ignores them.
# First comment
print ("Hello, Python!") # second comment

This produces the following result-


Hello, Python!

You can also type a comment on the same line after a statement or expression

name = "Madisetti" # This is again comment

Python does not have multiple-line commenting feature. You have to comment each
line individually as follows-

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Department of CSE Page 11


PYTHON

Input output statements


Python provides numerous built-in functions that are readily available to us
at the Python prompt. Some of the functions like input() and print() are widely used
for standard input and output operations respectively. Let us see the output section
first.

Python Output Using print() function


We use the print() function to output data to the standard output device (screen).
We can also output data to a file, but this will be discussed later.

print('This sentence is output to the screen')


# Output: This sentence is output to the screen

a=5

print('The value of a is', a)


# Output: The value of a is 5

In the second print() statement, we can notice that a space was added between
the stringand the value of variable a.This is by default, but we can change it.

The actual syntax of the print() function is

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.


The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value
is sys.stdout(screen). Here are an example to illustrate this.
print(1,2,3,4)
# Output: 1 2 3 4

print(1,2,3,4,sep='*')
# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&

Output formatting
Sometimes we would like to format our output to make it look attractive. This can
be done by using the str.format() method. This method is visible to any string
object.

Department of CSE Page 12


PYTHON

x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here the curly braces {} are used as placeholders. We can specify the order in
which it is printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
# Output: I love bread and butter

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread
We can even use keyword arguments to format the string.
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name =
'John'))
# output: Hello John, Goodmorning
We can even format strings like the old sprintf() style used in C programming
language. We use the % operator to accomplish this.
x = 12.3456789
print('The value of x is %3.2f' %x)
# output: The value of x is 12.35

print('The value of x is %3.4f' %x)


# output: The value of x is 12.3457

Python Input
The value of variables were defined or hard coded into the source code. To
allow flexibility we might want to take the input from the user. In Python, we have
the input() function to allow this.
The syntax for input() is

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.


>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To
convert this into a number we can use int() or float() functions.
>>> int('10')
10
>>> float('10')
10.0

Department of CSE Page 13


PYTHON

This same operation can be performed using the eval() function. But it takes
it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'

>>> eval('2+3')
5

Department of CSE Page 14


PYTHON

UNIT-II
Standard Data Types:
The data stored in memory can be of many types. For example, a person's age is
stored as a numeric value and his or her address is stored as alphanumeric
characters.
Python has various standard data types that are used to define the operations
possible on them and the storage method for each of them.
Python has five standard data types-
 Numbers
 String
 List
 Tuple
 Dictionary

Python Numbers
 Number data types store numeric values. Number objects are created when you
assign a value to them. For example

var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement.
The syntax of the del statement is

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement.
For example

Del var
del var_a, var_b
Python supports three different numerical types –

 int (signed integers)


 float (floating point real values)
 complex (complex numbers)

All integers in Python 3 are represented as long integers. Hence, there is no


separate number type as long.
Examples
Here are some examples of numbers

Department of CSE Page 15


PYTHON

int float complex


10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j

080 32.3+e18 .876j

-0490 -90.0 -.6545+0J

-0x260 -32.54e100 3e+26J

0x69 70.2-E12 4.53e-7j

A complex number consists of an ordered pair of real floating-point numbers


denoted by x + yj, where x and y are real numbers and j is the imaginary unit.

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of
strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0
in the beginning of the string and working their way from -1 to the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

This will produce the following result-

Hello World!
H
llo
llo World!
Hello World!Hello World!

Department of CSE Page 16


PYTHON

Hello World!TEST

Boolenas:
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively

Boolean Expressions
 Compound boolean expressions short circuit
 and and or return one of the elements in the expression
 Note that when None is returned the interpreter does not print
anything
>>> True and False
False
>>> False or True
True
>>> 7 and 14
14
>>> None and 2
>>> None or 2
2

Operators:
Operators are the constructs, which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called the operator.
Types of Operator
Python language supports the following types of operators-

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Department of CSE Page 17


PYTHON

Python Arithmetic Operators


Assume variable a holds the value 10 and variable b holds the value 21, then-
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 31
- Subtraction Subtracts right hand operand from left hand a – b = -11
operand.
* Multiplication Multiplies values on either side of the a * b = 210
operator
/ Division Divides left hand operand by right hand b / a = 2.1
operand
% Modulus Divides left hand operand by right hand b%a=1
operand and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to the
Operators power 20
// Floor Division - The division of operands 9//2 = 4 and
where 9.0//2.0 = 4.0
the result is the quotient in which the digits
after the decimal point are removed.

Example Program
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c )
c=a*b
print ("Line 3 - Value of c is ", c)
c=a/b
print ("Line 4 - Value of c is ", c )
c=a%b
print ("Line 5 - Value of c is ", c)
a=2

Department of CSE Page 18


PYTHON

b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

Python Comparison Operators


These operators compare the values on either side of them and decide the relation
among them. They are also called Relational operators.
Assume variable a holds the value 10 and variable b holds the value 20, then-
Operator Description Example
== If the values of two operands are equal, then the (a == b)
condition becomes true. is not true.
!= If values of two operands are not equal, then (a!= b) is true.
condition becomes true.
> If the value of left operand is greater than the (a > b) is not true.
value of right operand, then condition becomes
true.
< If the value of left operand is less than the value (a < b) is true.
of right operand, then condition becomes true.
>= If the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, then condition
becomes true.
<= If the value of left operand is less than or equal to (a <= b) is true.
the value of right operand, then condition
becomes true.
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3

Department of CSE Page 19


PYTHON

a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
a, b = b, a #values of a and b swapped. a becomes 10, b becomes 21
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program, it produces the following result-
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b

Department of CSE Page 20


PYTHON

Line 5 - a is either less than or equal to b


Line 6 - b is either greater than or equal to b

Python Assignment Operators


Assume variable a holds 10 and variable b holds 20, then-
Operator Description Example
= Assigns values from right side operands c = a + b assigns
to left side operand value of a + b into c
+= Add AND It adds right operand to the left operand c += a is equivalent
and assign the result to left operand to c = c + a
-= Subtract It subtracts right operand from the left c -= a is equivalent
operand and assign the result to left to c = c - a
AND
operand
*= Multiply It multiplies right operand with the left c *= a is equivalent
operand and assign the result to left to c = c * a
AND
operand
/= Divide AND It divides left operand with the right c /= a is equivalent
operand and assign the result to left to c = c / ac /= a is
operand equivalent to c = c /a
%= Modulus It takes modulus using two operands c %= a is equivalent
and to c = c % a
AND
assign the result to left operand
**= Exponent Performs exponential (power) calculation c **= a is
on operators and assign value to the left equivalent to c = c ** a
AND
operand
//= Floor It performs floor division on operators and c //= a is equivalent
assign value to the left operand to c = c // a
Division

Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )

Department of CSE Page 21


PYTHON

c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c=2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Python Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60;
and b = 13; Now in binary format they will be as follows

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Pyhton's built-in function bin() can be used to obtain binary representation of an


integer number.
The following Bitwise operators are supported by Python language-
Operator Description Example

Department of CSE Page 22


PYTHON

& Binary AND Operator copies a bit to the result, if it (a & b) (means 0000
exists in both operands 1100)
| Binary OR It copies a bit, if it exists in either operand. (a | b) = 61 (means
0011 1101)
^ Binary XOR It copies the bit, if it is set in one operand (a ^ b) = 49 (means
but not both. 0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means
Complement bits. 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary The left operand’s value is moved left by a << = 240 (means
Left Shift the number of bits specified by the right 1111 0000)
operand.
>> Binary The left operand’s value is moved right a >> = 15 (means
Right Shift by the number of bits specified by the 0000 1111)
right operand.

Example
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c=0
c = a & b; # 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))
c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
c = ~a; # -61 = 1100 0011
print ("result of COMPLEMENT is ", c,':',bin(c))
c = a << 2; # 240 = 1111 0000
print ("result of LEFT SHIFT is ", c,':',bin(c))
c = a >> 2; # 15 = 0000 1111
print ("result of RIGHT SHIFT is ", c,':',bin(c))
When you execute the above program, it produces the following result

a=60 : 0b111100 b= 13 : 0b1101

Department of CSE Page 23


PYTHON

result of AND is 12 : 0b1100


result of OR is 61 : 0b111101
result of EXOR is 49 : 0b110001
result of COMPLEMENT is -61 : -0b111101
result of LEFT SHIFT is 240 : 0b11110000
result of RIGHT SHIFT is 15 : 0b111

Python Logical Operators


The following logical operators are supported by Python language. Assume variable
a holds True and variable b holds False then-
Operator Description Example
and Logical If both the operands are true then (a and b) is False.
AND condition becomes true.
or Logical OR If any of the two operands are non-zero (a or b) is True.
then condition becomes true.
Used to reverse the logical state of its Not(a and b)
not Logical NOT operand. is True.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists,
or tuples. There are two membership operators as explained below-
Operator Description Example
Evaluates to true, if it finds a variable x in y, here in results
in in the specified sequence and false in
otherwise. a 1 if x is a member of
sequence y.

not in Evaluates to true, if it does not find a x not in y, here not in


variable in the specified sequence and results in a 1 if x is not
false otherwise. a member of sequence
y.
Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")

Department of CSE Page 24


PYTHON

if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")

When you execute the above program, it produces the following result-

Line 1 - a is not available in the given list


Line 2 - b is not available in the given list
Line 3 - a is available in the given list

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below:

Operator Description Example


Evaluates to true if the variables on x is y, here is results
is either side of the operator point to the same in 1 if id(x) equals
object and false otherwise. id(y).

is not Evaluates to false if the variables on x is not y, here is


either side of the operator point to the same not results in 1 if id(x)
object and true otherwise. is not equal to id(y).

Example:

a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:

Department of CSE Page 25


PYTHON

print ("Line 2 - a and b do not have same identity")


if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")

When you execute the above program, it produces the following result

Line 1 a= 20 : 1594701888 b= 20 : 1594701888


Line 2 - a and b have same identity
Line 3 - a and b have same identity
Line 4 a= 20 : 1594701888 b= 30 : 1594702048
Line 5 - a and b do not have same identity

Python Operators Precedence


The following table lists all the operators from highest precedence to the lowest.
Operator Description
** Exponentiation (raise to the power)
~+- complement, unary plus and minus (method names for
the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators

Department of CSE Page 26


PYTHON

= %= /= //= -= += Assignment operators


*= **=
is, is not Identity operators
in not in Membership operators
not or and Logical operators
Operator precedence affects the evaluation of an an expression.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator *
has higher precedence than +, so it first multiplies 3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom.
Example
#!/usr/bin/python3
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

When you execute the above program, it produces the following result
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

Decision-making statements:

Decision-making is the anticipation of conditions occurring during the execution of a


Program and specified actions taken according to the conditions.

Department of CSE Page 27


PYTHON

Decision structures evaluate multiple expressions, which produce TRUE or FALSE as


the outcome. You need to determine which action to take and which statements to
execute if the outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of
the programming languages-

Python programming language assumes any non-zero and non-null values as


TRUE, and any zero or null values as FALSE value.
Python programming language provides the following types of decision-making
Statements.

Statement Description
if statements An if statement consists of a Boolean expression followed by
one or more statements.
if...else statements An if statement can be followed by an optional else
statement, which executes when the boolean expression is
FALSE.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).

IF Statement
The IF statement is similar to that of other languages. The if statement contains a
logical expression using which the data is compared and a decision is made based
on the result of the comparison.

Syntax:

Department of CSE Page 28


PYTHON

if expression:
statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. In Python, statements in a block are uniformly
indented after the: symbol. If boolean expression evaluates to FALSE, then the first
set of code after the end of block is executed.

Flow Diagram

Example
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")

When the above code is executed, it produces the following result

Department of CSE Page 29


PYTHON

1 - Got a true expression value


100
Good bye!

IF...ELIF...ELSE Statements

An else statement can be combined with an if statement. An else statement


contains a block of code that executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at the most only
one else statement following if.

Syntax
The syntax of the if...else statement is
if expression:
statement(s)
else:
statement(s)

Flow Diagram

Example

#!/usr/bin/python3
amount=int(input("Enter amount: "))

Department of CSE Page 30


PYTHON

if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
print ("Net payable:",amount-discount)

In the above example, discount is calculated on the input amount. Rate of discount
is 5%, if the amount is less than 1000, and 10% if it is above 10000. When the
above code is executed, it produces the following result-
Enter amount: 600
Discount 30.0
Net payable: 570.0
Enter amount: 1200
Discount 120.0
Net payable: 1080.0

The elif Statement

The elif statement allows you to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at the most one statement, there can be an arbitrary number of elif
statements following an if.

Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but
we can use if..elif...statements to simulate switch case as follows-
Example:

Department of CSE Page 31


PYTHON

#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
When the above code is executed, it produces the following result

Enter amount: 600


Discount 30.0
Net payable: 570.0
Enter amount: 3000
Discount 300.0
Net payable: 2700.0
Enter amount: 6000
Discount 900.0
Net payable: 5100.0

Nested IF Statements
There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another
if...elif...else construct.

Syntax
The syntax of the nested if...elif...else construct may be
if expression1:
statement(s)
if expression2:

Department of CSE Page 32


PYTHON

statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
# !/usr/bin/python3
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
When the above code is executed, it produces the following result

Enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
enter number5
not Divisible by 2 not divisible by 3

Department of CSE Page 33


PYTHON

Python-Loops:
In general, statements are executed sequentially- The first statement in a function
is executed first, followed by the second, and so on. There may be a situation when
you need to execute a block of code several number of times.
Programming languages provide various control structures that allow more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times.
The following diagram illustrates a loop statement.

Python programming language provides the following types of loops to handle


looping requirements.
Loop Type Exception
while loop Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing
the loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable
nested loops You can use one or more loop inside any another while,
or
for loop.

while Loop Statements


A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is
While expression:
statement(s)

Department of CSE Page 34


PYTHON

Here, statement(s) may be a single statement or a block of statements with


uniform indent. The condition may be any expression, and true is any non-zero
value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.

In Python, all the statements indented by the same number of character spaces
after a programming construct are considered to be part of a single block of code.
Python uses indentation as its method of grouping statements.

Flow Diagram

Example
#!/usr/bin/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
When the above code is executed, it produces the following result-

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4

Department of CSE Page 35


PYTHON

The count is: 5


The count is: 6
The count is: 7
The count is: 8
Good bye!
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must be
cautious when using while loops because of the possibility that this condition never
resolves to a FALSE value. This results in a loop that never ends. Such a loop is
called an infinite loop.

An infinite loop might be useful in client/server programming where the server


needs to run continuously so that client programs can communicate with it as and
when required.
#!/usr/bin/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")

When the above code is executed, it produces the following result-

Enter a number :20


You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number :"))

Department of CSE Page 36


PYTHON

KeyboardInterrupt

The above example goes in an infinite loop and you need to use CTRL+C to exit the
program.

Using else Statement with while Loop:

Python supports having an else statement associated with a loop statement.


 If the else statement is used with a while loop, the else statement is
executed when the condition becomes false.

The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else
statement gets executed.

#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")

When the above code is executed, it produces the following result-

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single
statement, it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause-


#!/usr/bin/python3

Department of CSE Page 37


PYTHON

flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.

for Loop Statements


The for statement in Python has the ability to iterate over the items of any
sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterating_var. Next, the
statements block is executed. Each item in the list is assigned to iterating_var, and
the statement(s) block is executed until the entire sequence is exhausted.

Flow Diagram

The range() function


The built-in function range() is the right function to iterate over a sequence of
numbers. It generates an iterator of arithmetic progressions.
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]

Department of CSE Page 38


PYTHON

range() generates an iterator to progress integers starting with 0 upto n-1. To


obtain a list object of the sequence, it is type casted to list(). Now this list can be
iterated using the for statement.
>>> for var in list(range(5)):
print (var)

This will produce the following output.


0
1
2
3
4
Example
#!/usr/bin/python3
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
print ("Good bye!")
When the above code is executed, it produces the following result –
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the
sequence itself. Following is a simple example-

Department of CSE Page 39


PYTHON

#!/usr/bin/python3
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("Good bye!")
When the above code is executed, it produces the following result
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Here, we took the assistance of the len() built-in function, which provides the total
number of elements in the tuple as well as the range() built-in function to give us
the actual sequence to iterate over.

Using else Statement with For Loop


Python supports having an else statement associated with a loop statement.
 If the else statement is used with a for loop, the else block is executed only
if for loop terminates normally (and not by encountering break statement).

The following example illustrates the combination of an else statement with a for
statement that searches for even number in given list.
#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number')
When the above code is executed, it produces the following result

the list does not contain even number

Nested loops
Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.

Syntax

Department of CSE Page 40


PYTHON

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is
as follows.
while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that you can put any type of loop inside any other
type of loop. For example a for loop can be inside a while loop or vice versa.

Example
The following program uses a nested-for loop to display multiplication tables from
1-10.

#!/usr/bin/python3
import sys
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

The print() function inner loop has end=' ' which appends a space instead of
default newline. Hence, the numbers will appear in one row.

Last print() will be executed at the end of inner for loop.

When the above code is executed, it produces the following result


1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50

Department of CSE Page 41


PYTHON

6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Loop Control Statements:

The Loop control statements change the execution from its normal sequence. When
the execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
Python supports the following control statements.

Control Statement Description


Terminates the loop statement and transfers execution
break statement to the statement immediately following the loop.

Causes the loop to skip the remainder of its body and


continue statement immediately retest its condition prior to reiterating.

The pass statement in Python is used when a


pass statement statement is required syntactically but you do not want
any command or code to execute.

break statement

The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the
traditional break statement in C.

The most common use of break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in both while
and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows
break

Flow Diagram

Department of CSE Page 42


PYTHON

Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break
print ("Good bye!")

When the above code is executed, it produces the following result-

Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7

Department of CSE Page 43


PYTHON

Current variable value : 6


Good bye!

The following program demonstrates the use of break in a for loop iterating over a
list. User inputs a number, which is searched in the list. If it is found, then the loop
terminates with the 'found' message.

#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')

The above program will produce the following output


any number: 33
number found in list
any number: 5
number not found in list

continue Statement
The continue statement in Python returns the control to the beginning of the
current loop.

When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.

The continue statement can be used in both while and for loops.

Syntax

continue

Flow Diagram

Department of CSE Page 44


PYTHON

Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
print ("Good bye!")

When the above code is executed, it produces the following result-


Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6

Department of CSE Page 45


PYTHON

Current variable value : 4


Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!

pass Statement:

It is used when a statement is required syntactically but you do not want any
command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The
pass statement is also useful in places where your code will eventually go, but has
not been written yet i.e. in stubs).

Syntax

Pass

Example
#!/usr/bin/python3
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following result

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block

Department of CSE Page 46


PYTHON

Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

UNIT-III
List
Python offers a range of compound datatypes often referred to as sequences. List is
one of the most frequently used and very versatile datatype used in Python.

How to create a list?


In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float,
string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

How to access elements from a list?


Department of CSE Page 47
PYTHON

There are various ways in which we can access the elements of a list.
List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So,
a list having 5 elements will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must
be an integer. We can't use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_list[0][1])

# Output: 5
print(n_list[1][3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.

my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

Department of CSE Page 48


PYTHON

# Output: p
print(my_list[-5])
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two index that will slice
that portion from the list.

How to change or add elements to a list?


List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

# Output: [1, 3, 5, 7]
print(odd)

Department of CSE Page 49


PYTHON

We can add one item to a list using append() method or add several items
using extend()method.
odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)
We can also use + operator to combine two lists. This is also called concatenation.
The * operator repeats a list for the given number of times.
odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["re", "re", "re"]


print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the


method insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]
odd.insert(1,3)

# Output: [1, 3, 9]
print(odd)

odd[2:2] = [5, 7]

# Output: [1, 3, 5, 7, 9]
print(odd)

How to delete or remove elements from a list?


We can delete one or more items from a list using the keyword del. It can even delete
the list entirely.
my_list = ['p','r','o','b','l','e','m']

# delete one item


del my_list[2]

Department of CSE Page 50


PYTHON

# Output: ['p', 'r', 'b', 'l', 'e', 'm']


print(my_list)

# delete multiple items


del my_list[1:5]

# Output: ['p', 'm']


print(my_list)

# delete entire list


del my_list

# Error: List not defined


print(my_list)
We can use remove() method to remove the given item or pop() method to remove
an item at the given index. The pop() method removes and returns the last item if
index is not provided. This helps us implement lists as stacks (first in, last out data
structure).
We can also use the clear() method to empty a list.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)

Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.

>>> my_list = ['p','r','o','b','l','e','m']

Department of CSE Page 51


PYTHON

>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python List Methods


Methods that are available with list object in Python programming are tabulated
below.They are accessed as list.method(). Some of the methods have already been
used above.

Python List Methods

append() - Add an element to the end of the list

extend() - Add all elements of a list to the another list

insert() - Insert an item at the defined index

remove() - Removes an item from the list

pop() - Removes and returns an element at the given index

clear() - Removes all items from the list

index() - Returns the index of the first matched item

count() - Returns the count of number of items passed as an argument

sort() - Sort items in a list in ascending order

reverse() - Reverse the order of items in the list

copy() - Returns a shallow copy of the list

Some examples of Python list methods:


my_list = [3, 8, 1, 6, 0, 8, 4]

# Output: 1
print(my_list.index(8))

# Output: 2

Department of CSE Page 52


PYTHON

print(my_list.count(8))

my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)

my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)

List Comprehension: Elegant way to create new List


List comprehension is an elegant and concise way to create new list from an existing
list in Python. List comprehension consists of an expression followed by for
statement inside square brackets. Here is an example to make a list with each item
being increasing power of 2.

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]


print(pow2)

This code is equivalent to


pow2 = []
for x in range(10):
pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An


optional ifstatement can filter out items for the new list. Here are some examples.
>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

Built-in Functions with List


Built-in functions
like all(), any(), enumerate(), len(), max(), min(), list(), sorted() etc. are
commonly used with list to perform different tasks.

Department of CSE Page 53


PYTHON

Built-in Functions with List

Function Description

Return True if all elements of the list are true (or if the list is
all()
empty).

Return True if any element of the list is true. If the list is empty,
any()
return False.

Return an enumerate object. It contains the index and value of all


enumerate()
the items of list as a tuple.

len() Return the length (the number of items) in the list.

list() Convert an iterable (tuple, string, set, dictionary) to a list.

max() Return the largest item in the list.

min() Return the smallest item in the list

sorted() Return a new sorted list (does not sort the list itself).

sum() Return the sum of all elements in the list.

What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is
that we cannot change the elements of a tuple once it is assigned whereas in a list,
elements can be changed.

Advantages of Tuple over List


Since, tuples are quite similiar to lists, both of them are used in similar situations as
well. However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes. Since tuple are immutable, iterating through tuple
is faster than with list. So there is a slight performance boost. Tuples that contain
immutable elements can be used as key for a dictionary. With list, this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.

Department of CSE Page 54


PYTHON

Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma. The parentheses are optional but is a good practice to write it.
A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).

# empty tuple
# Output: ()
my_tuple = ()
print(my_tuple)

# tuple having integers


# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

# tuple can be created without parentheses


# also called tuple packing
# Output: 3, 4.6, "dog"

my_tuple = 3, 4.6, "dog"


print(my_tuple)

# tuple unpacking is also possible


# Output:
#3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)

Creating a tuple with one element is a bit tricky.


Having one element within parentheses is not enough. We will need a trailing comma
to indicate that it is in fact a tuple.

Department of CSE Page 55


PYTHON

# only parentheses is not enough


# Output: <class 'str'>
my_tuple = ("hello")
print(type(my_tuple))

# need a comma at the end


# Output: <class 'tuple'>
my_tuple = ("hello",)
print(type(my_tuple))

# parentheses is optional
# Output: <class 'tuple'>
my_tuple = "hello",
print(type(my_tuple))

Accessing Elements in a Tuple


There are various ways in which we can access the elements of a tuple.

1. Indexing
We can use the index operator [] to access an item in a tuple where the index starts
from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element
other that (6, 7,...) will raise an IndexError.
The index must be an integer, so we cannot use float or other types. This will result
into TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the example
below.
my_tuple = ('p','e','r','m','i','t')

# Output: 'p'
print(my_tuple[0])

# Output: 't'
print(my_tuple[5])

# index must be in range


# If you uncomment line 14,
# you will get an error.
# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer


# If you uncomment line 21,
# you will get an error.
# TypeError: list indices must be integers, not float

Department of CSE Page 56


PYTHON

#my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
# Output: 's'
print(n_tuple[0][3])

# nested index
# Output: 4
print(n_tuple[1][1])
When you run the program, the output will be:
p
t
s
4

2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on.
my_tuple = ('p','e','r','m','i','t')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])

3. Slicing
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th


# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# elements beginning to 2nd


# Output: ('p', 'r')
print(my_tuple[:-7])

# elements 8th to end


# Output: ('i', 'z')

Department of CSE Page 57


PYTHON

print(my_tuple[7:])

# elements beginning to end


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need the index that will slice
the portion from the tuple.

Changing a Tuple
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned.
But, if the element is itself a mutable datatype like list, its nested items can be
changed.
We can also assign a tuple to different values (reassignment).
my_tuple = (4, 2, 3, [6, 5])

# we cannot change an element


# If you uncomment line 8
# you will get an error:
# TypeError: 'tuple' object does not support item assignment

#my_tuple[1] = 9

# but item of mutable element can be changed


# Output: (4, 2, 3, [9, 5])
my_tuple[3][0] = 9
print(my_tuple)

# tuples can be reassigned


# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
my_tuple = ('p','r','o','g','r','a','m','i','z')
print(my_tuple)
We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the *
operator.
Both + and * operations result into a new tuple.
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)

Department of CSE Page 58


PYTHON

print((1, 2, 3) + (4, 5, 6))

# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we
cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items


# if you uncomment line 8,
# you will get an error:
# TypeError: 'tuple' object doesn't support item deletion

#del my_tuple[3]

# can delete entire tuple


# NameError: name 'my_tuple' is not defined
del my_tuple
my_tuple

Python Tuple Methods


Methods that add items or remove items are not available with tuple. Only the
following two methods are available.

Python Tuple Method

Method Description

count(x) Return the number of items that is equal to x

index(x) Return index of first item that is equal to x


Some examples of Python tuple methods:
my_tuple = ('a','p','p','l','e',)

# Count
# Output: 2
print(my_tuple.count('p'))

# Index
# Output: 3

Department of CSE Page 59


PYTHON

print(my_tuple.index('l'))

Built-in Functions with Tuple


Built-in functions
like all(), any(), enumerate(), len(), max(), min(), sorted(), tuple()etc. are
commonly used with tuple to perform different tasks.

Built-in Functions with Tuple

Function Description

Return True if all elements of the tuple are true (or if the tuple is
all()
empty).

Return True if any element of the tuple is true. If the tuple is


any()
empty, return False.

Return an enumerate object. It contains the index and value of all


enumerate()
the items of tuple as pairs.

len() Return the length (the number of items) in the tuple.

max() Return the largest item in the tuple.

min() Return the smallest item in the tuple

Take elements in the tuple and return a new sorted list (does not
sorted()
sort the tuple itself).

sum() Retrun the sum of all elements in the tuple.

tuple() Convert an iterable (list, string, set, dictionary) to a tuple.

What is a set in Python?


A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.

Department of CSE Page 60


PYTHON

How to create a set?


A set is created by placing all the items (elements) inside curly braces {}, separated
by comma or by using the built-in function set().
It can have any number of items and they may be of different types (integer, float,
tuple, string etc.). But a set cannot have a mutable element, like list, set
or dictionary, as its element.
# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Different Python Set Methods


There are many set methods, some of which we have already used above. Here is a
list of all the methods that are available with set objects.

Python Set Methods

Method Description

add() Add an element to a set

clear() Remove all elements form a set

copy() Return a shallow copy of a set

Return the difference of two or more sets as a


difference()
new set

Remove all elements of another set from this


difference_update()
set

Remove an element from set if it is a member.


discard()
(Do nothing if the element is not in set)

intersection() Return the intersection of two sets as a new set

Update the set with the intersection of itself and


intersection_update()
another

Department of CSE Page 61


PYTHON

isdisjoint() Return True if two sets have a null intersection

issubset() Return True if another set contains this set

issuperset() Return True if this set contains another set

Remove and return an arbitary set element.


pop()
Raise KeyErrorif the set is empty

Remove an element from a set. If the element


remove()
is not a member, raise a KeyError

Return the symmetric difference of two sets as


symmetric_difference()
a new set

Update a set with the symmetric difference of


symmetric_difference_update()
itself and another

union() Return the union of sets in a new set

update() Update a set with the union of itself and others

What is dictionary in Python?


Python dictionary is an unordered collection of items. While other compound data
types have only value as an element, a dictionary has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?


Creating a dictionary is as simple as placing items inside curly braces {} separated
by comma.
An item has a key and the corresponding value expressed as a pair, key: value.
While values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()

Department of CSE Page 62


PYTHON

my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])
As you can see above, we can also create a dictionary using the built-in
function dict().

How to access elements from a dictionary?


While indexing is used with other container types to access values, dictionary uses
keys. Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key
is not found.
my_dict = {'name':'Jack', 'age': 26}

# Output: Jack
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']
When you run the program, the output will be:
Jack
26

Python Dictionary Methods


Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples.

Python Dictionary Methods

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v(defaults to None).

Department of CSE Page 63


PYTHON

Return the value of key. If key doesnot exit,


get(key[,d])
return d (defaults to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is
pop(key[,d]) not found. If d is not provided and key is not found,
raises KeyError.

Remove and return an arbitary item (key, value).


popitem()
Raises KeyError if the dictionary is empty.

If key is in the dictionary, return its value. If not,


setdefault(key[,d])
insert key with a value of d and return d (defaults to None).

Update the dictionary with the key/value pairs from other,


update([other])
overwriting existing keys.

values() Return a new view of the dictionary's values


Here are a few example use of these methods.
marks = {}.fromkeys(['Math','English','Science'], 0)

# Output: {'English': 0, 'Math': 0, 'Science': 0}


print(marks)

for item in marks.items():


print(item)

# Output: ['English', 'Math', 'Science']


list(sorted(marks.keys()))
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create new dictionary
from an iterable in Python. Dictionary comprehension consists of an expression pair
(key: value) followed by forstatement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and
its square.
squares = {x: x*x for x in range(6)}

# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


print(squares)

Department of CSE Page 64


PYTHON

UNIT-IV
Functions:
A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you
can also create your own functions. These functions are called user-defined functions.

Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.

 Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
 Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.
 The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.

Syntax:

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the
same order that they were defined.

Example
The following function takes a string as input parameter and prints it on the standard
screen.

def printme( str ):


"This prints a passed string into this function"
print (str)
return

Department of CSE Page 65


PYTHON

Calling a Function

Defining a function gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from
another function or directly from the Python prompt. Following is an example to call the
printme() function-

#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result-

This is first call to the user defined function!


Again second call to the same function

Pass by Reference vs Value

All parameters (arguments) in the Python language are passed by reference. It means if
you change what a parameter refers to within a function, the change also reflects back in
the calling function. For example-

#!/usr/bin/python3

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

Department of CSE Page 66


PYTHON

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

Values inside the function before change: [10, 20, 30]


Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]

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

#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

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

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


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

Function Arguments

You can call a function by using the following types of formal arguments-
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments

Required Arguments

Required arguments are the arguments passed to a function in correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives
a syntax error as follows-

#!/usr/bin/python3

Department of CSE Page 67


PYTHON

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return

# Now you can call printme function


printme()
When the above code is executed, it produces the following result-

Traceback (most recent call last):


File "test.py", line 11, in <module>
printme()
TypeError: printme() missing 1 required positional argument: 'str'

Keyword Arguments

Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You
can also make keyword calls to the printme() function in the following ways-

#!/usr/bin/python3

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result-

My string

The following example gives a clearer picture. Note that the order of parameters does not
matter.

#!/usr/bin/python3
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)

Department of CSE Page 68


PYTHON

return

# Now you can call printinfo function


printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result-

Name: miki
Age 50
Default Arguments

A default argument is an argument that assumes a default value if a value is not provided
in the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed.

#!/usr/bin/python3

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result-

Name: miki
Age 50
Name: miki
Age 35

Variable-length Arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is given below

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified
during the function call. Following is a simple example-

Department of CSE Page 69


PYTHON

#!/usr/bin/python3

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result-

Output is:
10
Output is:
70
60
50

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.

 Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an
expression.
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation
by passing function, during invocation for performance reasons.

Syntax
The syntax of lambda function contains only a single statement, which is as follows

lambda[arg1 [,arg2,.....argn]]:expression

Following is an example to show how lambda form of function works-

#!/usr/bin/python3

Department of CSE Page 70


PYTHON

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

When the above code is executed, it produces the following result

Value of total : 30
Value of total : 40

The return Statement

The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
You can return a value from a function as follows-
#!/usr/bin/python3

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total

# Now you can call sum function


total = sum( 10, 20 )
print ("Outside the function : ", total )

When the above code is executed, it produces the following result-

Inside the function : 30


Outside the function : 30

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python-
 Global variables
 Local variables

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all

Department of CSE Page 71


PYTHON

functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example-

#!/usr/bin/python3

total = 0 # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total

# Now you can call sum function


sum( 10, 20 )
print ("Outside the function global total : ", total )

When the above code is executed, it produces the following result-

Inside the function local total : 30


Outside the function global total : 0

Modules

A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes
and variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file namedaname.py.
Here is an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

The import Statement


You can use any Python source file as a module by executing an import statement in some
other Python source file.
The import has the following syntax
import module1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module

Department of CSE Page 72


PYTHON

is present in the search path. A search path is a list of directories that the interpreter
searches before importing a module. For example, to import the module hello.py, you
need to put the following command at the top of the script-

#!/usr/bin/python3
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result-

Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening repeatedly, if multiple imports occur.

The from...import Statement


Python's from statement lets you import specific attributes from a module into the current
namespace.

The from...import has the following syntax

from modname import name1[, name2[, ... nameN]]

For example, to import the function fibonacci from the module fib, use the following
statement-

#!/usr/bin/python3

# Fibonacci numbers module


def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

>>> from fib import fib


>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the
importing module.

The from...import * Statement:

It is also possible to import all the names from a module into the current namespace by
using the following import statement

Department of CSE Page 73


PYTHON

from modname import *

This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

Executing Modules as Scripts

Within a module, the module’s name (as a string) is available as the value of the global
variable __name__. The code in the module will be executed, just as if you imported it,
but with the __name__ set to "__main__".
Add this code at the end of your module-

#!/usr/bin/python3

# Fibonacci numbers module


def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

if __name__ == "__main__":
f=fib(100)
print(f)

When you run the above code, the following output will be displayed.

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Locating Modules

When you import a module, the Python interpreter searches for the module in the following
sequences-

 The current directory.


 If the module is not found, Python then searches each directory in the shell variable
o PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python3/.

The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation
dependent default.

The PYTHONPATH Variable


The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax
of PYTHONPATH is the same as that of the shell variable PATH.

Department of CSE Page 74


PYTHON

Here is a typical PYTHONPATH from a Windows system

set PYTHONPATH=c:\python34\lib;

And here is a typical PYTHONPATH from a UNIX system

set PYTHONPATH=/usr/local/lib/python

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).

 A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
 Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
 Python makes educated guesses on whether variables are local or global. It
assumes that any variable assigned a value in a function is local.
 Therefore, in order to assign a value to a global variable within a function, you must
first use the global statement.
 The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the
function Money, we assign Money a value, therefore Python assumes Money as a local
variable.

However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem

#!/usr/bin/python3

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)

AddMoney()
print (Money)

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the names defined by
a module.

The list contains the names of all the modules, variables and functions that are defined in

Department of CSE Page 75


PYTHON

a module. Following is a simple example-

#!/usr/bin/python3

# Import built-in module math


import math
content = dir(math)
print (content)
When the above code is executed, it produces the following result-

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',


'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the global and
local namespaces depending on the location from where they are called.

 If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.

 If globals() is called from within a function, it will return all the names that can
be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted
using the keys() function

The reload() Function


When a module is imported into a script, the code in the top-level portion of a module is
executed only once.

Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this

reload(module_name)

Here, module_name is the name of the module you want to reload and not the string
containing the module name. For example, to reload hello module, do the following

reload(hello)

Packages in Python

Department of CSE Page 76


PYTHON

A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has the following line of
source code-

#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same name as above.
They are −
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()

Now, create one more file __init__.py in the Phone directory-


 Phone/__init__.py
To make all of your functions available when you have imported Phone, you need to put
explicit import statements in __init__.py as follows

from Pots import Pots


from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.

#!/usr/bin/python3
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single function in each file, but you
can keep multiple functions in your files. You can also define different Python classes in
those files and then you can create your packages out of those classes.

Introduction to PIP:
PyPI - the Python Package Index

The Python Package Index is a repository of software for the Python programming
language.

Department of CSE Page 77


PYTHON

Requirements for installing packages


Install PIP, setuptools and wheel
If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will
already have pip and setuptools, but will need to upgrade to the latest version:
On Linux or OS X:

pip install -U pip setuptools


On Windows:

python -m pip install -U pip setuptools


 If you’re using a Python install on Linux that’s managed by the system package
manager (e.g “yum”, “apt-get” etc...), and you want to use the system package
manager to install or upgrade pip, then see Installing pip/setuptools/wheel with
Linux Package Managers
 Otherwise:
 Securely Download get-pip.py
 Run python get-pip.py . This will install or upgrade pip. Additionally, it will

install setuptools and wheel if they’re not installed already.

Use PIP for Installing:

pip is the recommended installer. Below, we’ll cover the most common usage
scenarios.

Installing from PyPI(Python Package Index )


The most common usage of pip is to install from the Python Package Index using
a requirement specifier. Generally speaking, a requirement specifier is composed of
a project name followed by an optional version specifier. PEP 440 contains a full
specification of the currently supported specifiers. Below are some examples.

To install the latest version of “SomeProject”:


pip install 'SomeProject'

To install a specific version:


pip install 'SomeProject==1.4'

To install greater than or equal to one version and less than another:
pip install 'SomeProject>=1,<2'

Department of CSE Page 78


PYTHON

To install a version that’s “compatible” with a certain version:


pip install 'SomeProject~=1.4.2'

 pip is the preferred installer program. Starting with Python 3.4, it is included
by default with the Python binary installers.
 A virtual environment is a semi-isolated Python environment that allows
packages to be installed for use by a particular application, rather than being
installed system wide.
 venv is the standard tool for creating virtual environments, and has been
part of Python since Python 3.3. Starting with Python 3.4, it defaults to
installing pip into all created virtual environments.
 virtualenv is a third party alternative (and predecessor) to venv. It allows
virtual environments to be used on versions of Python prior to 3.4, which
either don’t provide venv at all, or aren’t able to automatically install pip into
created environments.
 The Python Packaging Index is a public repository of open source licensed
packages made available for use by other Python users.
 the Python Packaging Authority are the group of developers and
documentation authors responsible for the maintenance and evolution of the
standard packaging tools and the associated metadata and file format
standards. They maintain a variety of tools, documentation, and issue
trackers on both GitHub and BitBucket.
 distutils is the original build and distribution system first added to the Python
standard library in 1998. While direct use of distutils is being phased out, it
still laid the foundation for the current packaging and distribution
infrastructure, and it not only remains part of the standard library, but its
name lives on in other ways (such as the name of the mailing list used to
coordinate Python packaging standards development).

Basic usage

The standard packaging tools are all designed to be used from the command
line.

The following command will install the latest version of a module and its
dependencies from the Python Packaging Index:

python -m pip install SomePackage

Department of CSE Page 79


PYTHON

It’s also possible to specify an exact or minimum version directly on the command
line. When using comparator operators such as >, < or some other special character
which get interpreted by shell, the package name and the version should be enclosed
within double quotes:

python -m pip install SomePackage==1.0.4 # specific version


python -m pip install "SomePackage>=1.0.4" # minimum version

Normally, if a suitable module is already installed, attempting to install it again will


have no effect. Upgrading existing modules must be requested explicitly:

python -m pip install --upgrade SomePackage

Creation of virtual environments is done through the venv module.


Python “Virtual Environments” allow Python packages to be installed in an isolated
location for a particular application, rather than being installed globally.

Imagine you have an application that needs version 1 of LibFoo, but another
application requires version 2. How can you use both these applications? If you install
everything into /usr/lib/python2.7/site-packages (or whatever your platform’s
standard location is), it’s easy to end up in a situation where you unintentionally
upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an
application works, any change in its libraries or the versions of those libraries can
break the application.

Also, what if you can’t install packages into the global site-packages directory? For
instance, on a shared host.

In all these cases, virtual environments can help you. They have their own installation
directories and they don’t share libraries with other virtual environments.

Currently, there are two viable tools for creating Python virtual environments:

 venv is available by default in Python 3.3 and later, and


installs pip and setuptools into created virtual environments in Python 3.4 and
later.
 virtualenv needs to be installed separately, but supports Python 2.6+ and Python
3.3+, and pip, setuptools and wheel are always installed into created virtual
environments by default (regardless of Python version).

Department of CSE Page 80


PYTHON

The basic usage is like so:


Using virtualenv:
virtualenv <DIR>
source <DIR>/bin/activate
Using venv:

python3 -m venv <DIR>


source <DIR>/bin/activate

UNIT-V
Errors and Exceptions

Department of CSE Page 81


PYTHON

There are two distinguishable kinds of errors: syntax errors and exceptions

Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
The parser repeats the offending line and displays a little ‘arrow’ pointing at the
earliest point in the line where the error was detected. The error is caused by (or at
least detected at) the token preceding the arrow: in the example, the error is
detected at the function print(), since a colon (':') is missing before it. File name and
line number are printed so you know where to look in case the input came from
ascript.

Exceptions
An exception is an error that happens during the execution of a program. Exception
handling is a construct in some programming languages to handle or deal with
errors automatically. Many programming languages like C++, Objective-C, PHP,
Java, Ruby, Python, and many others have built-in support for exception handling.

Even if a statement or expression is syntactically correct, it may cause an error when


an attempt is made to execute it. Errors detected during execution are
called exceptions and are not unconditionally fatal. Most exceptions are not handled
by programs, however, and result in error messages as shown here:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in the
example are ZeroDivisionError, NameError and TypeError. The string printed as the
exception type is the name of the built-in exception that occurred. This is true for all
built-in exceptions, but need not be true for user-defined exceptions (although it is a

Department of CSE Page 82


PYTHON

useful convention). Standard exception names are built-in identifiers (not reserved
keywords)

Handling Exceptions in Python


Exceptions handling in Python is very similar to Java.

Some of the common exception errors are:


IOError
If the file cannot be opened.
ImportError
If python cannot find the module
ValueError
Raised when a built-in operation or function receives an argument that has the
right type but an inappropriate value
KeyboardInterrupt
Raised when the user hits the interrupt key (normally Control-C or Delete)
EOFError
Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file
condition (EOF) without reading any data
It is possible to write programs that handle selected exceptions. Look at the followi
ng example, which asks the user for input until a valid integer has been entered, bu
t allows the user to interrupt the program (using Control-C or whatever the operati
ng system supports); note that a user-generated interruption is signalled by raising
the KeyboardInterrupt exception.

>>> while True:


... try:
... x = int(input("Please enter a number: "))

Department of CSE Page 83


PYTHON

... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
The try statement works as follows.

 First, the try clause (the statement(s) between the try and except keywords)
is executed.
 If no exception occurs, the except clause is skipped and execution of
the try statement is finished.
 If an exception occurs during execution of the try clause, the rest of the clause
is skipped. Then if its type matches the exception named after the
except keyword, the except clause is executed, and then execution continues
after the try statement.
 If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler is found, it is
an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for
different exceptions. At most one handler will be executed. Handlers only handle
exceptions that occur in the corresponding try clause, not in other handlers of the
same try statement. An except clause may name multiple exceptions as a
parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):


... pass

A class in an except clause is compatible with an exception if it is the same class or a base class
thereof (but not the other way around — an except clause listing a derived class is not compatible
with a base class). For example, the following code will print B, C, D in that order:

class B(Exception):
pass

class C(B):
pass

Department of CSE Page 84


PYTHON

class D(C):
pass

for cls in [B, C, D]:


try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")

Example:

import sys

try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise

The try ... except statement has an optional else clause, which, when present, must
follow all except clauses. It is useful for code that must be executed if the try clause
does not raise an exception. For example:

for arg in sys.argv[1:]:


try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')

Department of CSE Page 85


PYTHON

f.close()

The use of the else clause is better than adding additional code to the try clause
because it avoids accidentally catching an exception that wasn’t raised by the code
being protected by the try ... except statement.

When an exception occurs, it may have an associated value, also known as the
exception’s argument. The presence and type of the argument depend on the
exception type.

Raising Exceptions

The raise statement allows the programmer to force a specified exception to occur.
For example:

>>> raise NameError('HiThere')


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere

The sole argument to raise indicates the exception to be raised. This must be either
an exception instance or an exception class (a class that derives from Exception). If
an exception class is passed, it will be implicitly instantiated by calling its constructor
with no arguments:

raise ValueError # shorthand for 'raise ValueError()'

If you need to determine whether an exception was raised but don’t intend to handle
it, a simpler form of the raise statement allows you to re-raise the exception:

>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):

Department of CSE Page 86


PYTHON

File "<stdin>", line 2, in <module>


NameError: HiThere

User-defined Exceptions

Programs may name their own exceptions by creating a new exception class.
Exceptions should typically be derived from the Exception class, either directly or
indirectly.

Exception classes can be defined which do anything any other class can do, but are
usually kept simple, often only offering a number of attributes that allow information
about the error to be extracted by handlers for the exception. When creating a
module that can raise several distinct errors, a common practice is to create a base
class for exceptions defined by that module, and subclass that to create specific
exception classes for different error conditions:

class Error(Exception):
"""Base class for exceptions in this module."""
pass

class InputError(Error):
"""Exception raised for errors in the input.

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""

def __init__(self, expression, message):


self.expression = expression
self.message = message

class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.

Attributes:
previous -- state at beginning of transition
next -- attempted new state

Department of CSE Page 87


PYTHON

message -- explanation of why the specific transition is not


allowed
"""

def __init__(self, previous, next, message):


self.previous = previous
self.next = next
self.message = message

Most exceptions are defined with names that end in “Error,” similar to the naming of
the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur
in functions they define.
Object Oriented Programming OOP in Python:
Python has been an object-oriented language since the time it existed. Due to this,
creating and using classes and objects are downright easy. This chapter helps you
become an expert in using Python's object-oriented programming support.

Overview of OOP Terminology

 Class: A user-defined prototype for an object that defines a set of attributes


that characterize any object of the class. The attributes are data members
(class variables and instance variables) and methods, accessed via dot
notation.

 Class variable: A variable that is shared by all instances of a class. Class


variables are defined within a class but outside any of the class's methods.
Class variables are not used as frequently as instance variables.

 Data member: A class variable or instance variable that holds data


associated with a class and its objects.

 Function overloading: The assignment of more than one behavior to a


particular function. The operation performed varies by the types of objects or
arguments involved.

 Instance variable: A variable that is defined inside a method and belongs


only to the current instance of a class.

 Inheritance: The transfer of the characteristics of a class to other classes


that are derived from it.

 Instance: An individual object of a certain class. An object obj that belongs


to a class Circle, for example, is an instance of the class Circle.

Department of CSE Page 88


PYTHON

 Instantiation: The creation of an instance of a class.

 Method : A special kind of function that is defined in a class definition.

 Object: A unique instance of a data structure that is defined by its class. An


object comprises both data members (class variables and instance variables)
and methods.

 Operator overloading: The assignment of more than one function to a


particular operator.

Creating Classes

The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows

class ClassName:
'Optional class documentation string'
class_suite

 The class has a documentation string, which can be accessed


viaClassName.__doc__.

 The class_suite consists of all the component statements defining class


members, data attributes and functions.

Example
Following is an example of a simple Python class

class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

Department of CSE Page 89


PYTHON

def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

 The variable empCount is a class variable whose value is shared among all
the instances of a in this class. This can be accessed as Employee.empCount
from inside the class or outside the class.
 The first method __init__() is a special method, which is called class
constructor or initialization method that Python calls when you create a new
instance of this class.
 You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to
the list for you; you do not need to include it when you call the methods.

Creating Instance Objects

To create instances of a class, you call the class using class name and pass in
whatever arguments its __init__ method accepts.
This would create first object of Employee class
emp1 = Employee("Abhinay", 2000)

This would create second object of Employee class


emp2 = Employee("Venkat", 5000)

Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would
be accessed using class name as follows

emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)

Now, putting all the concepts together-


#!/usr/bin/python3

class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):

Department of CSE Page 90


PYTHON

print ("Total Employee %d" % Employee.empCount)


def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

#This would create first object of Employee class"


emp1 = Employee("Abhinay", 2000)

#This would create second object of Employee class"


emp2 = Employee("Venkat", 5000)

emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)

When the above code is executed, it produces the following result-

Name : Abinay ,Salary: 2000


Name : Venkat ,Salary: 5000
Total Employee 2

You can add, remove, or modify attributes of classes and objects at any time

emp1.salary = 7000 # Add an 'salary' attribute.


emp1.name = 'xyz' # Modify 'name' attribute.
del emp1.salary # Delete 'salary' attribute.
Instead of using the normal statements to access attributes, you can use the
followingfunctions-

 The getattr(obj, name[, default]): to access the attribute of object.


 The hasattr(obj,name): to check if an attribute exists or not.
 The setattr(obj,name,value): to set an attribute. If attribute does not
exist, then it would be created.

 The delattr(obj, name): to delete an attribute.


hasattr(emp1, 'salary') # Returns true if 'salary' attribute exists
getattr(emp1, 'salary') # Returns value of 'salary' attribute
setattr(emp1, 'salary', 7000) # Set attribute 'salary' at 7000
delattr(emp1, 'salary') # Delete attribute 'salary'

Department of CSE Page 91


PYTHON

Built-In Class Attributes


Every Python class keeps the following built-in attributes and they can be accessed
using dot operator like any other attribute.

 __dict__: Dictionary containing the class's namespace.


 __doc__: Class documentation string or none, if undefined.
 __name__: Class name.
 __module__: Module name in which the class is defined. This attribute is
 "__main__" in interactive mode.

 __bases__: A possibly empty tuple containing the base classes, in the order
of their occurrence in the base class list.
For the above class let us try to access all these attributes-

#!/usr/bin/python3

class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print ("Total Employee %d" % Employee.empCount)

def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)

emp1 = Employee("Abhinay", 2000)


emp2 = Employee("Venkat", 5000)

print ("Employee.__doc__:", Employee.__doc__)


print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )
When the above code is executed, it produces the following result-

Department of CSE Page 92


PYTHON

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (,)
Employee.__dict__: {'displayCount': , '__module__': '__main__', '__doc__':
'Common base class for all employees', 'empCount': 2, '__init__': ,
'displayEmployee': , '__weakref__': , '__dict__': }

Class Inheritance

The child class inherits the attributes of its parent class, and you can use those
attributes as if they were defined in the child class. A child class can also override
data members and methods from the parent.

Syntax
Derived classes are declared much like their parent class; however, a list of base
classes to inherit from is given after the class name –

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite

Example
#!/usr/bin/python3

class Parent: # define parent class


parentAttr = 100
def __init__(self):
print ("Calling parent constructor")

def parentMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr

def getAttr(self):

Department of CSE Page 93


PYTHON

print ("Parent attribute :", Parent.parentAttr)

class Child(Parent): # define child class


def __init__(self):
print ("Calling child constructor")
def childMethod(self):
print ('Calling child method')

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

When the above code is executed, it produces the following result-


Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

In a similar way, you can drive a class from multiple parent classes as follows

class A: # define your class A


.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....

You can use issubclass() or isinstance() functions to check a relationship of two


classes and instances.
 The issubclass(sub, sup) boolean function returns True, if the given
subclass sub is indeed a subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns True, if obj is an
instance of Class or is an instance of a subclass of Class.

Department of CSE Page 94


PYTHON

Overriding Methods

 You can always override your parent class methods. One reason for overriding
parent's methods is that you may want special or different functionality in your
subclass.

Example

#!/usr/bin/python3

class Parent: # define parent class


def myMethod(self):
print ('Calling parent method')

class Child(Parent): # define child class


def myMethod(self):
print ('Calling child method')

c = Child() # instance of child


c.myMethod() # child calls overridden method

When the above code is executed, it produces the following result-

Calling child method

Base Overloading Methods


The following table lists some generic functionality that you can override in your own
classes-

S. No Method, Description and Sample call


1 __init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)

2 __del__( self )
Destructor, deletes an object
Sample Call : del obj

3 __repr__( self )
Evaluatable string representation
Sample Call : repr(obj)

Department of CSE Page 95


PYTHON

4 __str__( self )
Printable string representation
Sample Call : str(obj)

5 __cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators
Suppose you have created a Vector class to represent two-dimensional vectors. What
happens when you use the plus operator to add them? Most likely Python will yell at
you. You could, however, define the __add__ method in your class to perform vector
addition and then the plus operator would behave as per expectation −
Example

#!/usr/bin/python3
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

When the above code is executed, it produces the following result

Vector(7,8)

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
will not be directly visible to outsiders.
Example

Department of CSE Page 96


PYTHON

#!/usr/bin/python3

class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)

When the above code is executed, it produces the following result-

1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
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 (counter._JustCounter__secretCount)

When the above code is executed, it produces the following result


1
2
2

Internet Access/ Network Programming:

Department of CSE Page 97


PYTHON

Python provides two levels of access to the network services. At a low level, you
can access the basic socket support in the underlying operating system, which
allows you to implement clients and servers for both connection-oriented and
connectionless protocols.

Python also has libraries that provide higher-level access to specific application-
level network protocols, such as FTP, HTTP, and so on.

What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may
communicate within a process, between processes on the same machine, or
between processes on different continents.

Sockets may be implemented over a number of different channel types: Unix


domain sockets, TCP, UDP, and so on. The socket library provides specific classes
for handling the common transports as well as a generic interface for handling the
rest
Term Description
Domain The family of protocols that is used as the transport mechanism.
These
values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25,
and so on.

type The type of communications between the two endpoints, typically


SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM
for connectionless protocols.

protocol Typically zero, this may be used to identify a variant of a protocol


within a domain and type.

hostname The identifier of a network interface:


A string, which can be a host name, a dotted-quad address, or an
IPV6
address in colon (and possibly dot) notation
A string "<broadcast>", which specifies an INADDR_BROADCAST
address.
A zero-length string, which specifies INADDR_ANY, or
An Integer, interpreted as a binary address in host byte order.

port Each server listens for clients calling on one or more ports. A port
may
be a Fixnum port number, a string containing a port number, or the
name of a service.
The socket Module

Department of CSE Page 98


PYTHON

To create a socket, you must use the socket.socket() function available in the
socket module, which has the general syntax is

s= socket.socket (socket_family, socket_type, protocol=0)

Here is the description of the parameters-


 socket_family: This is either AF_UNIX or AF_INET, as explained earlier.
 socket_type: This is either SOCK_STREAM or SOCK_DGRAM.
 protocol: This is usually left out, defaulting to 0.
Once you have socket object, then you can use the required functions to create
your clientor server program. Following is the list of functions required.

Server Socket Methods


Method Description
s.bind() This method binds address (hostname, port number pair) to
socket
s.listen() This method sets up and start TCP listener.

s.accept() This passively accept TCP client connection, waiting until


connection arrives (blocking).

Client Socket Methods


Method Description

s.connect() This method actively initiates TCP server connection.

General Socket Methods


Method Description

s.recv() This method receives TCP message


s.send() This method transmits TCP message
s.recvfrom() This method receives UDP message
s.sendto() This method transmits UDP message
s.close() This method closes socket
socket.gethostname() Returns the hostname.
A Simple Server
To write Internet servers, we use the socket function available in socket module to
create a socket object. A socket object is then used to call other functions to setup
a socket server.

Department of CSE Page 99


PYTHON

Now call the bind(hostname, port) function to specify a port for your service on
the given host.
Next, call the accept method of the returned object. This method waits until a client
connects to the port you specified, and then returns a connection object that
represents the connection to that client.
#!/usr/bin/python3 # This is server.py file
import socket
# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999

# bind to the port


serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
msg='Thank you for connecting'+ "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()

A Simple Client
Let us write a very simple client program, which opens a connection to a given port
12345 and a given host. It is very simple to create a socket client using the
Python's socket module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on


the port. Once you have a socket open, you can read from it like any IO object.
When done, remember to close it, as you would close a file.

Department of CSE Page 100


PYTHON

The following code is a very simple client that connects to a given host and port,
reads any available data from the socket, and then exits-

#!/usr/bin/python3 # This is client.py file

import socket

# create a socket object


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get local machine name


host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))

# Receive no more than 1024 bytes


msg = s.recv(1024)
s.close()
print (msg.decode('ascii'))
Now run this server.py in the background and then run the above client.py to see
the result.
# Following would start a server in background.
$ python server.py &
# Once server is started run client as follows:
$ python client.py

This would produce the following result


on server terminal
Got a connection from ('192.168.1.10', 3747)
On client terminal
Thank you for connecting

Python Internet Modules


A list of some important modules in Python Network/Internet programming are
given below.
Protocol Common function Port No Python Module
HTTP Web Pages 80 Httplib,urllib,xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib

Department of CSE Page 101


PYTHON

SMTP Sending email 25 smtplib


POP3 Fetching email 110 Poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 elnetlib
Gopher Document transfers 70 gopherlib, urllib
Date & Time:

A Python program can handle date and time in several ways. Converting between
date formats is a common chore for computers. Python's time and calendar
modules help track dates and times.

What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in
time are expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python, which provides functions for
working with times, and for converting between representations. The function
time.time() returns the current system time in ticks since 12:00am, January 1,
1970(epoch).

Example
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)

What is TimeTuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown
below
Index Field Values
0 4-digit year 2016

1 Month 1 to 12

2 Day 1 to 31

3 Hour 0 to 23

4 Minute 0 to 59

5 Second 0 to 61 (60 or 61 are leap-seconds)

6 Day of Week 0 to 6 (0 is Monday)

7 Day of year 1 to 366 (Julian day)

8 Daylight savings -1, 0, 1, -1 means library determines DST

For Example-
>>>import time
>>> print (time.localtime())

Department of CSE Page 102


PYTHON

This would produce a result as follows

time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=9,


tm_min=29, tm_sec=2, tm_wday=0, tm_yday=46, tm_isdst=0)

Getting current time


To translate a time instant from seconds since the epoch floating-point value into a
timetuple, pass the floating-point value to a function (e.g., localtime) that returns a
time-tuple with all valid nine items.

#!/usr/bin/python3

import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable
form-

Local current time : time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15,


tm_hour=9, tm_min=29, tm_sec=2, tm_wday=0, tm_yday=46, tm_isdst=0)

Getting formatted time


You can format any time as per your requirement, but a simple method to get time
in a readable format is asctime() –
#!/usr/bin/python3
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)

This would produce the following result-


Local current time : Tue Feb 21 13:53:08 2017

Getting calendar for a month

The calendar module gives a wide range of methods to play with yearly and
monthly calendars. Here, we print a calendar for a given month ( Jan 2008 ).

#!/usr/bin/python3
import calendar

Department of CSE Page 103


PYTHON

cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)

This would produce the following result-


Here is the Calendar

February 2017

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

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.
S.No Function with Description
1 time.altzone
The offset of the local DST timezone, in seconds west of UTC, if one is
defined. This is negative if the local DST timezone is east of UTC (as in
Western Europe,including the UK). Use this if the daylight is nonzero.
2 time.asctime([tupletime])
Accepts a time-tuple and returns a readable 24-character string such
as 'Tue Dec11 18:07:14 2008'.
3 time.clock( )
Returns the current CPU time as a floating-point number of seconds.
To measure computational costs of different approaches, the value of
time.clock is more useful than that of time.time().
4 time.ctime([secs])
Like asctime(localtime(secs)) and without arguments is like asctime( )
5 time.gmtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a
time-tuplet with the UTC time. Note : t.tm_isdst is always 0
6 time.localtime([secs])
Accepts an instant expressed in seconds since the epoch and returns a
time-tuplet with the local time (t.tm_isdst is 0 or 1, depending on
whether DST applies toinstant secs by local rules).
7 time.mktime(tupletime)

Department of CSE Page 104


PYTHON

Accepts an instant expressed as a time-tuple in local time and returns


a floatingpoint value with the instant expressed in seconds since the
epoch.
8 time.sleep(secs)
Suspends the calling thread for secs seconds.
9 time.strftime(fmt[,tupletime])
Accepts an instant expressed as a time-tuple in local time and returns
a string representing the instant as specified by string fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Parses str according to format string fmt and returns the instant in
time-tupleformat.
11 time.time( )
Returns the current time instant, a floating-point number of seconds
since the epoch.
12 time.tzset()
Resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.

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 the calendar.setfirstweekday() function.
Here is a list of functions available with the calendar module-
S. No Function with Description
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a multiline string with a calendar for year year formatted into
three
columns separated by c spaces. w is the width in characters of each date;
eachline has length 21*w+18+2*c. l is the number of lines for each
week.
2 calendar.firstweekday( )
Returns the current setting for the weekday that starts each week. By
default,when calendar is first imported, this is 0, meaning Monday
3 calendar.isleap(year)
Returns True if year is a leap year; otherwise, False.
4 calendar.leapdays(y1,y2)
Returns the total number of leap days in the years within range(y1,y2).
5 calendar.month(year,month,w=2,l=1)
Returns a multiline string with a calendar for month month of year year,
one line per week plus two header lines. w is the width in characters of

Department of CSE Page 105


PYTHON

each date; each line has length 7*w+6. l is the number of lines for each
week.
6 calendar.monthcalendar(year,month)
Returns a list of lists of ints. Each sublist denotes a week. Days outside
month of year year are set to 0; days within the month are set to their
day-ofmonth,1 and up.
7 calendar.monthrange(year,month)
Returns two integers. The first one is the code of the weekday for the
first day of the month month in year year; the second one is the number
of days in the month. Weekday codes are 0 (Monday) to 6 (Sunday);
month numbers are 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
Like print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
Like print calendar.month(year,month,w,l).
10 calendar.setfirstweekday(weekday)
Sets the first day of each week to weekday code weekday. Weekday
codes are 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time instant in time-tuple form
and returns the same instant as a floating-point number of seconds since
the epoch.
12 calendar.weekday(year,month,day)
Returns the weekday code for the given date. Weekday codes are 0
(Monday) to 6 (Sunday); month numbers are 1 (January) to 12
(December).

GUI Programming:
Python provides various options for developing graphical user interfaces (GUIs).
The most important features 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 wxWidgets GUI


toolkit. http://wxpython.org/

 PyQt:This is also a Python interface for a popular cross-platform Qt GUI


library. TutorialsPoint has a very good tutorial on PyQt here.

 JPython: JPython is a Python port for Java, which gives Python scripts
seamless access to the Java class libraries on the local machine
http://www.jython.org.
Tkinter Programming

Department of CSE Page 106


PYTHON

Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a
powerful object-oriented interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps –

 Import the Tkinter module.


 Create the GUI application main window.
 Add one or more of the above-mentioned widgets to the GUI application.
 Enter the main event loop to take action against each event triggered by the
user.

Example

#!/usr/bin/python3
import tkinter # note that module name has changed from Tkinter in Python 2 to
tkinter in Python 3
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()

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 the buttons in your
application.
Canvas The Canvas widget is used to draw shapes, such as lines,
ovals, polygons and rectangles, in your application.
Checkbutton The Checkbutton widget is used to display a number of
options as checkboxes. The user can select multiple
options at a time.
Entry The Entry widget is used to display a single-line text field
for accepting values from a user.
Frame The Frame widget is used as a container widget to
organize other widgets.
Label The Label widget is used to provide a single-line caption
for other widgets. It can also contain images.
Listbox The Listbox widget is used to provide a list of options to
a user.
Menubutton The Menubutton widget is used to display menus in your

Department of CSE Page 107


PYTHON

application.
Menu The Menu widget is used to provide various commands
to a user. These commands are contained inside
Menubutton.
Message The Message widget is used to display multiline text fields
for accepting values from a user.
Radiobutton The Radiobutton widget is used to display a number of
options as radio buttons. The user can select only one
option at a time.
Scale The Scale widget is used to provide a slider widget.
Scrollbar The Scrollbar widget is used to add scrolling 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.
Spinbox The Spinbox widget is a variant of the standard Tkinter
Entry widget, which can be used to select from a fixed
number of values.
PanedWindow A PanedWindow is a container widget that may contain
any number of panes, arranged horizontally or vertically.
LabelFrame A labelframe is a simple container widget. Its primary
purpose is to act as a spacer or container for complex
window layouts.
TkMessageBox This module is used to display the message boxes in your
applications.

Python Multithreaded Programming

 Multiple threads within a process share the same data space with the main
thread and can therefore share information or communicate with each other
more easily than if they were separate processes.
 Threads sometimes called light-weight processes and they do not require
much memory overhead; they are cheaper than processes.

A thread has a beginning, an execution sequence, and a conclusion. It has an
instruction pointer that keeps track of where within its context it is currently running.
 It can be pre-empted (interrupted)
 It can temporarily be put on hold (also known as sleeping) while other threads
are running - this is called yielding.
Starting a New Thread
To spawn another thread, you need to call following method available
in thread module:
thread.start_new_thread ( function, args[, kwargs] )

This method call enables a fast and efficient way to create new threads in both Linux
and Windows.

Department of CSE Page 108


PYTHON

The method call returns immediately and the child thread starts and calls function
with the passed list of args. When function returns, the thread terminates.

Here, args is a tuple of arguments; use an empty tuple to call function without
passing any arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python

import thread
import time

# Define a function for the thread


def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows


try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )

except:
print "Error: unable to start thread"

while 1:
pass

When the above code is executed, it produces the following result –


Thread-1: Thu Jan 22 15:42:17 2009
Thread-1: Thu Jan 22 15:42:19 2009
Thread-2: Thu Jan 22 15:42:19 2009
Thread-1: Thu Jan 22 15:42:21 2009
Thread-2: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:23 2009
Thread-1: Thu Jan 22 15:42:25 2009
Thread-2: Thu Jan 22 15:42:27 2009
Thread-2: Thu Jan 22 15:42:31 2009
Thread-2: Thu Jan 22 15:42:35 2009

Department of CSE Page 109


PYTHON

The Threading Module:


The newer threading module included with Python 2.4 provides much more powerful,
high-level support for threads than the thread module discussed in the previous
section.
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.
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.

Multithreaded Priority Queue


The Queue module allows you to create a new queue object that can hold a specific
number of items. There are following methods to control the Queue −
 get(): The get() removes and returns an item from the queue.
 put(): The put adds item to a queue.
 qsize() : The qsize() returns the number of items that are currently in the
queue.
 empty(): The empty( ) returns True if queue is empty; otherwise, False.
 full(): the full() returns True if queue is full; otherwise, False.

Turtle Graphics
Turtle graphics is a popular way for introducing programming to kids. It was part of
the original Logo programming language developed by Wally Feurzig and Seymour
Papert in 1966.

There are many Python packages that can be used to create graphics and GUI’s. Two
graphics modules, called turtle and tkinter, come as a part of Python’s standard
library. tkinter is primarily designed for creating GUI’s. In fact, IDLE is built using
tkinter. However, we will focus on the turtle module that is primarily used as a simple
graphics package but can also be used to create simple GUI’s.

Department of CSE Page 110


PYTHON

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give
it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the
direction it is facing, drawing a line as it moves. Give it the command turtle.right(25),
and it rotates in-place 25 degrees clockwise

Importing Turtle Graphics


In order to start using turtle graphics, we need to import the turtle module. Start
Python/IDLE and type the following

>>> import turtle as t


This imports the turtle module using the identifier t. By importing the module this
way we access the methods within the module using t.

Using dir() to view the turtle module’s methods and attributes.


>>> dir(t) 2 [’Canvas’, ’Pen’, ’RawPen’, ’RawTurtle’, ’Screen’, ’ScrolledCanvas’, 3
’Shape’, ’TK’, ’TNavigator’, ’TPen’, ’Tbuffer’, ’Terminator’, 4 ’Turtle’,
’TurtleGraphicsError’, ’TurtleScreen’, ’TurtleScreenBase’, 5 ’Vec2D’, ’_CFG’,
’_LANGUAGE’, ’_Root’, ’_Screen’, ’_TurtleImage’, 6 ’__all__’, ’__builtins__’,
’__cached__’, ’__doc__’, ’__file__’, 7 ... <> 8 ’window_width’, ’write’,
’write_docstringdict’, ’xcor’, ’ycor’]
Your First Drawing
Let’s begin by telling our turtle to draw a line. Try entering the command shown in
Listing 13.4.

Listing 13.4 Drawing a line with a length of 100 units


>>> t.fd(100)

Examples
A square spiral program:

from turtle import *


for i in range(500): # this "for" loop will repeat these functions 500
times

Department of CSE Page 111


PYTHON

forward(i)
left(91)

A colorful hexagon spiral program:

from turtle import *


colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']
for x in range(360):
pencolor(colors[x % 6])
width(x / 100 + 1)
forward(x)
left(59)

Department of CSE Page 112


PYTHON

Testing in Python:

Software Testing

Software testing is the process of evaluation a software item to detect differences between
given input and expected output. Also to assess the feature of A software item. Testing
assesses the quality of the product. Software testing is a process that should be done during
the development process. In other words software testing is a verification and validation
process.

Verification

Verification is the process to make sure the product satisfies the conditions imposed at the
start of the development phase. In other words, to make sure the product behaves the way
we want it to.

Validation

Validation is the process to make sure the product satisfies the specified requirements at
the end of the development phase. In other words, to make sure the product is built as per
customer requirements.

Basics of software testing

There are two basics of software testing: blackbox testing and whitebox testing.

Department of CSE Page 113


PYTHON

Blackbox Testing

Black box testing is a testing technique that ignores the internal mechanism of the system
and focuses on the output generated against any input and execution of the system. It is
also called functional testing.

Whitebox Testing

White box testing is a testing technique that takes into account the internal mechanism of a
system. It is also called structural testing and glass box testing.

Black box testing is often used for validation and white box testing is often used for
verification.

Types of testing

There are many types of testing like

 Unit Testing
 Integration Testing
 Functional Testing
 System Testing
 Stress Testing
 Performance Testing
 Usability Testing
 Acceptance Testing
 Regression Testing
 Beta Testing

Unit Testing

Unit testing is the testing of an individual unit or group of related units. It falls under the
class of white box testing. It is often done by the programmer to test that the unit he/she
has implemented is producing expected output against given input.

Integration Testing

Integration testing is testing in which a group of components are combined to produce


output. Also, the interaction between software and hardware is tested in integration testing
if software and hardware components have any relation. It may fall under both white box
testing and black box testing.

Department of CSE Page 114


PYTHON

Functional Testing

Functional testing is the testing to ensure that the specified functionality required in the
system requirements works. It falls under the class of black box testing.

System Testing

System testing is the testing to ensure that by putting the software in different
environments (e.g., Operating Systems) it still works. System testing is done with full system
implementation and environment. It falls under the class of black box testing.

Stress Testing

Stress testing is the testing to evaluate how system behaves under unfavorable conditions.
Testing is conducted at beyond limits of the specifications. It falls under the class of black
box testing.

Performance Testing

Performance testing is the testing to assess the speed and effectiveness of the system and
to make sure it is generating results within a specified time as in performance requirements.
It falls under the class of black box testing.

Usability Testing

Usability testing is performed to the perspective of the client, to evaluate how the GUI is
user-friendly? How easily can the client learn? After learning how to use, how proficiently
can the client perform? How pleasing is it to use its design? This falls under the class of
black box testing.

Acceptance Testing

Acceptance testing is often done by the customer to ensure that the delivered product
meets the requirements and works as the customer expected. It falls under the class of black
box testing.

Regression Testing

Regression testing is the testing after modification of a system, component, or a group of


related units to ensure that the modification is working correctly and is not damaging or
imposing other modules to produce unexpected results. It falls under the class of black box
testing.

Department of CSE Page 115


PYTHON

Beta Testing

Beta testing is the testing which is done by end users, a team outside development, or
publicly releasing full pre-version of the product which is known as beta version. The aim of
beta testing is to cover unexpected errors. It falls under the class of black box testing.

Unit Testing in Python

The Python unit testing framework, sometimes referred to as “PyUnit,” is a Python


language version of JUnit, by Kent Beck and Erich Gamma in 1997for testing Java
programs. JUnit is, in turn, a Java version of Kent’s Smalltalk testing framework.
Each is the de facto standard unit testing framework for its respective language.

The goals of a 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.
o The methods under test should not ask for any input or produce
any output -- certainly no output that you need to look at. The
testing framework should tell you all you need to know.
o Logic should be separate from input/output in any case.

The standard workflow is:


1. You define your own class derived from unittest.TestCase.
2. Then you fill it with functions that start with ‘test_’.
3. You run the tests by placing unittest.main() in your file, usually at the bottom.

unittest supports test automation, sharing of setup and shutdown code for tests,
aggregation of tests into collections, and independence of the tests from the reporting
framework. The unittest module provides classes that make it easy to support these
qualities for a set of tests.

To achieve this, unittest supports some important concepts:

Department of CSE Page 116


PYTHON

test fixture
A test fixture represents the preparation needed to perform one or more tests, and
any associate cleanup actions. This may involve, for example, creating temporary
or proxy databases, directories, or starting a server process.
test case
A test case is the smallest unit of testing. It checks for a specific response to a
particular set of inputs. unittest provides a base class, TestCase, which may be
used to create new test cases.

test suite

A test suite is a collection of test cases, test suites, or both. It is used to aggregate
tests that should be executed together.
test runner
A test runner is a component which orchestrates the execution of tests and provides
the outcome to the user. The runner may use a graphical interface, a textual
interface, or return a special value to indicate the results of executing the tests.
Basic example
The unittest module provides a rich set of tools for constructing and running tests.
This section demonstrates that a small subset of the tools suffice to meet the needs
of most users.
Here is a short script to test three string methods:
import unittest

class TestStringMethods(unittest.TestCase):

def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())

def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)

if __name__ == '__main__':

Department of CSE Page 117


PYTHON

unittest.main()

A testcase is created by subclassing unittest.TestCase. The three individual tests are


defined with methods whose names start with the letters test. This naming
convention informs the test runner about which methods represent tests.

An introduction to TestCases

The basic building blocks of unit testing are 'test cases' -- single scenarios that
must be set up and checked for correctness. In PyUnit, test cases are represented
by the TestCase class in the unittest module. To make your own test cases you
must write subclasses of TestCase.

An instance of a TestCase class is an object that can completely run a single test
method, together with optional set-up and tidy-up code.

The testing code of a TestCase instance should be entirely self contained, such that
it can be run either in isolation or in arbitrary combination with any number of other
test cases.

Creating a simple test case

The simplest test case subclass will simply override the runTest method in order to
perform specific testing code:

import unittest

class DefaultWidgetSizeTestCase(unittest.TestCase):
def runTest(self):
widget = Widget("The widget")
assert widget.size() == (50,50), 'incorrect default size'

Where to place testing code

You can place the definitions of test cases and test suites in the same modules as
the code they are to test (e.g. 'widget.py'), but there are several advantages to
placing the test code in a separate module, such as 'widgettests.py':

 The test module can be run standalone from the command line
 The test code can more easily be separated from shipped code
 There is less temptation to change test code to fit the code it tests without a
good reason
 Test code should be modified much less frequently than the code it tests
 Tested code can be refactored more easily
 Tests for modules written in C must be in separate modules anyway, so why
not be consistent?

Department of CSE Page 118


PYTHON

 If the testing strategy changes, there is no need to change the source code

Running tests interactively

Of course, the whole point of writing these tests is so that we can run them and
find out if our software is working. The test framework uses 'TestRunner' classes to
provide an environment in which your tests can execute. The most common
TestRunner is TextTestRunner, which can run tests and report the results in textual
form:

runner = unittest.TextTestRunner()
runner.run(widgetTestSuite)

By default, TextTestRunner prints its output to sys.stderr, but this can be changed
by passing a different file-like object to its constructor.

Using TextTestRunner like this is an ideal way to run your tests interactively from
within a Python interpreter session.

Running tests from the command line

The unittest module contains a function called main, which can be used to easily
turn a test module into a script that will run the tests it contains. The main function
uses the unittest.TestLoader class to automatically find and load test cases within
the current module.

Therefore, if you name your test methods using the test* convention described
earlier, you can place the following code at the bottom of your test module:

if __name__ == "__main__":
unittest.main()

Then, when you execute your test module from the command line, all of the tests
contained therein will be run. Run the module with the '-h' option in order to see
the options available.

To run arbitrary tests from the command-line, you can run the unittest module as a
script, giving it the name of an test case or test suite:

% python unittest.py widgettests.WidgetTestSuite


or
% python unittest.py widgettests.makeWidgetTestSuite

Department of CSE Page 119


PYTHON

The GUI test runner

There is a graphical front end that you can use in order to run your tests. It is
written using Tkinter, the windowing toolkit shipped with Python on most platforms.
It looks similar to the JUnit GUI.

To use the GUI test runner, simply run:

% python unittestgui.py

or

% python unittestgui.py widgettests.WidgetTestSuite

Department of CSE Page 120

You might also like