Download as pdf or txt
Download as pdf or txt
You are on page 1of 136

UNIT 1

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.
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.
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable.
• 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 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
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.8.0, documentation
released on 14 October 2019 is the latest version of Python 3.
Python Features
Python's features include −

1|Page Python Programming (KNC-402)


• 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
cross-platform compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging 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.
Python is an easy to learn, powerful programming language. It has efficient high-level
data structures and a simple but effective approach to object-oriented programming.
Python’s elegant syntax and dynamic typing, together with its interpreted nature, make
it an ideal language for scripting and rapid application development in many areas on
most platforms.

2|Page Python Programming (KNC-402)


Python IDE:
Python is available at: https://www.python. org/

3|Page Python Programming (KNC-402)


On a Linux machine or a Mac you can check to see if Python 3 is installed by opening a
terminal window and typing python at the prompt. If Python is not installed, you can
download it at the python.org website.

After installing Python, you should be able to invoke Python on the command line in a
terminal window by typing the name of the program.

This opens the Python Interpreter, where you can run Python code directly in the
terminal by typing ‘python’ and hitting the Enter key:

4|Page Python Programming (KNC-402)


Interactive Mode

5|Page Python Programming (KNC-402)


When commands are read from a tty, the interpreter is said to be in interactive mode.
In this mode it prompts for the next command with the primary prompt, usually three
greater-than signs (>>>); for continuation lines it prompts with the secondary prompt,
by default three dots (...). The interpreter prints a welcome message stating its version
number and a copyright notice before printing the first prompt:

$ python3.8
Python 3.8 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more
information.
>>>

Continuation lines are needed when entering a multi-line construct. As an example,


take a look at this if statement:

>>>

>>> the_world_is_flat = True


>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!

Interacting with Python Programs:


First Python Program on shell-

>>> 4+5

Out put is-----9

----------------------------

>>> “ Hello Students”

Output is---‘Hello Students’

-------------------------------

>>>print(“Hello, Students”)

output is ---- Hello, Students

6|Page Python Programming (KNC-402)


--------------------------------------------------

name=input("Enter your name: ")

Enter your name: Sachin Tendulkar

>>> name

'Sachin Tendulkar'

>>> print(name)

Sachin Tendulkar

---------------------------------------------

Program to add two numbers


>>> a=int(input("Enter first number-:"))

Enter first number-:10

>>> b=int(input("Enter second number-:"))

Enter second number-:20

>>> c=a+b

>>> print("Sum = ", c)

Sum = 30

----------------------------------

a=input("enter first number-")

enter first number-10

>>> b=input("enter second number-")

enter second number-20

>>> c=a+b

>>> c

'1020'

7|Page Python Programming (KNC-402)


>>> print(c)

1020

----------------------------------------

Program to calculate area of circle


>>> radius=int(input("Enter the radius of circle--"))

Enter the radius of circle--10

>>> area=3.14*radius*radius

>>> print("Area of circle is--",area)

Area of circle is-- 314.0

----------------------------------------------------------------------------------

Program to calculate Simple Interest


>>> p=int(input("Enter principle Amount-"))

Enter principle Amount-1000

>>> r=float(input("Enter rate of interest--"))

Enter rate of interest--3.5

>>> t=float(input("Enter time--"))

Enter time--2

>>> SI=(p*r*t)/100

>>> print("Simple Interest =",SI)

Simple Interest = 70.0

----------------------------------------------------------------

Elements of Python:
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).

8|Page Python Programming (KNC-402)


Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, NAME and name are two
different identifiers in Python.
Here are naming conventions for Python identifiers −
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strong private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.

Reserved 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

elif is with

9|Page Python Programming (KNC-402)


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")

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
10 | P a g e Python Programming (KNC-402)
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −

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

For 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.

Or by three times double quotes (“””) or single quotes (‘’‘)

“””This is a comment.

This is a comment, too.

This is a comment, too.

11 | P a g e Python Programming (KNC-402)


I said that already.”””

‘’’This is a comment.

This is a comment, too.

This is a comment, too.

I said that already.’’’

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 –

-----------------------------------
>>> a=10
>>> a
10
>>> b=20.58
>>> b
20.58
>>> c='PYTHON'
>>> c
' PYTHON '
---------------------------------

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example –

a = b = c = 1

12 | P a g e Python Programming (KNC-402)


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.5, "Viraat"

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 "ITS" is assigned to the variable c.

Standard Data Types


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 −
1) Numbers
2) String
3) List
4) Tuple
5) Dictionary

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

a = 10
b = 20

You can also delete the reference to a number object by using the del statement. You
can delete a single object or multiple objects by using the del statement.
For example −

del a
del a, b

Python supports three different numerical types −


1) int (signed integers)
2) float (floating point real values)

3) complex (complex numbers)


All integers in Python3 are represented as long integers. Hence, there is no separate
number type as long.

Examples
Here are some examples of numbers −

13 | P a g e Python Programming (KNC-402)


int float complex

10 0.05 3.14j

100 15.20 45.j

-786 -21.9 9.322e-36j

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 to end -1.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator. For example −

str = 'Computer Science’

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 + "Engineering") # Prints concatenated string

This will produce the following result –

---------------------------------------------------

>>> str='Computer Science'


>>> print(str)
Computer Science

14 | P a g e Python Programming (KNC-402)


>>> print(str[0])
C
>>> print(str[2:5])
mpu
>>> print(str[2:])
mputer Science
>>> print(str*2)
Computer ScienceComputer Science
>>> print(str+"Engineering")
Computer ScienceEngineering

------------------------------------------------------------------------------

Python Lists
Lists are the most versatile of Python's compound data types. A list contains
items separated by commas and enclosed within square brackets ([]). To
some extent, lists are similar to arrays in C. One of the differences between
them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator. For example −

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

newlist = [123, 'john']

print (list) # Prints complete list

print (list[0]) # Prints first element of the list

print (list[1:3]) # Prints elements starting from 2nd till 3rd

print (list[2:]) # Prints elements starting from 3rd element

print (newlist * 2) # Prints list two times

print (list + newlist) # Prints concatenated lists

This produces the following result −

['abcd', 786, 2.23, 'john', 70.2]

15 | P a g e Python Programming (KNC-402)


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Add Elements to a List-


One can use the method insert, append and extend to add elements to a List.
The insert method expects an index and the value to be inserted.
>>> List.insert(0,"Yes")

Deletion in List-
>>> a=[1,2,3]
>>> a.remove(2)
>>> a
[1, 3]
>>> a=[1,2,3]
>>> del a[1]
>>> a
[1, 3]
>>> a= [1,2,3]
>>> a.pop(1)
2
>>> a
[1, 3]
>>>
• remove removes the first matching value, not a specific index:
• del removes the item at a specific index:
• and pop removes the item at a specific index and returns it.

Built-in List Functions


S.No. Function & Description

1 cmp(list1, list2)

16 | P a g e Python Programming (KNC-402)


No longer available in Python 3.

len(list)
2
Gives the total length of the list.

max(list)
3
Returns item from the list with max value.

min(list)
4
Returns item from the list with min value.

list(seq)
5
Converts a tuple into list.

S.No. Methods & Description

list.append(obj)
1
Appends object obj to list

list.count(obj)
2
Returns count of how many times obj occurs in list

list.extend(seq)
3
Appends the contents of seq to list

list.index(obj)
4
Returns the lowest index in list that obj appears

list.insert(index, obj)
5
Inserts object obj into list at offset index

6 list.pop(obj = list[-1])

17 | P a g e Python Programming (KNC-402)


Removes and returns last object or obj from list

list.remove(obj)
7
Removes object obj from list

list.reverse()
8
Reverses objects of list in place

list.sort([func])
9
Sorts objects of list, use compare func if given

Python Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just
like lists. The main difference between the tuples and the lists is that the
tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists
use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally,


you can put these comma-separated values between parentheses also.

tuple is another sequence data type that is similar to the list. A tuple consists of a
number of values separated by commas. Unlike lists, however, tuples are enclosed
within parenthesis.

The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses
( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For
example −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

newtuple = (123, 'john')

print (tuple) # Prints complete tuple

print (tuple[0]) # Prints first element of the tuple

print (tuple[1:3]) # Prints elements starting from 2nd till 3rd

18 | P a g e Python Programming (KNC-402)


print (tuple[2:]) # Prints elements starting from 3rd element

print (newtuple * 2) # Prints tuple two times

print (tuple + newtuple) # Prints concatenated tuple

This produces the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is invalid with tuple, because we attempted to update a tuple,
which is not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

tuple[2] = 1000 # Invalid syntax with tuple

list[2] = 1000 # Valid syntax with list

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong
with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in
the previous chapter.

Python Expression Results Description

len((1, 2, 3)) 3 Length

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

19 | P a g e Python Programming (KNC-402)


('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1,2,3) : print (x, end = ' ') 123 Iteration

Built-in Tuple Functions


Python includes the following tuple functions −

S.No. Function & Description

cmp(tuple1, tuple2)
1
Compares elements of both tuples.

len(tuple)
2
Gives the total length of the tuple.

max(tuple)
3
Returns item from the tuple with max value.

min(tuple)
4
Returns item from the tuple with min value.

tuple(seq)
5
Converts a list into tuple.

Python Dictionary
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary without
any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
For example −

20 | P a g e Python Programming (KNC-402)


dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

newdict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key

print (newdict) # Prints complete dictionary

print (newdict.keys()) # Prints all the keys

print (newdict.values()) # Prints all the values

This produces the following result −

This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry.

Delete Dictionary Elements


You can either remove individual dictionary elements or clear the entire contents of a
dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name'] # remove entry with key 'Name'

dict.clear() # remove all entries in dict

del dict # delete entire dictionary

print ("dict['Age']: ", dict['Age'])

print ("dict['School']: ", dict['School'])

21 | P a g e Python Programming (KNC-402)


Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either
standard objects or user-defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys –

(a) More than one entry per key is not allowed. This means no duplicate key is
allowed. When duplicate keys are encountered during assignment, the last assignment
wins. For example −

dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}

print ("dict['Name']: ", dict['Name'])

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


dict['Name']: Manni

(b) Keys must be immutable. This means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed.

Built-in Dictionary Functions and Methods


Python includes the following dictionary functions −

S.No. Function & Description

cmp(dict1, dict2)
1
No longer available in Python 3.

len(dict)
2 Gives the total length of the dictionary. This would be equal to the
number of items in the dictionary.

str(dict)
3 Produces a printable string representation of a dictionary

type(variable)
4 Returns the type of the passed variable. If passed variable is dictionary,
then it would return a dictionary type.

Python includes the following dictionary methods −

22 | P a g e Python Programming (KNC-402)


S.No. Method & Description

dict.clear()
1
Removes all elements of dictionary dict

dict.items()
2 Returns a list of dict's (key, value) tuple pairs

dict.keys()
3 Returns list of dictionary dict's keys

dict.update(dict2)
4 Adds dictionary dict2's key-values pairs to dict

dict.values()
5 Returns list of dictionary dict's values

Eval- In simple terms, the eval() method runs the python code (which is passed as an
argument) within the program.
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1

Data Type Conversion

When a description of an arithmetic operator below uses the phrase “the numeric
arguments are converted to a common type,” this means that the operator
implementation for built-in types works as follows:

• If either argument is a complex number, the other is converted to


complex;
• otherwise, if either argument is a floating point number, the other is
converted to floating point;
• otherwise, both must be integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string as a left argument to
the ‘%’ operator). Extensions must define their own conversion behavior.

23 | P a g e Python Programming (KNC-402)


Sometimes, you may need to perform conversions between the built-in types. To
convert between types, you simply use the type-names as a function.

There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.

S.No. Function & Description

int(x)
1
Converts x to an integer.

float(x)
2
Converts x to a floating-point number.

complex(real [,imag])
3
Creates a complex number.

str(x)
4
Converts object x to a string representation.

eval(str)
5
Evaluates a string and returns an object.

tuple(s)
6
Converts s to a tuple.

list(s)
7
Converts s to a list.

set(s)
8
Converts s to a set.

dict(d)
9
Creates a dictionary. d must be a sequence of (key,value) tuples.

chr(x)
10
Converts an integer to a character.

ord(x)
11
Converts a single character to its integer value.

hex(x)
12
Converts an integer to a hexadecimal string.

oct(x)
13
Converts an integer to an octal string.

Expressions
24 | P a g e Python Programming (KNC-402)
an expression in python is a block of code that produces a result or value upon
evaluation. A simple example of an expression is 6+3. An expression can be broken
doun into operators and operands. Operators are symbols which help the user or
command computer to perform mathematical or logical operations.

Operators
Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called the 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

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

Subtracts right hand operand from left


- Subtraction a – b = -11
hand operand.

Multiplies values on either side of the


* Multiplication a * b = 210
operator

Divides left hand operand by right hand


/ Division b / a = 2.1
operand

Divides left hand operand by right hand


% Modulus b%a=1
operand and returns remainder

Performs exponential (power) calculation on a**b =10 to the


** Exponent
operators power 20

Floor Division - The division of operands


where the result is the quotient in which 9//2 = 4 and
the digits after the decimal point are 9.0//2.0 = 4.0, -
//
removed. But if one of the operands is 11//3 = -4, -
negative, the result is floored, i.e., rounded 11.0//3 = -4.0
away from zero (towards negative infinity):

25 | P a g e Python Programming (KNC-402)


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) is not


==
condition becomes true. 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
> value of right operand, then condition becomes
true.
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
>= equal to the value of right operand, then condition
true.
becomes true.

If the value of left operand is less than or equal to


(a <= b) is
<= the value of right operand, then condition
true.
becomes true.

Python Assignment Operators


Assume variable a holds the value 10 and variable b holds the value 20, then

Operator Description Example

Assigns values from right side c = a + b assigns value of


=
operands to left side operand a + b into c

It adds right operand to the


c += a is equivalent to c =
+= Add AND left operand and assign the
c+a
result to left operand

It subtracts right operand


from the left operand and c -= a is equivalent to c =
-= Subtract AND
assign the result to left c-a
operand

26 | P a g e Python Programming (KNC-402)


It multiplies right operand
with the left operand and c *= a is equivalent to c =
*= Multiply AND
assign the result to left c*a
operand

It divides left operand with the c /= a is equivalent to c =


/= Divide AND right operand and assign the c / ac /= a is equivalent to
result to left operand c=c/a

It takes modulus using two


c %= a is equivalent to c
%= Modulus AND operands and assign the result
=c%a
to left operand

Performs exponential (power)


calculation on operators and c **= a is equivalent to c
**= Exponent AND
assign value to the left = c ** a
operand

It performs floor division on


c //= a is equivalent to c =
//= Floor Division operators and assign value to
c // a
the left operand

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

Python'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

Operator copies a bit, to the


(a & b) (means 0000
& Binary AND result, if it exists in both
1100)
operands

27 | P a g e Python Programming (KNC-402)


It copies a bit, if it exists in (a | b) = 61 (means
| Binary OR
either operand. 0011 1101)

It copies the bit, if it is set in (a ^ b) = 49 (means


^ Binary XOR
one operand but not both. 0011 0001)

(~a ) = -61 (means


1100 0011 in 2's
~ Binary Ones It is unary and has the effect of
complement form
Complement 'flipping' bits.
due to a signed
binary number.

The left operand's value is


moved left by the number of a << = 240 (means
<< Binary Left Shift
bits specified by the right 1111 0000)
operand.

The left operand's value is


moved right by the number of a >> = 15 (means
>> Binary Right Shift
bits specified by the right 0000 1111)
operand.

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 condition (a and b) is
AND becomes true. False.

If any of the two operands are non-zero then (a or b) is


or Logical OR
condition becomes true. True.

Used to reverse the logical state of its operand. not(a and b)


not Logical NOT
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

28 | P a g e Python Programming (KNC-402)


Evaluates to true if it finds a variable in x in y, here in results
the specified sequence and false in a 1 if x is a
In
otherwise. member of sequence
y.

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


variable in the specified sequence and results in a 1 if x is
not in
false otherwise. not a member of
sequence y.

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 in 1
Is either side of the operator point to the
if id(x) equals id(y).
same object and false otherwise.

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


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

Python Operators Precedence


The following table lists all operators from highest precedence to the lowest.

S.No. Operator & Description

**
1
Exponentiation (raise to the power)

~+-
2 Complement, unary plus and minus (method names for the last two are
+@ and -@)

* / % //
3
Multiply, divide, modulo and floor division

+-
4
Addition and subtraction

>> <<
5
Right and left bitwise shift

29 | P a g e Python Programming (KNC-402)


&
6
Bitwise 'AND'

^|
7
Bitwise exclusive `OR' and regular `OR'

<= < > >=


8
Comparison operators

<> == !=
9
Equality operators

= %= /= //= -= += *= **=
10
Assignment operators

is is not
11
Identity operators

in not in
12
Membership operators

not or and
13
Logical operators

NOTE- Exponentiation and Assignment operations are right associative.

Use of some built-in functions-

1. help()
>>> help()
Welcome to Python 3.4's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name or
summary contain a given string such as "spam", type "modules spam".
help> quit

>>>

30 | P a g e Python Programming (KNC-402)


2. id()
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.). For
example—
------------------------------
>>> a=10
>>> id(a)
1684853344
>>> id(10)
1684853344
>>>
--------------------------------------
3. chr()
Return a Unicode string of one character with ordinal i. For example—
----------------------------
>>> chr(8976)
'⌐'
>>> chr(97)
'a'
----------------------------------
4. ord()
Return the integer ordinal of a one-character string.
Given a string representing one Unicode character, return an integer representing
the Unicode code point of that character. For example, ord('a') returns the
integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr(). For
example--
---------------------------------------
>>> ord('A')
65
>>> ord('@')
64
-----------------------------

5. type()
With one argument, return the type of an object.
---------------------
>>> a=10
>>> type(a)
<class 'int'>
>>> name="ABC"
>>> type(name)
<class 'str'>
----------------------
Size of a variable-
>>> from sys import getsizeof
>>> a=10
>>> getsizeof(a)
14 bytes
31 | P a g e Python Programming (KNC-402)
>>> a = 2**1000
>>> getsizeof(a)
146 bytes

Operator Precedence

Operator precedence determines which operator is performed first in an expression with


more than one operators with different precedence.
For example: Solve

10 + 20 * 30

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left to Right or Right to Left.

For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated. For example, consider the following program, associativity of
the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The
output of the following program is in-fact compiler dependent.

Associativity of Python Operators

• We can see in the above table that more than one operator exists in the same
group. These operators have the same precedence.
• When two operators have the same precedence, associativity helps to determine
which the order of operations.
• Associativity is the order in which an expression is evaluated that has multiple
operator of the same precedence. Almost all the operators have left-to-right
associativity.
• Exponent operator ** has right-to-left associativity in Python.

32 | P a g e Python Programming (KNC-402)


How to create and save python program/files
Open IDLE(Python GUI)--shell will open.
File--→ New File
Write code in file
File--→ Save or Ctrl+S--------to save a file

File is saved in C:\python34\filename.py


How to run python program/files
In program file, go to Run-→ Check module(Will show error, if any)
Then Run-→ Run Module or press F5

How to run a saved python program/files


exec(open("C:\\python34\\aa.py").read())

33 | P a g e Python Programming (KNC-402)


NOTE-Make programs for Simple Interest calculation and area of a circle.

1.Program to calculate Simple Interest

1. P = float(input("Enter the principal amount : "))


2. N = float(input("Enter the number of years : "))
3. R = float(input("Enter the rate of interest : "))
4. SI = (P * N * R)/100
5. print("Simple interest : ,SI)

2.Program to calculate Area of circle

1. PI = 3.14
2. r = float(input('Enter the radius of the circle :'))
3. area = PI * r * r
4. print("Area of the circle is : ",area)

34 | P a g e Python Programming (KNC-402)


UNIT 2
Conditional Statement in Python

Decision Making

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


program and specified actions taken according to the conditions.
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.
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.

S.No. Statement & Description

if statements
1 An if statement consists of a boolean expression followed by one or
more statements.

if...else statements
2 An if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.

nested if statements
3 You can use one if or else if statement inside another if or else if
statement(s).

if Statement

35 | P a g e Python Programming (KNC-402)


if-else Statement

Nested if Statements (if with in if)


36 | P a g e Python Programming (KNC-402)
If-elif-else Statement

Programs based on decision making----


1. Program to check whether a given number is even or odd.
Check even / odd using modulus operator:

1. #Even Odd Program using Modulus Operator


2. a=int(input("Please Enter a Number : "));
3. if(a%2==0):
4. print("This Number is Even")
5. else:
6. print("This Number is Odd")

Check even / odd using bitwise operator:

1. #Even Odd Program using Bitwise Operator


2. a=int(input("Please Enter a Number : "));
3. if(a&1==1):
4. print("This Number is Odd")
5. else:
6. print("This Number is Even")

Check Even / Odd without using modulus or bitwise operator:

1. #Even Odd Program using Modulus Operator


2. number=int(input("Please Enter a Number : "));
3. x=int(number/2)*2;
4. if(x==number):
5. print("This Number is Even")
6. else:
7. print("This Number is Odd")

Program to find largest among two numbers.

1. num1=int(input("Enter your first number:"))


2. num2=int(input("Enter your second number: "))
3. if(num1>num2):
4. print(num1+"is greatest")
5. elif(num2>num1):
6. print(num2+ “is greatest")
7. else:
8. print(num1+ “and” num2+ “are equal")
9.
37 | P a g e Python Programming (KNC-402)
Program to find largest among three numbers.

1. num1,num2,num3=map(int,input("Enter three numbers:").split(" "))


2. if(num1>num2 and num1>num3):
3. print("{} is greatest".format(num1))
4. elif (num2>num3):
5. print("{} is greatest".format(num2))
6. else:
7. print("{} is greatest".format(num3))

Program to calculate the electricity bill as per below information-

Input Customer ID
Input Last Meter Reading(LMR)
Input Current Meter Reading(CMR)
Calculate the bill as per given unit consumption—
For first 150 units, charges are Rs. 3.0 per unit
For units >150 and <=300, charges are Rs. 4.5 per unit
For units>300 and <=500, charges are Rs. 6.0 per units
For Units >500, charges are Rs. 8.0 per unit.

units = int(input(" Please enter Number of Units you Consumed : "))


if(units <= 150):
amount = units * 3.00
elif(units <= 300):
amount = (150*3.00+(units - 150) * 4.50)
elif(units <= 500):
amount = 150*3.00 + 150*4.50 + ((units - 500) * 6.00)
else:
amount = 150*3.00 + 150*4.50 +200*6.00+ ((units - 500) * 8.00)
print("\nElectricity Bill = %.2f" %amount)

Loops
A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides the following types of loops to handle looping
requirements.

while Loop
38 | P a g e Python Programming (KNC-402)
for Loop

For loop provides a mechanism to repeat a task until a particular condition is True. It is usually
known as a determinate or definite loop because the programmer knows exactly how many
times the loop will repeat. The for...in statement is a looping statement used in Python to iterate
over a sequence of objects.

For Loop and Range() Function

The range() function is a built-in function in Python that is used to iterate over a sequence of
numbers. The syntax of range() is range(beg, end, [step])

The range() produces a sequence of numbers starting with beg (inclusive) and ending with one
less than the number end. The step argument is option (that is why it is placed in brackets). By
default, every number in the range is incremented by 1 but we can specify a different increment
using step. It can be both negative and positive, but not zero.

39 | P a g e Python Programming (KNC-402)


If range() function is given a single argument, it produces an object with values from 0 to
argument-1. For example: range(10) is equal to writing range(0, 10).

• If range() is called with two arguments, it produces values from the first to the second. For
example, range(0,10).

• If range() has three arguments then the third argument specifies the interval of the sequence
produced. In this case, the third argument must be an integer. For example, range(1,20,3).

Nested Loops

• Python allows its users to have nested loops, that is, loops that can be placed inside other
loops. Although this feature will work with any loop like while loop as well as for loop.
• A for loop can be used to control the number of times a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
• Loops should be properly indented to identify which statements are contained within
each for statement.

The Break Statement


40 | P a g e Python Programming (KNC-402)
The break statement is used to terminate the execution of the nearest enclosing loop in which it
appears. The break statement is widely used with for loop and while loop. When interpreter
encounters a break statement, the control passes to the statement that follows the loop in which the
break statement appears.

The Continue Statement

Like the break statement, the continue statement can only appear in the body of a loop. When the
compiler encounters a continue statement then the rest of the statements in the loop are skipped and
the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing
loop.

Programs based on loops----

Write a program to sum the digits of a number.


1. n=int(input("Enter a number:"))
2. tot=0
3. while(n>0):
4. dig=n%10
5. tot=tot+dig
6. n=n//10

41 | P a g e Python Programming (KNC-402)


7. print("The total sum of digits is:",tot)

Write a program to reverse a number and check whether it is palindrome or


not.
1. n=int(input("Enter number:"))
2. temp=n
3. rev=0
4. while(n>0):
5. dig=n%10
6. rev=rev*10+dig
7. n=n//10
8. if(temp==rev):
9. print("The number is a palindrome!")
10. else:
11. print("The number isn't a palindrome!")

Write a program to check whether a given number is armstrong or not.

1. num = int(input("Enter a number: "))


2.
3. sum = 0
4.
5. temp = num
6. while temp > 0:
7. digit = temp % 10
8. sum += digit ** 3
9. temp //= 10
10. if num == sum:
11. print(num,"is an Armstrong number")
12. else:
13. print(num,"is not an Armstrong number")

Write a program to calculate factorial of a given number.


n=int(input("Enter number:"))
fact=1
while(n>0):
fact=fact*n
n=n-1
print("Factorial of the number is: ")
print(fact)

Write a program to print Fibonacci series.

a=int(input("Enter the first number of the series "))


b=int(input("Enter the second number of the series "))
n=int(input("Enter the number of terms needed "))
print(a,b,end=" ")
while(n-2):
c=a+b
a=b
b=c
print(c,end=" ")

42 | P a g e Python Programming (KNC-402)


n=n-1

Write a program to find prime numbers from 1 to 100.

for Number in range (1, 101):


count = 0
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
count = count + 1
break

if (count == 0 and Number != 1):


print(" %d" %Number, end = ' ')

43 | P a g e Python Programming (KNC-402)


UNIT 3
3.1 Functions
3.2 Strings
3.3 Python Data Structure
3.4 Sieve of Eratosthenes
3.5 File I/O
3.6 Exceptions and Assertions

3.1 Functions

Functions
Python enables its programmers to break up a program into segments commonly known as functions, each
of which can be written more or less independently of the others. Every function in the program is
supposed to perform a well-defined task.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

44 | P a g e Python Programming (KNC-402)


Need for Functions
Each function to be written and tested separately.
• Understanding, coding and testing multiple separate functions is far easier.
Without the use of any function, then there will be countless lines in the code and maintaining it will be a big
mess.
• Programmers use functions without worrying about their code details. This speeds up program development,
by allowing the programmer to concentrate only on the code that he has to write.
Different programmers working on that project can divide the workload by writing different functions.
• Like Python libraries, programmers can also make their functions and use them from different point in the
main program or any other program that needs its functionalities.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Function Declaration and Definition

• A function, f that uses another function g, is known as the calling function and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

45 | P a g e Python Programming (KNC-402)


Function Definition
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed within parentheses.
• The first statement of a function can be an optional statement - the docstring describe what the function does.
• The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement.That is, the return statement is optional.
• You can assign the function name to a variable. Doing this will allow you to call same function using the name
of that variable. Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Function Call
The function call statement invokes the function. When a function is invoked the program control jumps to
the called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
A function can take parameters which are nothing but some values that are passed to it so that the function
can manipulate them to produce the desired result. These parameters are normal variables with a small
difference that the values of these variables are defined (initialized) when we call the function and are then
passed to the function.
Function name and the number and type of arguments in the function call must be same as that given in the
function definition.
If the data type of the argument passed does not matches with that expected in function then an error is
generated. Example: 6

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

46 | P a g e Python Programming (KNC-402)


Examples

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Local and Global Variables

A variable which is defined within a function is local to that function. A local variable can be accessed from
the point of its definition until the end of the function in which it is defined. It exists as long as the function is
executing. Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside a function, a new local variable is created.

Global variables are those variables which are defined in the main body of the program file. They are visible
throughout the program file. As a good programming habit, you must try to avoid the use of global variables
because they may get altered by mistake and then result in erroneous output.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

47 | P a g e Python Programming (KNC-402)


Local and Global Variables
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Using the Global Statement


To define a variable defined inside a function as global, you must use the global statement. This declares the
local or the inner variable of the function to have module scope.

Example:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

48 | P a g e Python Programming (KNC-402)


Resolution of names
Scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope is that
particular block. If it is defined in a function, then its scope is all blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest enclosing scope. If no variable of
that name is found, then a NameError is raised. In the code given below, str is a global string because it has
been defined before calling the function.

Example:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

The Return Statement


The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is present, it is evaluated and the
resultant value is returned to the calling function. However, if no expression is specified then the function will
return None. Example:

The return statement is used for two things.


• Return a value to the caller
• To end and exit a function and go back to its caller

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

49 | P a g e Python Programming (KNC-402)


Required Arguments

In the required arguments, the arguments are passed to a function in correct positional order. Also, the number
of arguments in the function call should exactly match with the number of arguments specified in the
function definition

Examples:

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Keyword Arguments

When we call a function with some values, the values are assigned to the arguments based on their position.
Python also allow functions to be called using keyword arguments in which the order (or position) of the
arguments can be changed. The values are not assigned to arguments according to their position but based
on their name (or keyword).
Keyword arguments are beneficial in two cases.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

50 | P a g e Python Programming (KNC-402)


Default Arguments
Python allows users to specify function arguments that can have default values.This means that a function can be
called with fewer arguments than it is defined to have.That is, if the function accepts three parameters, but function
call provides only two arguments, then the third parameter will be assigned the default (already specified) value.
The default value to an argument is provided by using the assignment operator (=). Users can specify a
default value for one or more arguments.

Example:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

51 | P a g e Python Programming (KNC-402)


Lambda Functions Or Anonymous Functions
Lambda or anonymous functions are so called because they are not declared as other functions using the def
keyword. Rather, they are created using the lambda keyword. Lambda functions are throw-away functions,
i.e. they are just needed where they have been created and can be used anywhere a function is required. The
lambda feature was added to Python due to the demand from LISP programmers.
Lambda functions contain only a single line. Its syntax can be given as,

Example:

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

52 | P a g e Python Programming (KNC-402)


Strings
Python treats strings as contiguous series of characters delimited by single, double or even triple quotes.
Python has a built-in string class named "str" that has many useful features. We can simultaneously declare
and define a string by creating a variable of string type.This can be done in several ways which are as follows:
name = "India" graduate = 'N' country = name nationality = str("Indian")

Indexing: Individual characters in a string are accessed using the subscript ([ ]) operator. The expression in
brackets is called an index. The index specifies a member of an ordered set and in this case it specifies the
character we want to access from the given set of characters in the string.
The index of the first character is 0 and that of the last character is n-1 where n is the number of characters
in the string. If you try to exceed the bounds (below 0 or above n-1), then an error is raised.
2

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Strings
Traversing a String: A string can be traversed by accessing character(s) from one index to another. For
example, the following program uses indexing to traverse a string from first character to the last.

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

53 | P a g e Python Programming (KNC-402)


Concatenating, Appending and Multiplying Strings
Examples:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Strings are Immutable


Python strings are immutable which means that once created they cannot be changed. Whenever you try to
modify an existing string variable, a new string is created.
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

54 | P a g e Python Programming (KNC-402)


String Formatting Operator
The % operator takes a format string on the left (that has %d, %s, etc) and the corresponding values in a tuple
(will be discussed in subsequent chapter) on the right. The format operator, % allow users to construct strings,
replacing parts of the strings with the data stored in variables. The syntax for the string formatting operation
is:
"<Format>" % (<Values>)
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

55 | P a g e Python Programming (KNC-402)


Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in String Methods and Functions

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

56 | P a g e Python Programming (KNC-402)


Slice Operation
A substring of a string is called a slice. The slice operation is used to refer to sub-parts of sequences and
strings.You can take subset of string from original string by using [ ] operator also known as slicing operator.

Examples:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Specifying Stride while Slicing Strings


In the slice operation, you can specify a third argument as the stride, which refers to the number of characters
to move forward after the first character is retrieved from the string. By default the value of stride is 1, so in
all the above examples where he had not specified the stride, it used the value of 1 which means that every
character between two index numbers is retrieved.

Examples:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

57 | P a g e Python Programming (KNC-402)


ord() and chr() Functions
ord() function returns the ASCII code of the character and chr() function returns character represented by
a ASCII number. Examples:

in and not in Operators


in and not in operators can be used with strings to determine whether a string is present in another string.
Therefore, the in and not in operator are also known as membership operators.

Examples:

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Comparing Strings

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

58 | P a g e Python Programming (KNC-402)


Iterating String
String is a sequence type (sequence of characters).You can iterate through the string using for loop.

Examples:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

59 | P a g e Python Programming (KNC-402)


The String Module
The string module consist of a number of useful constants, classes and functions (some of which are
deprecated).These functions are used to manipulate strings.
Examples:

15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

60 | P a g e Python Programming (KNC-402)


Data Structure: Sequence
A data structure is a group of data elements that are put together under one name. Data structure defines a
particular way of storing and organizing data in a computer so that it can be used efficiently.
Sequence is the most basic data structure in Python. In sequence, each element has a specific index. This
index value starts from zero and is automatically incremented for the next element. In Python, sequence is
the generic term for an ordered set. For example, we have already studied strings which are a sequence of
characters.
Python has some basic built-in functions that help programmers to manipulate elements that form a part
of a sequence.These functions include finding the length of a sequence, finding the largest and smallest
elements in a sequence, etc. Other operations that can be performed on a sequence include indexing, slicing,
adding, multiplying, and checking for membership.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Lists
List is a versatile data type available in Python. It is a sequence in which elements are written as a list of
comma-separated values (items) between square brackets. The key feature of a list is that it can have
elements that belong to different data types.The syntax of defining a list can be given as,
List_variable = [val1, val2,...]

Examples:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

61 | P a g e Python Programming (KNC-402)


Access Values in Lists

Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are used
to slice along with the index or indices to get value stored at that index. The syntax for the slice operation is
given as, seq = List[start:stop:step]
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Updating Values in Lists


Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand side of
the assignment operator. You can also append new values in the list and remove existing value(s) from the list
using the append() method and del statement respectively.
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

62 | P a g e Python Programming (KNC-402)


Nested Lists
Nested list means a list within another list. We have already said that a list has elements of different data
types which can include even a list.

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Cloning Lists
If you want to modify a list and also keep a copy of the original list, then you should create a separate copy
of the list (not just the reference).This process is called cloning.The slice operation is used to clone a list.

Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

63 | P a g e Python Programming (KNC-402)


Basic List Operations

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

List Methods

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

64 | P a g e Python Programming (KNC-402)


List Comprehensions
Python also supports computed lists called list comprehensions having the following syntax.
List = [expression for variable in sequence]
Where, the expression is evaluated once, for every item in the sequence.
List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new
lists where each element is the obtained by applying some operations to each member of another sequence
or iterable. List comprehension is also used to create a subsequence of those elements that satisfy a certain
condition.
Example:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Looping in Lists
Python's for and in constructs are extremely useful especially when working with lists. The for var in list
statement is an easy way to access each element in a list (or any other sequence). For example, in the
following code, the for loop is used to access each item in the list.
for i in list: Example:
print(i)

15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

65 | P a g e Python Programming (KNC-402)


Using the enumerate() and range() Functions
enumerate() function is used when you want to print both index as well as an item in the list. The function
returns an enumerate object which contains the index and value of all the items of the list as a tuple.
The range() function is used when you need to print index.

Examples:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Using an Iterator
You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements
of the list. For this, the iterator fetches the value and then automatically points to the next element in the
list when it is used with the next() method.
Example:

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

66 | P a g e Python Programming (KNC-402)


Tuple
Like lists, tuple is another data structure supported by Python. It is very similar to lists but differs in two
things.
• First, a tuple is a sequence of immutable objects. This means that while you can change the value of one or
more items in a list, you cannot change the values in a tuple.
• Second, tuples use parentheses to define its elements whereas lists use square brackets.
Creating Tuple
Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need
to just put the different comma-separated values within a parentheses as shown below.
Tup1 = (val 1, val 2,...)
where val (or values) can be an integer, a floating number, a character, or a string.
21

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Utility of Tuples
In real-world applications, tuples are extremely useful for representing records or structures as we call
in other programming languages.These structures store related information about a subject together.
The information belongs to different data types.
For example, a tuple that stores information about a student can have elements like roll_no, name, course,
total marks, avg, etc. Some built-in functions return a tuple. For example, the divmod() function returns two
values—quotient as well as the remainder after performing the divide operation.
Examples:

22

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

67 | P a g e Python Programming (KNC-402)


Accessing Values in a Tuple
Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0.You can even perform
operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is
used along with the index or indices to obtain value stored at that index

Example:

23

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Deleting Elements in Tuple


Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course, you can create a
new tuple that has all elements in your tuple except the ones you don't want (those you wanted to be
deleted).

Examples:

24

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

68 | P a g e Python Programming (KNC-402)


Basic Tuple Operations

25

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Tuple Assignment
Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the
assignment operator to be assigned values from a tuple given on the right side of the assignment operator.
Each value is assigned to its respective variable. In case, an expression is specified on the right side of the
assignment operator, first that expression is evaluated and then assignment is done.

Example:

26

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

69 | P a g e Python Programming (KNC-402)


Tuples for Returning Multiple Values and Nested Tuples
Examples:

27

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Checking the Index: index() method


The index of an element in the tuple can be obtained by using the index() method. If the element being
searched is not present in the list, then error is generated. The syntax of index() is given as, list.index(obj)
where, obj is the object to be found out.

Examples:

28

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

70 | P a g e Python Programming (KNC-402)


count()Method and List Comprehension and Tuples

Examples:

29

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Advantages of Tuple over List

• Tuples are used to store values of different data types. Lists can however, store data of similar data types.
• Since tuples are immutable, iterating through tuples is faster than iterating over a list.This means that a
tuple performs better than a list.
• Tuples can be used as key for a dictionary but lists cannot be used as keys.
• Tuples are best suited for storing data that is write-protected.
• Tuples can be used in place of lists where the number of values is known and small.
• If you are passing a tuple as an argument to a function, then the potential for unexpected behavior due to
aliasing gets reduced.
• Multiple values from a function can be returned using a tuple.
• Tuples are used to format strings.
32

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

71 | P a g e Python Programming (KNC-402)


Sets

Sets is another data structure supported by Python. Basically, sets are same as lists but with a difference that
sets are lists with no duplicate entries.Technically, a set is a mutable and an unordered collection of items.This
means that we can easily add or remove items from it.
A set is created by placing all the elements inside curly brackets {}, separated by comma or by using the
built-in function set().The syntax of creating a set can be given as,

Example:To create a set, you can write,

33

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Set Operations

34

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

72 | P a g e Python Programming (KNC-402)


Set Operations

35

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Set Operations

36

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

73 | P a g e Python Programming (KNC-402)


Set Operations

37

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Dictionaries
Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated from its
value by a colon (:), and consecutive items are separated by commas.The entire items in a dictionary are
enclosed in curly brackets({}).The syntax for defining a dictionary is
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line
to make the code easier to read and understand.This is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}

Example:

38

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

74 | P a g e Python Programming (KNC-402)


Accessing Values

Example:

39

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Adding and Modifying an Item in a Dictionary

Example:

40

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

75 | P a g e Python Programming (KNC-402)


Modifying an Entry
Example:

41

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Deleting Items
You can delete one or more items using the del keyword. To delete or remove all the items in just one
statement, use the clear() function. Finally, to remove an entire dictionary from the memory, we can gain
use the del statement as del Dict_name.The syntax to use the del statement can be given as,
del dictionary_variable[key]
Example:

42

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

76 | P a g e Python Programming (KNC-402)


Sorting Items and Looping over Items in a Dictinonary
Examples:

43

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Nested Dictionaries

Example:

44

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

77 | P a g e Python Programming (KNC-402)


Built-in Dictionary Functions and Methods

45

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Built-in Dictionary Functions and Methods

46

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

78 | P a g e Python Programming (KNC-402)


Built-in Dictionary Functions and Methods

47

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Difference between a List and a Dictionary


First, a list is an ordered set of items. But, a dictionary is a data structure that is used for matching one item
(key) with another (value).
• Second, in lists, you can use indexing to access a particular item. But, these indexes should be a number. In
dictionaries, you can use any type (immutable) of value as an index. For example, when we write Dict['Name'],
Name acts as an index but it is not a number but a string.
• Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another
value. For this reason, dictionary is also known as a lookup table.
Fourth, the key-value pair may not be displayed in the order in which it was specified while defining the
dictionary. This is because Python uses complex algorithms (called hashing) to provide fast access to the items
stored in the dictionary.This also makes dictionary preferable to use over a list of tuples.
48

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

79 | P a g e Python Programming (KNC-402)


String Formatting with Dictionaries

Python also allows you to use string formatting feature with dictionaries. So you can use %s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.

Example: Program that uses string formatting feature to print the key-value pairs stored in the dictionary

49

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

When to use which Data Structure?


• Use lists to store a collection of data that does not need random access.
• Use lists if the data has to be modified frequently.
• Use a set if you want to ensure that every element in the data structure must be unique.
• Use tuples when you want that your data should not be altered.

50

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

80 | P a g e Python Programming (KNC-402)


3.4 Sieve of Eratosthenes

The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n
is smaller than 10 million or so Given a number n, print all primes smaller than or equal to n. It is
also given that n is a small number.

For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7,
11, 13, 17, 19”

def prime_eratosthenes(n):
prime_list = []
for i in range(2, n+1):
if i not in prime_list:
print (i)
for j in range(i*i, n+1, i):
prime_list.append(j)

print(prime_eratosthenes(100))';

81 | P a g e Python Programming (KNC-402)


3.5 Python File I/O

What is a file?

File is a named location on disk to store related information. It is used to permanently store data in a
non-volatile memory (e.g. hard disk).

Since, random access memory (RAM) is volatile which loses its data when computer is turned off,
we use files for future use of the data.

When we want to read from or write to a file we need to open it first. When we are done, it needs to
be closed, so that resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order.


1. Open a file
2. Read or write (perform operation)
3. Close the file

How to open a file?


82 | P a g e Python Programming (KNC-402)
Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read or modify the file accordingly.

1. >>> f = open("test.txt") # open file in current directory


2. >>> f = open("C:/Python33/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary
mode.

The default is reading in text mode. In this mode, we get strings when reading from the file.

On the other hand, binary mode returns bytes and this is the mode to be used when dealing with
non-text files like image or exe files.

Mode Description

'r' Open a file for reading. (default)

'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

'x' Open a file for exclusive creation. If the file already exists, the operation fails.

'a' Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.

't' Open in text mode. (default)

'b' Open in binary mode.

'+' Open a file for updating (reading and writing)

Python File Modes

1. f = open("test.txt") # equivalent to 'r' or 'rt'


2. f = open("test.txt",'w') # write in text mode
3. f = open("img.bmp",'r+b') # read and write in binary mode

Unlike other languages, the character 'a' does not imply the number 97 until it is encoded
using ASCII (or other equivalent encodings).
83 | P a g e Python Programming (KNC-402)
Moreover, the default encoding is platform dependent. In windows, it is 'cp1252' but 'utf-8' in
Linux.

So, we must not also rely on the default encoding or else our code will behave differently in different
platforms.

Hence, when working with files in text mode, it is highly recommended to specify the encoding type.

1. f = open("test.txt",mode = 'r',encoding = 'utf-8')

How to close a file Using Python?

When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.

Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close
the file.
1. f = open("test.txt",encoding = 'utf-8')
2. # perform file operations
3. f.close()

This method is not entirely safe. If an exception occurs when we are performing some operation with
the file, the code exits without closing the file.
A safer way is to use a try...finally block.
1. try:
2. f = open("test.txt",encoding = 'utf-8')
3. # perform file operations
4. finally:
5. f.close()

This way, we are guaranteed that the file is properly closed even if an exception is raised, causing
program flow to stop.

The best way to do this is using the with statement. This ensures that the file is closed when the
block inside with is exited.

We don't need to explicitly call the close() method. It is done internally.

1. with open("test.txt",encoding = 'utf-8') as f:


2. # perform file operations

84 | P a g e Python Programming (KNC-402)


How to write to File Using Python?

In order to write into a file in Python, we need to open it in write 'w', append 'a' or exclusive
creation 'x' mode.
We need to be careful with the 'w' mode as it will overwrite into the file if it already exists. All
previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method
returns the number of characters written to the file.
1. with open("test.txt",'w',encoding = 'utf-8') as f:
2. f.write("my first file\n")
3. f.write("This file\n\n")
4. f.write("contains three lines\n")
This program will create a new file named 'test.txt' if it does not exist. If it does exist, it is
overwritten.

We must include the newline characters ourselves to distinguish different lines.

How to read files in Python?

To read a file in Python, we must open the file in reading mode.

There are various methods available for this purpose. We can use the read(size) method to read
in size number of data. If size parameter is not specified, it reads and returns up to the end of the
file.
1. >>> f = open("test.txt",'r',encoding = 'utf-8')
2. >>> f.read(4) # read the first 4 data
3. 'This'
4.
5. >>> f.read(4) # read the next 4 data
6. ' is '
7.
8. >>> f.read() # read in the rest till end of file
9. 'my first file\nThis file\ncontains three lines\n'
10.
11. >>> f.read() # further reading returns empty sting
12. ''

We can see that, the read() method returns newline as '\n'. Once the end of file is reached, we
get empty string on further reading.
We can change our current file cursor (position) using the seek() method. Similarly,
the tell() method returns our current position (in number of bytes).

1. >>> f.tell() # get the current file position


2. 56
85 | P a g e Python Programming (KNC-402)
3.
4. >>> f.seek(0) # bring file cursor to initial position
5. 0
6.
7. >>> print(f.read()) # read the entire file
8. This is my first file
9. This file
10. contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

1. >>> for line in f:


2. ... print(line, end = '')
3. ...
4. This is my first file
5. This file
6. contains three lines

The lines in file itself has a newline character '\n'.


Moreover, the print() end parameter to avoid two newlines when printing.
Alternately, we can use readline() method to read individual lines of a file. This method reads a
file till the newline, including the newline character.

1. >>> f.readline()
2. 'This is my first file\n'
3.
4. >>> f.readline()
5. 'This file\n'
6.
7. >>> f.readline()
8. 'contains three lines\n'
9.
10. >>> f.readline()
11. ''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
method return empty values when end of file (EOF) is reached.

1. >>> f.readlines()
2. ['This is my first file\n', 'This file\n', 'contains three lines\n']

Python File Methods

There are various methods available with the file object. Some of them have been used in above
examples.
Here is the complete list of methods in text mode with a brief description.
86 | P a g e Python Programming (KNC-402)
Method Description

close() Close an open file. It has no effect if the file is already closed.

Separate the underlying binary buffer from the TextIOBase and return
detach() it.

fileno() Return an integer number (file descriptor) of the file.

flush() Flush the write buffer of the file stream.

isatty() Return True if the file stream is interactive.

Read atmost n characters form the file. Reads till end of file if it is
read(n) negative or None.

readable() Returns True if the file stream can be read from.

Read and return one line from the file. Reads in at most n bytes if
readline(n=-1) specified.

Read and return a list of lines from the file. Reads in at


readlines(n=-1) most n bytes/characters if specified.

Change the file position to offset bytes, in reference to from (start,


seek(offset,from=SEEK_SET) current, end).

seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

Resize the file stream to size bytes. If size is not specified, resize to
truncate(size=None) current location.

writable() Returns True if the file stream can be written to.

write(s) Write string s to the file and return the number of characters written.

writelines(lines) Write a list of lines to the file.

87 | P a g e Python Programming (KNC-402)


3.6 Exceptions & Assertions

Errors and Exceptions


The programs that we write may behave abnormally or unexpectedly because of some errors and/or
exceptions. The two common types of errors that we very often encounter are syntax errors and logic errors.
While logic errors occur due to poor understanding of problem and its solution, syntax errors, on the other
hand, arises due to poor understanding of the language. However, such errors can be detected by exhaustive
debugging and testing of procedures.
But many a times, we come across some peculiar problems which are often categorized as exceptions.
Exceptions are run-time anomalies or unusual conditions (such as divide by zero, accessing arrays out of its
bounds, running out of memory or disk space, overflow, and underflow) that a program may encounter during
execution. Like errors, exceptions can also be categorized as synchronous and asynchronous exceptions.While
synchronous exceptions (like divide by zero, array index out of bound, etc.) can be controlled by the program,
asynchronous exceptions (like an interrupt from the keyboard, hardware malfunction, or disk failure), on the
2

other hand, are caused by events that are beyond the control of the program.
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Syntax and Logic Errors


Syntax errors occurs when we violate the rules of Python and they are the most common kind of error that we
get while learning a new language. For example, consider the lines of code given below.
>>> i=0
>>> if i == 0 print(i)
SyntaxError: invalid syntax

Logic error specifies all those type of errors in which the program executes but gives incorrect results. Logical
error may occur due to wrong algorithm or logic to solve a particular program. In some cases, logic errors
may lead to divide by zero or accessing an item in a list where the index of the item is outside the bounds of
the list. In this case, the logic error leads to a run-time error that causes the program to terminate abruptly.
These types of run-time errors are known as exceptions. 3

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

88 | P a g e Python Programming (KNC-402)


Exceptions
Even if a statement is syntactically correct, it may still cause an error when executed. Such errors that occur
at run-time (or during execution) are known as exceptions. An exception is an event, which occurs during
the execution of a program and disrupts the normal flow of the program's instructions.When a program
encounters a situation which it cannot deal with, it raises an exception. Therefore, we can say that an
exception is a Python object that represents an error.
When a program raises an exception, it must handle the exception or the program will be immediately
terminated.You can handle exceptions in your programs to end it gracefully, otherwise, if exceptions are not
handled by programs, then error messages are generated..

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Handling Exceptions
We can handle exceptions in our program by using try block and except block. A critical operation which can
raise exception is placed inside the try block and the code that handles exception is written in except block. The
syntax for try–except block can be given as,
Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

89 | P a g e Python Programming (KNC-402)


Multiple Except Blocks
Python allows you to have multiple except blocks for a single try block. The block which matches with
the exception generated will get executed. A try block can be associated with more than one except
block to specify handlers for different exceptions. However, only one handler will be executed. Exception
handlers only handle exceptions that occur in the corresponding try block. We can write our programs
that handle selected exceptions. The syntax for specifying multiple except blocks for a single try block
can be given as, Example:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Multiple Exceptions in a Single Block — Example

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

90 | P a g e Python Programming (KNC-402)


except: Block without Exception
You can even specify an except block without mentioning any exception (i.e., except:). This type of except
block if present should be the last one that can serve as a wildcard (when multiple except blocks are
present). But use it with extreme caution, since it may mask a real programming error.
In large software programs, may a times, it is difficult to anticipate all types of possible exceptional
conditions.Therefore, the programmer may not be able to write a different handler (except block) for every
individual type of exception. In such situations, a better idea is to write a handler that would catch all types
of exceptions.The syntax to define a handler that would catch every possible exception from the try block is,

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Except Block Without Exception — Example

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

91 | P a g e Python Programming (KNC-402)


The Else Clause
The try ... except block can optionally have an else clause, which, when present, must follow all except blocks.
The statement(s) in the else block is executed only if the try clause does not raise an exception.
Examples:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Raising Exceptions
You can deliberately raise an exception using the raise keyword.The general syntax for the raise statement is,
raise [Exception [, args [, traceback]]]
Here, Exception is the name of exception to be raised (example, TypeError). args is optional and specifies a
value for the exception argument. If args is not specified, then the exception argument is None.The final
argument, traceback, is also optional and if present, is the traceback object used for the exception.

Example:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

92 | P a g e Python Programming (KNC-402)


Instantiating Exceptions
Python allows programmers to instantiate an exception first before raising it and add any attributes (or
arguments) to it as desired. These attributes can be used to give additional information about the error. To
instantiate the exception, the except block may specify a variable after the exception name. The variable
then becomes an exception instance with the arguments stored in instance.args. The exception instance also
has the __str__() method defined so that the arguments can be printed directly without using instance.args.

Example:

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Handling Exceptions In Invoked Functions

Example:

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

93 | P a g e Python Programming (KNC-402)


Built-in and User-defined Exceptions

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

The finally Block


The try block has another optional block called finally which is used to define clean-up actions that must be
executed under all circumstances.The finally block is always executed before leaving the try block.This means
that the statements written in finally block are executed irrespective of whether an exception has occurred or
not.The syntax of finally block can be given as, Example:
try:
Write your operations here
......................
Due to any exception, operations written here will be skipped
finally:
This would always be executed.
...................... 15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

94 | P a g e Python Programming (KNC-402)


Pre-defined Clean–up Action
In Python, some objects define standard clean-up actions that are automatically performed when the object
is no longer needed. The default clean-up action is performed irrespective of whether the operation using the
object succeeded or failed.We have already seen such an operation in file handling.We preferred to open
the file using with keyword so that the file is automatically closed when not in use. So, even if we forget to
close the file or the code to close it is skipped because of an exception, the file will still be closed.
Example:

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

Re-raising Exception
Python allows programmers to re-raise an exception. For example, an exception thrown from the try block
can be handled as well as re-raised in the except block using the keyword raise.The code given below
illustrates this concept.
Example: Program to re-raise the exception

17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

95 | P a g e Python Programming (KNC-402)


Assertions in Python
An assertion is a basic check that can be turned on or off when the program is being tested.You can think of assert as a
raise-if statement (or a raise-if-not statement). Using the assert statement, an expression is tested, and if the result of the
expression is False then an exception is raised.The assert statement is intended for debugging statements. It can be seen as
an abbreviated notation for a conditional raise statement.
In Python, assertions are implemented using assert keyword. Assertions are usually placed at the start of a function to
check for valid input, and after a function call to check for valid output.
When Python encounters an assert statement, the expression associated with it is calculated and if the
expression is False, an AssertionError is raised.The syntax for assert statement is,
assert expression[, arguments]
If the expression is False (also known as assertion fails), Python uses ArgumentExpression as the argument for the
AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except block.
However, if the AssertionError is not handled by the program, the program will be terminated and an error message will
18
be displayed. In simple words, the assert statement, is semantically equivalent to writing,
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
assert <expression>, <message>

Assertions In Python — Example

19

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

96 | P a g e Python Programming (KNC-402)


UNIT 4
Module
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
named aname.py. Here's an example of a simple module, support.py

def print_func( par ):


print "Hello : ", par
return

Importing modules

The import Statement

97 | P a g e Python Programming (KNC-402)


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 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
support.py, you need to put the following command at the top of the script −

#!/usr/bin/python

# 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 over and over again 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 −
from fib import fibonacci
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 names from a module into the current namespace by
using the following import statement −
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.

98 | P a g e Python Programming (KNC-402)


Abstract Data Types

Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by
a set of value and a set of operations.
The definition of ADT only mentions what operations are to be performed but not how
these operations will be implemented. It does not specify how data will be organized in
memory and what algorithms will be used for implementing the operations. It is called
“abstract” because it gives an implementation-independent view. The process of
providing only the essentials and hiding the details is known as abstraction.

Python Classes and Methods

Python is an “object-oriented programming language.” This means that almost all the
code is implemented using a special construct called classes. Programmers use classes
to keep related things together. This is done using the keyword “class,” which is a
grouping of object-oriented constructs.

By the end of this tutorial you will be able to:

1. Define what is a class


2. Describe how to create a class
3. Define what is a method
4. Describe how to do object instantiation
5. Describe how to create instance attributes in Python

What is a class?

A class is a code template for creating objects. Objects have member variables and
have behavior (methods) associated with them. In python a class is created by the
keyword class.
99 | P a g e Python Programming (KNC-402)
An object is created using the constructor of the class. This object will then be called
the instance of the class. In Python we create instances in the following manner

Instance = class(arguments)

How to create a class

The simplest class can be created using the class keyword. For example, let's create a
simple, empty class with no functionalities.

>>> class Snake:


... pass
...
>>> snake = Snake()
>>> print(snake)
<__main__.Snake object at 0x7f315c573550>

Attributes and Methods in class:

A class by itself is of no use unless there is some functionality associated with it.
Functionalities are defined by setting attributes, which act as containers for data and
functions related to those attributes. Those functions are called methods.

Attributes:

You can define the following class with the name Snake. This class will have an
attribute name.

>>> class Snake:


... name = "python" # set an attribute `name` of the class
...

You can assign the class to a variable. This is called object instantiation. You will then
be able to access the attributes that are present inside the class using the
dot . operator. For example, in the Snake example, you can access the
attribute name of the class Snake.

>>> # instantiate the class Snake and assign it to variable snake


>>> snake = Snake()

>>> # access the class attribute name inside the class Snake.
>>> print(snake.name)
python

100 | P a g e Python Programming (KNC-402)


Methods

Once there are attributes that “belong” to the class, you can define functions that will
access the class attribute. These functions are called methods. When you define
methods, you will need to always provide the first argument to the method with a self
keyword.

For example, you can define a class Snake, which has one attribute name and one
method change_name. The method change name will take in an
argument new_name along with the keyword self.

>>> class Snake:


... name = "python"
...
... def change_name(self, new_name): # note that the first argument is self
... self.name = new_name # access the class attribute with the self keyword
...

Now, you can instantiate this class Snake with a variable snake and then change the
name with the method change_name.

>>> # instantiate the class


>>> snake = Snake()

>>> # print the current object name


>>> print(snake.name)
python

>>> # change the name using the change_name method


>>> snake.change_name("anaconda")
>>> print(snake.name)
anaconda

Instance attributes in python and the init method

You can also provide the values for the attributes at runtime. This is done by defining
the attributes inside the init method. The following example illustrates this.

class Snake:

def __init__(self, name):


self.name = name

def change_name(self, new_name):


self.name = new_name

101 | P a g e Python Programming (KNC-402)


Now you can directly define separate attribute values for separate objects. For
example,

>>> # two variables are instantiated


>>> python = Snake("python")
>>> anaconda = Snake("anaconda")

>>> # print the names of the two variables


>>> print(python.name)
python
>>> print(anaconda.name)
anaconda

Special Methods

All the built-in data types implement a collection of special object methods. The names
of special methods are always preceded and followed by double underscores (__).

These methods are automatically triggered by the interpreter as a program executes.


For example, the operation x + y is mapped to an internal method, x.__add__(y), and
an indexing operation, x[k], is mapped to x.__getitem__(k). The behavior of each data
type depends entirely on the set of special methods that it implements.

User-defined classes can define new objects that behave like the built-in types simply
by supplying an appropriate subset of the special methods described in this section. In
addition, built-in types such as lists and dictionaries can be specialized (via inheritance)
by redefining some of the special methods.

Object Creation, Destruction, and Representation

The methods in Table 3.9 create, initialize, destroy, and represent objects.

__new__() is a static method that is called to create an instance (although this


method is rarely redefined).
The __init__() method initializes the attributes of an object and is called immediately
after an object has been newly created.

The __del__() method is invoked when an object is about to be destroyed. This


method is invoked only when an object is no longer in use. It’s important to note that
the statement del x only decrements an object’s reference count and doesn’t
necessarily result in a call to this function. Further details about these methods can be
found in Chapter 7.

Table 3.9 Special Methods for Object Creation, Destruction, and


Representation

Method Description

102 | P a g e Python Programming (KNC-402)


__new__(cls [,*args [,**kwargs]]) A static method called to create a new instance

__init__(self [,*args [,**kwargs]]) Called to initialize a new instance

__del__(self) Called to destroy an instance

__repr__(self) Creates a full string representation of an object

__str__(self) Creates an informal string representation

__cmp__(self,other) Compares two objects and returns negative, zero,


or positive

__hash__(self) Computes a 32-bit hash index

__nonzero__(self) Returns 0 or 1 for truth-value testing

__unicode__(self) Creates a Unicode string representation

The __new__() and __init__() methods are used to create and initialize new instances.
When an object is created by calling A(args), it is translated into the following steps:

x = A.__new__(A,args)

is isinstance(x,A): x.__init__(args)

The __repr__() and __str__() methods create string representations of an object.


The __repr__() method normally returns an expression string that can be evaluated to
re-create the object. This method is invoked by the built-in repr() function and by the
backquotes operator (´). For example:

a = [2,3,4,5] # Create a list

s = repr(a) # s = '[2, 3, 4, 5]'

# Note : could have also used s = ´a´

b = eval(s) # Turns s back into a list

103 | P a g e Python Programming (KNC-402)


If a string expression cannot be created, the convention is for __repr__() to return a
string of the form <...message...>, as shown here:

f = open("foo")

a = repr(f) # a = "<open file ‘foo’, mode ‘r’ at dc030>"

The __str__() method is called by the built-in str() function and by the print statement.
It differs from __repr__() in that the string it returns can be more concise and
informative to the user. If this method is undefined, the __repr__() method is invoked.
The __cmp__(self,other) method is used by all the comparison operators. It returns a
negative number if self < other, zero if self == other, and positive if self > other. If this
method is undefined for an object, the object will be compared by object identity. In
addition, an object may define an alternative set of comparison functions for each of
the relational operators. These are known as rich comparisons and are described
shortly. The __nonzero__() method is used for truth-value testing and should
return 0 or 1 (or True or False). If undefined, the __len__() method is invoked to
determine truth.

Finally, the __hash__() method computes an integer hash key used in dictionary
operations (the hash value can also be returned using the built-in function hash()). The
value returned should be identical for two objects that compare as equal. Further-more,
mutable objects should not define this method; any changes to an object will alter the
hash value and make it impossible to locate an object on subsequent dictionary
lookups. An object should not define a __hash__() method without also
defining __cmp__().

Attribute Access
The methods in Table 3.10 read, write, and delete the attributes of an object using the
dot (.) operator and the del operator, respectively.

Table 3.10 Special Methods for Attribute Access

Method Description

__getattribute__(self,name) Returns the attribute self.name.

__getattr__(self, name) Returns the attribute self.name if not found through


normal attribute lookup.

__setattr__(self, name, value) Sets the attribute self.name = value. Overrides the
default mechanism.

__delattr__(self, name) Deletes the attribute self.name.

104 | P a g e Python Programming (KNC-402)


An example will illustrate:

class Foo(object):
def __init__(self):
self.x = 37
f = Foo()
a = f.x # Invokes __getattribute__(f,"x")
b = f.y # Invokes __getattribute__(f,"y") --> Not found
# Then invokes __getattr__(f,"y")
f.x = 42 # Invokes __setattr__(f,"x",42)
f.y = 93 # Invokes __setattr__(f,"y",93)
del f.y # Invokes __delattr__(f,"y")

Whenever an attribute is accessed, the __getattribute__() method is always invoked. If


the attribute is located, it is returned. Otherwise, the __getattr__() method is invoked.

The default behavior of __getattr__() is to raise an AttributeError exception.

The __setattr__() method is always invoked when setting an attribute, and


the __delattr__() method is always invoked when deleting an attribute.

A subtle aspect of attribute access concerns a special kind of attribute known as


a descriptor. A descriptor is an object that implements one or more of the methods in
Table 3.11.

Table 3.11 Special Methods for Descriptor Attributes

Method Description

__get__(self,instance,owner) Returns an attribute value or raises AttributeError

__set__(self,instance,value) Sets the attribute to value

__delete__(self,instance) Deletes the attribute


Essentially, a descriptor attribute knows how to compute, set, and delete its own value
whenever it is accessed. Typically, it is used to provide advanced features of classes
such as static methods and properties. For example:

class SimpleProperty(object):
def __init__(self,fget,fset):
self.fget = fget
self.fset = fset

def __get__(self,instance,cls):
return self.fget(instance) # Calls instance.fget()
105 | P a g e Python Programming (KNC-402)
def __set__(self,instance,value)
return self.fset(instance,value) # Calls instance.fset(value)

class Circle(object):
def __init__(self,radius):
self.radius = radius

def getArea(self):
return math.pi*self.radius**2

def setArea(self):
self.radius = math.sqrt(area/math.pi)

area = SimpleProperty(getArea,setArea)

In this example, the class SimpleProperty defines a descriptor in which two functions,
fget and fset, are supplied by the user to get and set the value of an attribute (note
that a more advanced version of this is already provided using the property() function
described in Chapter 7). In the Circle class that follows, these functions are used to
create a descriptor attribute called area. In subsequent code, the area attribute is
accessed transparently.

c = Circle(10)

a = c.area # Implicitly calls c.getArea()

c.area = 10.0 # Implicitly calls c.setArea(10.0)

Underneath the covers, access to the attribute c.area is being translated into an
operation such as Circle.__dict__[‘area’].__get__(c,Circle).
It is important to emphasize that descriptors can only be created at the class level. It is
not legal to create descriptors on a per-instance basis by defining descriptor objects
inside __init__() and other methods.

106 | P a g e Python Programming (KNC-402)


Sequence and Mapping Methods
The methods in Table 3.12 are used by objects that want to emulate sequence and
mapping objects.

Table 3.12 Methods for Sequences and Mappings

Method Description

__len__(self) Returns the length of self

__getitem__(self, key) Returns self[key]

__setitem__(self, key, value) Sets self[key] = value

__delitem__(self, key) Deletes self[key]

__getslice__(self,i,j) Returns self[i:j]

__setslice__(self,i,j,s) Sets self[i:j] = s

__delslice__(self,i,j) Deletes self[i:j]

__contains__(self,obj) Returns True if obj is in self; otherwise, returns False

Here's an example:

a = [1,2,3,4,5,6]

len(a) # __len__(a)

x = a[2] # __getitem__(a,2)

a[1] = 7 # __setitem__(a,1,7)

del a[2] # __delitem__(a,2)

x = a[1:5] # __getslice__(a,1,5)

a[1:3] = [10,11,12] # __setslice__(a,1,3,[10,11,12])

del a[1:4] # __delslice__(a,1,4)

107 | P a g e Python Programming (KNC-402)


The __len__ method is called by the built-in len() function to return a nonnegative
length. This function also determines truth values unless the __nonzero__() method
has also been defined.

For manipulating individual items, the __getitem__() method can return an item by key
value. The key can be any Python object, but is typically an integer for sequences.
The __setitem__() method assigns a value to an element. The __delitem__() method is
invoked whenever the del operation is applied to a single element.

The slicing methods support the slicing operator s[i:j]. The __getslice__() method
returns a slice, which is normally the same type of sequence as the original object. The
indices i and j must be integers, but their interpretation is up to the method. Missing
values for i and j are replaced with 0 and sys.maxint, respectively.
The __setslice__() method assigns values to a slice. Similarly, __delslice__() deletes all
the elements in a slice.

The __contains__() method is used to implement the in operator.


In addition to implementing the methods just described, sequences and mappings
implement a number of mathematical methods,
including __add__(), __radd__(), __mul__(), and __rmul__() to support concatenation
and sequence replication. These methods are described shortly.

Finally, Python supports an extended slicing operation that's useful for working with
multidimensional data structures such as matrices and arrays. Syntactically, you specify
an extended slice as follows:

a = m[0:100:10] # Strided slice (stride=10)


b = m[1:10, 3:20] # Multidimensional slice
c = m[0:100:10, 50:75:5] # Multiple dimensions with strides
m[0:5, 5:10] = n # extended slice assignment
del m[:10, 15:] # extended slice deletion

The general format for each dimension of an extended slice is i:j[:stride], where stride
is optional. As with ordinary slices, you can omit the starting or ending values for each
part of a slice. In addition, a special object known as the Ellipsis and written as ... is
available to denote any number of trailing or leading dimensions in an extended slice:

a = m[..., 10:20] # extended slice access with Ellipsis

m[10:20, ...] = n

108 | P a g e Python Programming (KNC-402)


When using extended slices, the __getitem__(), __setitem__(),
and __delitem__() methods implement access, modification, and deletion, respectively.
However, instead of an integer, the value passed to these methods is a tuple containing
one or more slice objects and at most one instance of the Ellipsis type. For example,

a = m[0:10, 0:100:5, ...]

invokes __getitem__() as follows:

a = __getitem__(m, (slice(0,10,None), slice(0,100,5), Ellipsis))

Python strings, tuples, and lists currently provide some support for extended slices,
which is described in Chapter 4. Special-purpose extensions to Python, especially those
with a scientific flavor, may provide new types and objects with advanced support for
extended slicing operations.

Iteration
If an object, obj, supports iteration, it must provide a method, obj.__iter__(), that
returns an iterator object. The iterator object iter, in turn, must implement a single
method, iter.next(), that returns the next object or raises StopIteration to signal the
end of iteration. Both of these methods are used by the implementation of
the for statement as well as other operations that implicitly perform iteration. For
example, the statement for x in s is carried out by performing steps equivalent to the
following:

_iter = s.__iter__()
while 1:
try:
x = _iter.next()
except StopIteration:
break
# Do statements in body of for loop
...

Mathematical Operations
Table 3.13 lists special methods that objects must implement to emulate numbers.
Mathematical operations are always evaluated from left to right; when an expression
such as x + y appears, the interpreter tries to invoke the method x.__add__(y). The
109 | P a g e Python Programming (KNC-402)
special methods beginning with r support operations with reversed operands. These are
invoked only if the left operand doesn’t implement the specified operation. For example,
if x in x + y doesn’t support the __add__() method, the interpreter tries to invoke the
method y.__radd__(x).

Table 3.13 Methods for Mathematical Operations

Method Result

__add__(self,other) self + other

__sub__(self,other) self - other

__mul__(self,other) self * other

__div__(self,other) self / other

__truediv__(self,other) self / other (future)

__floordiv__(self,other) self // other

__mod__(self,other) self % other

__divmod__(self,other) divmod(self,other)

__pow__(self,other [,modulo]) self ** other, pow(self, other, modulo)

__lshift__(self,other) self << other

__rshift__(self,other) self >> other

__and__(self,other) self & other

__or__(self,other) self | other

__xor__(self,other) self ^ other

__radd__(self,other) other + self

__rsub__(self,other) other - self

__rmul__(self,other) other * self

__rdiv__(self,other) other / self

__rtruediv__(self,other) other / self (future)

110 | P a g e Python Programming (KNC-402)


__rfloordiv__(self,other) other // self

__rmod__(self,other) other % self

__rdivmod__(self,other) divmod(other,self)

__rpow__(self,other) other ** self

__rlshift__(self,other) other << self

__rrshift__(self,other) other >> self

__rand__(self,other) other & self

__ror__(self,other) other | self

__rxor__(self,other) other ^ self

__iadd__(self,other) self += other

__isub__(self,other) self -= other

__imul__(self,other) self *= other

__idiv__(self,other) self /= other

__itruediv__(self,other) self /= other (future)

__ifloordiv__(self,other) self //= other

__imod__(self,other) self %= other

__ipow__(self,other) self **= other

__iand__(self,other) self &= other

__ior__(self,other) self |= other

__ixor__(self,other) self ^= other

__ilshift__(self,other) self <<= other

__irshift__(self,other) self >>= other

__neg__(self) –self

__pos__(self) +self

111 | P a g e Python Programming (KNC-402)


__abs__(self) abs(self)

__invert__(self) ~self

__int__(self) int(self)

__long__(self) long(self)

__float__(self) float(self)

__complex__(self) complex(self)

__oct__(self) oct(self)

__hex__(self) hex(self)

__coerce__(self,other) Type coercion

The methods __iadd__(), __isub__(), and so forth are used to support in-place
arithmetic operators such as a+=b and a-=b (also known as augmented assignment). A
distinction is made between these operators and the standard arithmetic methods
because the implementation of the in-place operators might be able to provide certain
customizations such as performance optimizations. For instance, if the self parameter is
not shared, it might be possible to modify its value in place without having to allocate a
newly created object for the result.

The three flavors of division operators, __div__(), __truediv__(), and __floordiv__(),


are used to implement true division (/) and truncating division (//) operations. The
separation of division into two types of operators is a relatively recent change to Python
that was started in Python 2.2, but which has far-reaching effects. As of this writing,
the default behavior of Python is to map the / operator to __div__(). In the future, it
will be remapped to __truediv__(). This latter behavior can currently be enabled as an
optional feature by including the statement from __future__ import division in a
program.

The conversion methods __int__(), __long__(), __float__(),


and __complex__() convert an object into one of the four built-in numerical types.
The __oct__() and __hex__() methods return strings representing the octal and
hexadecimal values of an object, respectively.

112 | P a g e Python Programming (KNC-402)


The __coerce__(x,y) method is used in conjunction with mixed-mode numerical
arithmetic. This method returns either a 2-tuple containing the values of x and y
converted to a common numerical type, or NotImplemented (or None) if no such
conversion is possible. To evaluate the operation x op y, where op is an operation such
as +, the following rules are applied, in order:
1. If x has a __coerce__() method, replace x and y with the values returned by
x.__coerce__(y). If None is returned, skip to step 3.
2. If x has a method __op__(), return x.__op__(y). Otherwise, restore x and y to
their original values and continue.
3. If y has a __coerce__() method, replace x and y with the values returned by
y.__coerce__(x). If None is returned, raise an exception.
4. If y has a method __rop__(), return y.__rop__(x). Otherwise, raise an exception.

Although strings define a few arithmetic operations, the __coerce__() method is not
used in mixed-string operations involving standard and Unicode strings.
The interpreter supports only a limited number of mixed-type operations involving the
built-in types, in particular the following:

• If x is a string, x % y invokes the string-formatting operation, regardless of the


type of y.
• If x is a sequence, x + y invokes sequence concatenation.
• If either x or y is a sequence and the other operand is an integer, x * y invokes
sequence repetition.

Comparison Operations
Table 3.14 lists special methods that objects can implement to provide individualized
versions of the relational operators (<, >, <=, >=, ==, !=). These are known as rich
comparisons. Each of these functions takes two arguments and is allowed to return any
kind of object, including a Boolean value, a list, or any other Python type. For instance,
a numerical package might use this to perform an element-wise comparison of two
matrices, returning a matrix with the results. If a comparison can’t be made, these
functions may also raise an exception.

113 | P a g e Python Programming (KNC-402)


Table 3.14 Methods for Comparisons

Method Result

__lt__(self,other) self < other

__le__(self,other) self <= other

__gt__(self,other) self > other

__ge__(self,other) self >= other

__eq__(self,other) self == other

__ne__(self,other) self != other

Callable Objects
Finally, an object can emulate a function by providing
the __call__(self [,*args [, **kwargs]]) method. If an object, x, provides this method,
it can be invoked like a function. That is, x(arg1, arg2, ...) invokes
x.__call__(self, arg1, arg2, ...).

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from
another class.

Parent class is the class being inherited from, also called base class.

Child class is the class that inherits from another class, also called derived class.

Create a Parent Class

Any class can be a parent class, so the syntax is the same as creating any other class:

Example

Create a class named Person, with firstname and lastname properties, and
a printname method:
114 | P a g e Python Programming (KNC-402)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname

def printname(self):
print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("John", "Doe")
x.printname()

Create a Child Class

To create a class that inherits the functionality from another class, send the parent
class as a parameter when creating the child class:

Example

Create a class named Student, which will inherit the properties and methods from
the Person class:

class Student(Person):
pass

Note: Use the pass keyword when you do not want to add any other properties or
methods to the class.

Now the Student class has the same properties and methods as the Person class.

Example

Use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Olsen")
x.printname()

115 | P a g e Python Programming (KNC-402)


Add the __init__() Function

So far we have created a child class that inherits the properties and methods from its
parent.

We want to add the __init__() function to the child class (instead of


the pass keyword).

Note: The __init__() function is called automatically every time the class is being used
to create a new object.

Example

Add the __init__() function to the Student class:

class Student(Person):
def __init__(self, fname, lname):
#add properties etc.

When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.

Note: The child's __init__() function overrides the inheritance of the


parent's __init__() function.

To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:

Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)

Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.

Use the super() Function

Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:

116 | P a g e Python Programming (KNC-402)


Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)

By using the super() function, you do not have to use the name of the parent element,
it will automatically inherit the methods and properties from its parent.

Add Properties
Example

Add a property called graduationyear to the Student class:

class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019

In the example below, the year 2019 should be a variable, and passed into
the Student class when creating student objects. To do so, add another parameter in
the __init__() function:

Example

Add a year parameter, and pass the correct year when creating objects:

class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year

x = Student("Mike", "Olsen", 2019)

Add Methods
Example

Add a method called welcome to the Student class:

class Student(Person):
def __init__(self, fname, lname, year):
117 | P a g e Python Programming (KNC-402)
super().__init__(fname, lname)
self.graduationyear = year

def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of",
self.graduationyear)

If you add a method in the child class with the same name as a function in the parent
class, the inheritance of the parent method will be overridden.

Introduction to OOPs in Python

Python is a multi-paradigm programming language. Meaning, it supports different


programming approach.

One of the popular approach to solve a programming problem is by creating objects.


This is known as Object-Oriented Programming (OOP).

An object has two characteristics:

• attributes
• behavior

Let's take an example:

Parrot is an object,

• name, age, color are attributes


• singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also
known as DRY (Don't Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

A process of using details from a new class without modifying


Inheritance existing class.

Encapsulation Hiding the private details of a class from other objects.

118 | P a g e Python Programming (KNC-402)


A concept of using common operation in different ways for different
Polymorphism data input.

Class

A class is a blueprint for the object.

We can think of class as an sketch of a parrot with labels. It contains all the details
about the name, colors, size etc. Based on these descriptions, we can study about the
parrot. Here, parrot is an object.

The example for class of parrot can be :

class Parrot:

pass

Here, we use class keyword to define an empty class Parrot. From class, we construct
instances. An instance is a specific object created from a particular class.

Object

An object (instance) is an instantiation of a class. When class is defined, only the


description for the object is defined. Therefore, no memory or storage is allocated.

The example for object of parrot class can be:

obj = Parrot()

Here, obj is object of class Parrot.

Suppose we have details of parrot. Now, we are going to show how to build the class
and objects of parrot.

class Parrot:

# class attribute

species = "bird"
119 | P a g e Python Programming (KNC-402)
# instance attribute

def __init__(self, name, age):

self.name = name

self.age = age

# instantiate the Parrot class

blu = Parrot("Blu", 10)

woo = Parrot("Woo", 15)

# access the class attributes

print("Blu is a {}".format(blu.__class__.species))

print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes

print("{} is {} years old".format( blu.name, blu.age))

print("{} is {} years old".format( woo.name, woo.age))

When we run the program, the output will be:

Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old

In the above program, we create a class with name Parrot. Then, we define attributes.
The attributes are a characteristic of an object.

Then, we create instances of the Parrot class. Here, blu and woo are references (value)
to our new objects.

Then, we access the class attribute using __class __.species. Class attributes are same
for all instances of a class. Similarly, we access the instance attributes
using blu.name and blu.age. However, instance attributes are different for every
instance of a class.

Methods

Methods are functions defined inside the body of a class. They are used to define the
behaviors of an object.

120 | P a g e Python Programming (KNC-402)


class Parrot:

# instance attributes

def __init__(self, name, age):

self.name = name

self.age = age

# instance method

def sing(self, song):

return "{} sings {}".format(self.name, song)

def dance(self):

return "{} is now dancing".format(self.name)

# instantiate the object

blu = Parrot("Blu", 10)

# call our instance methods

print(blu.sing("'Happy'"))

print(blu.dance())

When we run program, the output will be:

Blu sings 'Happy'


Blu is now dancing

In the above program, we define two methods i.e sing() and dance(). These are called
instance method because they are called on an instance object i.e blu.

Inheritance

Inheritance is a way of creating new class for using details of existing class without
modifying it. The newly formed class is a derived class (or child class). Similarly, the
existing class is a base class (or parent class).

# parent class

class Bird:

121 | P a g e Python Programming (KNC-402)


def __init__(self):

print("Bird is ready")

def whoisThis(self):

print("Bird")

def swim(self):

print("Swim faster")

# child class

class Penguin(Bird):

def __init__(self):

# call super() function

super().__init__()

print("Penguin is ready")

def whoisThis(self):

print("Penguin")

def run(self):

print("Run faster")

peggy = Penguin()

peggy.whoisThis()

peggy.swim()

peggy.run()

When we run this program, the output will be:

Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster

In the above program, we created two classes i.e. Bird (parent class)
and Penguin (child class). The child class inherits the functions of parent class. We can
see this from swim() method. Again, the child class modified the behavior of parent

122 | P a g e Python Programming (KNC-402)


class. We can see this from whoisThis() method. Furthermore, we extend the functions
of parent class, by creating a new run() method.

Additionally, we use super() function before __init__() method. This is because we want
to pull the content of __init__() method from the parent class into the child class.

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevent
data from direct modification which is called encapsulation. In Python, we denote
private attribute using underscore as prefix i.e single “ _ “ or double “ __“.

class Computer:

def __init__(self):

self.__maxprice = 900

def sell(self):

print("Selling Price: {}".format(self.__maxprice))

def setMaxPrice(self, price):

self.__maxprice = price

c = Computer()

c.sell()

# change the price

c.__maxprice = 1000

c.sell()

# using setter function

c.setMaxPrice(1000)

c.sell()

When we run this program, the output will be:

Selling Price: 900


Selling Price: 900
Selling Price: 1000

123 | P a g e Python Programming (KNC-402)


In the above program, we defined a class Computer. We use __init__() method to store
the maximum selling price of computer. We tried to modify the price. However, we
can’t change it because Python treats the __maxprice as private attributes. To change
the value, we used a setter function i.e setMaxPrice() which takes price as parameter.

Polymorphism

Polymorphism is an ability (in OOP) to use common interface for multiple form (data
types).

Suppose, we need to color a shape, there are multiple shape option (rectangle, square,
circle). However we could use same method to color any shape. This concept is called
Polymorphism.

class Parrot:

def fly(self):

print("Parrot can fly")

def swim(self):

print("Parrot can't swim")

class Penguin:

def fly(self):

print("Penguin can't fly")

def swim(self):

print("Penguin can swim")

# common interface

def flying_test(bird):

bird.fly()

#instantiate objects

blu = Parrot()

peggy = Penguin()

# passing the object

124 | P a g e Python Programming (KNC-402)


flying_test(blu)

flying_test(peggy)

When we run above program, the output will be:

Parrot can fly


Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have
common method fly() method. However, their functions are different. To allow
polymorphism, we created common interface i.e flying_test() function that can take any
object. Then, we passed the objects blu and peggy in the flying_test() function, it ran
effectively.

Key Points to Remember:


• The programming gets easy and efficient.
• The class is sharable, so codes can be reused.
• The productivity of programmars increases
• Data is safe and secure with data abstraction.

UNIT-5
Iterators in Python

Iterator in python is any python type that can be used with a ‘for in loop’. Python lists,
tuples, dicts and sets are all examples of inbuilt iterators. These types are iterators
because they implement following methods. In fact, any object that wants to be an
iterator must implement following methods.
1. __iter__ method that is called on initialization of an iterator. This should return
an object that has a next or __next__ (in Python 3) method.

2. next ( __next__ in Python 3) The iterator next method should return the next
value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop
implicitly calls next() on the iterator object. This method should raise a
StopIteration to signal the end of the iteration.

125 | P a g e Python Programming (KNC-402)


Below is a simple Python program that creates iterator type that iterates from 10 to
given limit. For example, if limit is 15, then it prints 10 11 12 13 14 15. And if limit is 5,
then it prints nothing.
# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value

# An iterable user defined type


class Test:

# Constructor
def __init__(self, limit):
self.limit = limit

# Called when iteration is initialized


def __iter__(self):
self.x = 10
return self

# To move to next element. In Python 3,


# we should replace next with __next__
def next(self):

# Store current value ofx


x = self.x

# Stop iteration if limit is reached


if x > self.limit:
raise StopIteration

# Else increment and return old value


self.x = x + 1;
return x

# Prints numbers from 10 to 15


for i in Test(15):
print(i)

# Prints nothing
for i in Test(5):
print(i)

Output :
10
11
12
13

126 | P a g e Python Programming (KNC-402)


14
15

Python Recursive Function

We know that in Python, a function can call other functions. It is even possible for
the function to call itself. These type of construct are termed as recursive
functions.

Following is an example of recursive function to find the factorial of an integer.

Factorial of a number is the product of all the integers from 1 to that number. For
example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Example of recursive function

# An example of a recursive function to


# find the factorial of a number

def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))

In the above example, calc_factorial() is a recursive functions as it calls itself.

When we call this function with a positive integer, it will recursively call itself by
decreasing the number.

Each function call multiples the number with the factorial of number 1 until the number
is equal to one.

#Recursive Python Program for Fibonacci Series:


1. def recur_fibo(n):
2. if n <= 1:
3. return n
4. else:
5. return(recur_fibo(n-1) + recur_fibo(n-2))

127 | P a g e Python Programming (KNC-402)


6. # take input from the user
7. nterms = int(input("How many terms? "))
8. # check if the number of terms is valid
9. if nterms <= 0:
10. print("Plese enter a positive integer")
11. else:
12. print("Fibonacci sequence:")
13. for i in range(nterms):
14. print(recur_fibo(i))

Python Program for Tower of Hanoi

Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The
objective of the puzzle is to move the entire stack to another rod, obeying the following
simple rules:

1) Only one disk can be moved at a time.


2) Each move consists of taking the upper disk from one of the stacks and placing it on
top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.

# Recursive Python function to solve tower of hanoi

def TowerOfHanoi(n , from_rod, to_rod, aux_rod):

if n == 1:

print "Move disk 1 from rod",from_rod,"to rod",to_rod

return

TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)

128 | P a g e Python Programming (KNC-402)


print "Move disk",n,"from rod",from_rod,"to rod",to_rod

TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)

# Driver code

n=4

TowerOfHanoi(n, \'A\', \'C\', \'B\')

# A, C, B are the name of rods

Output:
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

Python Program to Implement Linear Search


This is a Python program to implement linear search.
Problem Description

The program takes a list and key as input and finds the index of the key in the list using
linear search.
Problem Solution

129 | P a g e Python Programming (KNC-402)


1. Create a function linear_search that takes a list and key as arguemnts.
2. A loop iterates through the list and when an item matching the key is found, the
corresponding index is returned.
3. If no such item is found, -1 is returned.
Program/Source Code

Here is the source code of a Python program to implement linear search. The program
output is shown below.
def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1

alist = input('Enter the list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = linear_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Program Explanation

1. The user is prompted to enter a list of numbers.


2. The user is then asked to enter a key to search for.
3. The list and key is passed to linear_search.
4. If the return value is -1, the key is not found and a message is displayed, otherwise
the index of the found item is displayed.
Runtime Test Cases

Case 1:
Enter the list of numbers: 5 4 3 2 1 10 11 2
The number to search for: 1
1 was found at index 4.

Case 2:
Enter the list of numbers: 5 2 1 5 -3
130 | P a g e Python Programming (KNC-402)
The number to search for: 2
2 was found at index 1.

Case 3:
Enter the list of numbers: 3 5 6
The number to search for: 2
2 was not found.

Python Program to Implement Binary Search

Problem Description

The program takes a list and key as input and finds the index of the key in the list using
binary search.
Problem Solution

1. Create a function binary_search that takes a list and key as arguments.


2. The variable start is set to 0 and end is set to the length of the list.
3. The variable start keeps track of the first element in the part of the list being
searched while end keeps track of the element one after the end of the part being
searched.
4. A while loop is created that iterates as long as start is less than end.
5. mid is calculated as the floor of the average of start and end.
6. If the element at index mid is less than key, start is set to mid + 1 and if it is more
than key, end is set to mid. Otherwise, mid is returned as the index of the found
element.
7. If no such item is found, -1 is returned.
Program/Source Code

Here is the source code of a Python program to implement binary search without using
recursion. The program output is shown below.
def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end)//2
if alist[mid] > key:
end = mid
elif alist[mid] < key:
start = mid + 1
else:
return mid
return -1

alist = input('Enter the sorted list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
131 | P a g e Python Programming (KNC-402)
key = int(input('The number to search for: '))

index = binary_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Program Explanation

1. The user is prompted to enter a list of numbers.


2. The user is then asked to enter a key to search for.
3. The list and key is passed to binary_search.
4. If the return value is -1, the key is not found and a message is displayed, otherwise
the index of the found item is displayed.
Runtime Test Cases

Case 1:
Enter the sorted list of numbers: 3 5 10 12 15 20
The number to search for: 12
12 was found at index 3.

Case 2:
Enter the sorted list of numbers: -3 0 1 5 6 7 8
The number to search for: 2
2 was not found.

Case 3:
Enter the sorted list of numbers: 5
The number to search for: 5
5 was found at index 0.

Python Program to Implement Selection Sort

This is a Python program to implement selection sort.


Problem Description

The program sorts a list by selection sort.


Problem Solution

132 | P a g e Python Programming (KNC-402)


1. Create a function selection_sort that takes a list as argument.
2. Inside the function create a loop with a loop variable i that counts from 0 to the
length of the list – 1.
3. Create a variable smallest with initial value i.
4. Create an inner loop with a loop variable j that counts from i + 1 up to the length of
the list – 1.
5. Inside the inner loop, if the elements at index j is smaller than the element at index
smallest, then set smallest equal to j.
6. After the inner loop finishes, swap the elements at indexes i and smallest.
Program/Source Code

Here is the source code of a Python program to implement selection sort. The program
output is shown below.
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)

Program Explanation

1. The user is prompted to enter a list of numbers.


2. The list is passed to the selection_sort function.
3. The sorted list is displayed.
Runtime Test Cases

Case 1:
Enter the list of numbers: 3 1 4 5 2 6
Sorted list: [1, 2, 3, 4, 5, 6]

Case 2:
Enter the list of numbers: 2 10 5 38 1 7
Sorted list: [1, 2, 5, 7, 10, 38]

Case 3:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]

133 | P a g e Python Programming (KNC-402)


Python Program to Implement Merge Sort

This is a Python program to implement merge sort.


Problem Description

The program sorts a list by merge sort.


Problem Solution

1. Create a function merge_sort that takes a list and two variables start and end as
arguments.
2. The function merge_sort will sort the list from indexes start to end – 1 inclusive.
3. If end – start is not greater than 1, then return.
4. Otherwise, set mid equal to the floor of (start + end)/2.
5. Call merge_sort with the same list and with start = start and end = mid as
arguments.
6. Call merge_sort with the same list and with start = mid and end = end as
arguments.
7. Call the function merge_list, passing the list and the variables start, mid and end as
arguments.
8. The function merge_list takes a list and three numbers, start, mid and end as
arguments and assuming the list is sorted from indexes start to mid – 1 and from mid
to end – 1, merges them to create a new sorted list from indexes start to end – 1.
Program/Source Code

Here is the source code of a Python program to implement merge sort. The program
output is shown below.
def merge_sort(alist, start, end):
'''Sorts the list from indexes start to end - 1 inclusive.'''
if end - start > 1:
mid = (start + end)//2
merge_sort(alist, start, mid)
merge_sort(alist, mid, end)
merge_list(alist, start, mid, end)

def merge_list(alist, start, mid, end):


left = alist[start:mid]
right = alist[mid:end]
k = start
i = 0
j = 0
while (start + i < mid and mid + j < end):
if (left[i] <= right[j]):
alist[k] = left[i]
i = i + 1
else:
alist[k] = right[j]
j = j + 1
k = k + 1

134 | P a g e Python Programming (KNC-402)


if start + i < mid:
while k < end:
alist[k] = left[i]
i = i + 1
k = k + 1
else:
while k < end:
alist[k] = right[j]
j = j + 1
k = k + 1

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
merge_sort(alist, 0, len(alist))
print('Sorted list: ', end='')
print(alist)

Program Explanation

1. The user is prompted to enter a list of numbers.


2. The list is passed to the merge_sort function.
3. The sorted list is displayed.
Runtime Test Cases

Case 1:
Enter the list of numbers: 3 1 5 8 2 5 1 3
Sorted list: [1, 1, 2, 3, 3, 5, 5, 8]

Case 2:
Enter the list of numbers: 5 3 2 1 0
Sorted list: [0, 1, 2, 3, 5]

Case 3:
Enter the list of numbers: 1
Sorted list: [1]

Higher order sort

sorted

sorted does pretty much the same thing what you expected.

135 | P a g e Python Programming (KNC-402)


# sorting numbers
In [0]: sorted([9, 5, 7])
Out[0]: [5, 7, 9]

# sorting alphabetically
In [0]: sorted(['foo', 'bar'])
Out[0]: ['bar', 'foo']

Using Key :key:


Well you can also customize the sorting also, the parameter key. The key needs to be
a simple function the takes a single value that tells python the value to use in sorting it.

In [0]: sorted([1, -3, 2]) # sorting normally


Out[0]: [-3, 1, 2]

In [0]: sorted([1, -2, 0], key=abs) # sorting by absolute values


Out[0]: [0, 1, -2]

Note: abs is the absolute value function. i.e. abs(-3) = 3

136 | P a g e Python Programming (KNC-402)

You might also like