You are on page 1of 146

OBJECTIVES

By the end of this module , you should be able to:

 Assess the importance of Python

 Get started with the Python environment

 Python interactive mode and scripting interface

 Understand variables, constructs and indentation

 Perform operations on basic and advanced data types

 Use tools like zip , lambda functions, filter and map

 Use file handling

1
PART 1
Python overview
WHAT IS PYTHON?

Python is a

 high level,

object-oriented,

interpreted,

multipurpose programming language.

3
KEY FEATURES

 Python focusses on readability & simplicity

 Python code is usually very compact

 Python code is portable across OS platforms

 Huge collection of libraries available for use by developers

4
ABOUT PYTHON

 Invented in the Netherlands in the early ‘90s by Guido van Rossum.

 Name after ‘Monty Python’, a comedy group, depicting its ‘fun’ philosophy

 Open source and interpreted language

 Considered a ‘scripting’ language, but is much more than that

 Scalable, object-oriented and functional

 Used by Google, increasingly popular

 Python knowledge is on high trending currently

5
USERS OF PYTHON

YouTube: Originally written in Python and mysql


Yahoo!: Yahoo acquired Four11, whose address and mapping lookup
services are implemented in Python
Yahoo! Maps uses Python
DropBox, a cloud based file hosting service runs on Python
Google: Many components of the Google spider and search engine are
written in Python

6
TRADITIONAL USES OF PYTHON

 Embedded Scripting

 Image processing

 Artificial intelligence

 GUI’s

 Database Programming

 Internet Scripting

 System Administration

 Automation

7
PYTHON 2 OR PYTHON 3?

 We would be using Python 3.7+

 Library support is more for Python 2.7 as it has been around longer

 The future is going to be Python 3+

 Development and porting of libraries is an ongoing process

 There are several key syntactic changes so advisable to be with 3.7+

8
HOW TO GET PYTHON?

 Comes pre-installed on most Unix systems, including Linux and Mac OS X

 Check your python version by issuing the following command

python --version
Python 3.5.2

9
PYTHON DOWNLOAD AND INSTALLATION

 Python may be downloaded from the following URL


https://www.python.org/downloads/

You can choose the version and operating system

Latest is recommended

10
USING PYTHON

 Python can be used in interactive or scripting mode


 Interactive mode allows one to quickly interact with Python on a command line interface
 Scripting mode allows to store several commands and constructs to be saved as a program
and then executed at one go

 Demonstration of both of these modes follows:

11
COMMENTS , LITERALS, VARIABLES

Any statement with a leading ‘#’ is treated as a comment


Literal Constants : Any number or a string value
Variable : A user defined container that can hold a literal value
a=10 # variable a contains 10
b=‘Hello’ # Storing a string ‘Hello’ in variable b
c=“World” # Stores a string ‘World’ in variable c
Variable : A user defined container that can hold a literal value

12
PYTHON IDENTIFIERS

Identifiers are names for entities


variables
functions
classes
objects
Identifiers have the following rules
Starts with [a-zA-Z_]
Following character could also include digits [0-9]
case-sensitive: Hello, hello and HELLO are three separate identifiers
Only special character allowed is the underscore ( _ )

13
OPERATIONS ON NUMBERS

 All basic arithmetic operations are supported


 Addition(+), subtraction(-), multiplication(*), Division(/)
 Modulo (%)
 Exponentiation (**)
 Integer division ( // )

 Logical Operators
 All 6 comparison operations are available(==, !=, <, <=, >, >=)
 To combine logical expressions, use : and not or

14
PRECEDENCE

In expressions having multiple operators, Python uses the PEMDAS


precedence resolution order
Parentheses
Exponentiation
Multiplication
Division
Addition
Subtraction
Python supports mixed type math. The final answer will be of the most
complex type

15
STRINGS - BASICS

Strings are ordered blocks of text


Written inside quotes ( both single and double quotes can be
used )
Basic Operations with strings
Concatenation: ‘hello’ + ‘world’ will result in ‘helloworld’
Repetition: ‘hello’ * 3 = ‘hellohellohello’
Indexing
Indexes start at 0
s[i] fetches character at index i
16
SOME BUILTIN STRING METHODS

 .capitalize()
 python -> Python

 .count(str, begin=0, end=len(str))


 Count number of occurrences of substring str inside this string

 .find(str, begin=0, end=len(str))


 Find first occurrence of str in string

17
DEMONSTRATION

 Using string operations and methods in interactive interface


 concatenation
 repetition
 find
 count

18
INDENTATION & BLOCKS

Indentation
Leading whitespace to shift some line starts to the right of others
Is used to determine grouping of statement in Python
Defines a ‘statement block’
Blocks
Start with a statement ending with ‘:’
All lines following it are indented forward
De-indenting to the previous level closes the block
Some editors, IDE’s automatically take care of indentation
Repeat: there are no curly braces { } in python for defining blocks

19
BASIC CONSTRUCTS

Conditions
if condition: statement
if condition: block
else
elif
Loops
for
while
break
continue

20
CONSTRUCTS : CONDITIONALS

if <condition>: statement or a block

if a<10 : print(“a is less than 10”)

if b<a :

print(“less”)

print(“value of a is “,a)

print(“value of b is “,b)

21
CONSTRUCTS : CONDITIONALS

if a<10 : print(“a is less than 10”)

else: print(“a is not less than 10”)

if b<a :

print(“less”)

print(“value of a is “,a)

print(“value of b is “,b)

else:

print(“Was not less”)

22
CONSTRUCTS : CONDITIONALS

if a<10:

print(“hello”)

elif a<5:

print(“world”)

23
CONSTRUCTS : CONDITIONALS

Keywords related to conditional statements

if

elif

else

24
CONSTRUCTS : ITERATIONS

while <condition>:

block

All the statements of the block are executed if the condition is true

At end of the block the condition is re-evaluated

If condition is still true, then the block is repeated

25
CONSTRUCTS : ITERATIONS

a=0

while a<10:

print(a)

a=a+1

This would display number 0 to 9

26
CONSTRUCTS : ITERATIONS

for <variable> in <iterable>:

block

The for loop iterates over an iterable, assigning subsequence elements of the sequence to the variable and then
executing the block

ctr=0

for x in “hello world”: # String is an iterable sequence of characters

if x == “o” : ctr=ctr+1

print(ctr)

27
CONSTRUCTS : ITERATIONS

for x in range(10):

print(x)

range function generate a sequence of number 0 to 9

28
CONSTRUCTS : ITERATIONS

range(10) # generates 0 to 9

range(3,10) # generates 3,4,5,6,7,8,9

So range function does not include the upper limiting value

range(3,10,2) # The third parameter is the stride or increment

# default stride was 1

# 3, 5 , 7 , 9

29
USE OF BREAK, CONTINUE, PASS

 break statement terminates a loop

 continue statement re-evaluates condition and restarts the block if true

30
USE OF BREAK, CONTINUE, PASS

 break statement terminates a loop

for letter in 'Python': # First Example

if letter == 'h':

break

print ('Current Letter :', letter)

31
USE OF BREAK, CONTINUE, PASS

 continue statement re-evaluates condition and restarts the block if true

for letter in 'Python': # First Example

if letter == 'h':

continue

print ('Current Letter :', letter)

32
USE OF BREAK, CONTINUE, PASS

 pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.

for letter in 'Python':

if letter == 'h':

pass

print ('This is pass block‘)

print ('Current Letter :', letter)

print ("Good bye!“)

33
TAKING INPUT FROM THE KEYBOARD

x=input()

x=input(“Enter a value”)

Value entered would be read as a string.

If we want it to be used as a number we can convert it

x=input(“Enter a value”)

y=int(x) # converts to integer

or

x=int(input(“Enter a value”)) # gets a number into x

34
GETTING DOWN TO PROGRAMMING

Writing a python script


Executing a python script
Debugging

Displaying results – the print function


print(a)
print(“This is the result”,a)
print(a,b,c)

35
RUNNING A PYTHON SCRIPT

 Python code saved in file with .py extension

 On a shell prompt type to run: python myfile.py

or Press f5 on script mode or go to run in top menu select run

 Edit, save, run, repeat

36
LAB EXERCISES

1. Generate the first 10 even numbers

2. Input a number and check if it is prime or not

3. Input 10 numbers and display the smallest and largest of them

4. Input 10 numbers and display the sum and average.

5. Input a number and calculate its factorial

37
ASSIGNMENT

 Count digits in a number

 Find out how many times a particular digit occurs in a number

 Display the Fibonacci series up to a max limit

 Calculate the factorial of a number n

 A program that generates all prime numbers between x and y

38
PART 2
Python Data Types
OBJECTIVES

This session is about Python types:

 Basic Python Literals


 Numbers
 Strings

 More complex Python types


 Tuples
 Sets
 Lists
 Dictionaries

40
NUMBERS

 Integers – normal vs long

 Floats – 16 digits of precision

 Other numeric types include hexdecimal, octal, complex numbers

Operators and functions for numbers will work on all the above

41
NUMBERS : ASSIGNMENTS

a=10

a=b=c=20

a,b,c=10,20,30 # a=10 b=20 c=30

a,b,c=10,5.3,20 # Improved with version

 Assignment creates a variable of the type of RHS expression

 Reassigning a variable simply creates a new variable

42
NUMBERS : OPERATORS

+ - * /

 % : Modulo division to get remainder : 5%2 gives 1

 ** : Power : 5**3 gives 125

 // : Integer division to get quotient : 5//2 gives 2

 a+=5 : implies a=a+5 ( We can combine with any operator as above )

 parenthesis can be used to combine expressions

 Precedence of operators is maintained in expressions

 The result is of the most complex type across all operands

 -a implies a unary operator. So if a was 5, then -a would be -5

43
NUMBERS : FUNCTIONS

int( ) function can convert a literal into an integer value

a=int(5.3) # results in 5

a=int(“23”) # results in 23

a=int(“0x41”,16) # results in 65. Second parameter is base

# by default base is 10

a=int(“0100”,2) # results in 4. Binary string to integer.

44
NUMBERS : FUNCTIONS

float( ) function can convert a literal into a float value

a=float(2) # results in 2.0

a=float(“2”) # results in 2.0

a=float(“2.3”) # results in 2.3

45
NUMBERS : FUNCTIONS

chr( ) : Returns ascii character, chr(65) gives ‘A’

ord( ) : Returns ascii value, ord(‘A’) gives 65

abs( ) : Returns the absolute value, abs(-5) gives 5

46
NUMBERS : FUNCTIONS

 divmod() function returns the quotient as well as the remainder of division

 q,r=divmod(5,3)

q becomes 1
r becomes 2

Functions in python can return multiple values in form of a sequence and the returned values
can be captured as above. The same can be implemented in user defined functions as well.

47
NUMBERS : FUNCTIONS

round( ) rounds off a float number to the digits needed.

a=round(4.3333,2) # returns 4.33

a=round(4.33) # returns 4

a=round(4.33,0) # returns 4.0

NOTE: Rounding is down to the nearest even value in case of midpoint

a=round(3.5) # returns 4

a=round(4.5) # returns 4, as 5 is not even

48
STRINGS

 We have already been introduced to string literals.


a=“hello”
b=‘world’
c=“””hello
world”””

• Triple quoted string can be a multi-line string


• Both single or double quotes mean the same

49
STRINGS : OPERATORS

+ : Used for concatenating strings

* : Used for replicating strings

in : To check for existence for example :

if “e” in “hello”:

print(“found”)

ch : To iterate through the string for example :

for ch in “hello”:

print(ch)

50
STRINGS : FUNCTIONS

There are several functions that work on strings such as :

len(“hello”) # returns the total number of characters in string

ord(“A”) # returns the ascii value of the character

51
STRINGS : METHODS

s=“hello world”

 x=s.count(‘o’) # gives us the total count of ‘o’ in the string

 y=“This is his coat”.count(‘is’) # counts repetitions of string ‘is’

 z=s.count(‘o’,2,5) # counts occurrences between index 2 and 5

 a=s.capitalize() # will capitalize first character of the string

 s.upper() s.lower() # returns the upper/lower converted string

 s.lstrip() s.rstrip() s.strip() # strips white spaces

Note: The string methods would return a new string rather than modifying the current one

52
STRINGS : METHODS

Testing conditions in a string

s.startswith(“he”)

s.endswith(“run”)

s.isalnum(), s.isalpha(), s.isdigit(), s.isupper(), s.islower(), s.isspace()

53
SEQUENCES

len( ) # gives the total number of elements in a sequence

in # can be used to check for existence of a value in the sequence

not in

[] # can be used to access an element or a slice of a sequence

# most sequences allow this operator

in # used to iterate through the sequence using for statement

54
SEQUENCES - EXAMPLE

A string is an ordered immutable sequence

s=“Hello”

 len(s) # gives the total elements in the sequence/string

 if ‘e’ in s: # use of in operator to check for existence

 s[1] # accesses character ‘e’, indexes start from 0

 s[1:4] # gives a slice of the sequence ‘ell’

 for c in s: # iterates one character at a time from s into c

 s[1]=‘c’ # not allowed, as string is immutable

55
SEQUENCES

 Sequences are collection of items

 Sequence items can be of any python type

 Sequences may be ordered or unordered


 Ordered sequences maintain order of elements
 Unordered sequences do not guarantee order of elements

 Sequences may be mutable or immutable


 Mutable sequences allow elements to be modified
 Immutable sequences do not allow elements to be modified

56
SLICES IN DETAIL

 A slice is a part of a sequence, returned as a new sequence

 The original sequence remains unchanged

 The [ ] brackets are used as a slice operator

b=a[1] # b is a single element slice of a

b=a[2:5] # slice is a[2],a[3] and a[4]

b=a[2:7:2] # slice is a[2], a[4], a[6] the index gap is 2 for elements

a[start,end,stride]

slice starts from the index start, does not include the index end, and stride is the gap after which the
elements are selected. By default stride is 1

57
SLICES IN DETAIL

 Negative index implies from the end of the sequence

 Index -1 refers to the last element

 Index -2 refers to the second last element and so on

s=‘ABCDEF’

print(s[-2]) # would print ‘E’

print(s[2:-2]) # prints ‘CD’ as the ending index is not included

58
SLICES IN DETAIL

 Negative stride implies traversing backwards

 The start index and end index should be logically correct

s=‘ABCDEF’

print(s[-1:0:-1])

This would start from the last element ( due to -1 index )

Will traverse backwards ( due to stride as -1 )

Will not include element 0 ( as end index is not included )

59
SLICES IN DETAIL

s=‘ABCDEF’

a=s[::] # makes a copy of s

b=s[::-1] # makes a reverse copy of s

60
TUPLES

 Tuples are ordered immutable sequences

a=10,20,30,40

a=(10,20,30,40)

In both the above, a tuple is assigned to the variable a

a[0] is 10

a[0]=12 is not allowed since a tuple is immutable

len(a) gives us 4, the total elements in the tuple

We can use slicing and use ‘in’ to check for existence or iterate a tuple

61
TUPLES

 Tuples can be added to get a new tuple

a=(10,20,30,40)

b=(15,16)

c=a+b

print(c)

This would print :

(10,20,30,40,15,16)

62
SETS

 Sets are unordered immutable sequences of UNIQUE elements

a={ 10,20,30,40 }

b={ 20,50,60 }

c=set() # makes an empty set

If a duplicate element was provided during assignment, it would be discarded automatically

The in operator can be used to check for existence of an element

The len() function can be used to find total elements in a set

63
SET OPERATIONS

a={ 10,20,30,40 }

b={ 20,50,60 }

c=a-b # What is in a but not in b

c=a&b # What is in a and b , Intersection

c=a|b # What is in a or b , Union

c=a^b # What is only in a or only in b, but not in both, exclusive or

-- DEMONSTRATION

64
LISTS

 Lists are ordered mutable sequences

 Lists can be compared to heterogeneous arrays

 Lists can be increased or decreased dynamically

a=[ 10, 20, “John” ]

a[0] # gives us 10

a[2] # gives us “John”

a[1]=30 # updates element at index 1 ( mutable )

65
LISTS OPERATIONS

A=[] # Creates an empty list

A=[10,”Alpha”, 5.3 ,20 ] # Creates a list with mixed type elements

A=[10,20,[2,3],30] # Element at index 2 is a list ( nesting )

A[1] # Gives 20

A[2][1] # Gives 3

len(A) # Gives 4 ( nested list is one element )

B=A*3 # Replicates A 3 times

A[2:4] # Slicing

66
LISTS OPERATIONS

if 10 in A: # check for existence of 10 in List

for e in A: # Iterates all elements of A

A.append(24) # Adds 24 as last element of A

A.extend( [1,5,9] ) # Appends a list at end of A

A.insert(2,”Hello”) # “Hello” inserted as index 2, shifting the elements

A.count(20) # counts occurrence of literal 20 in List

A.remove(10) # removes first occurrence of literal from the list

x=A.pop(2) # removes and returns element at index 2

67
LISTS OPERATIONS

A.sort() # Sorts the list

A.reverse() # Reverses the list

del A[x] # deletes the index location and shifts elements up

del A[x:y] # deletes a slice from the List and shifts accordingly

A[x:y]=[1,100,2] # replaces a slice, adjusting indexes automatically

68
LISTS BUILDING BY COMPREHENSION

A=[ x for x in range(2,10,2) ]

The iteration results are used to populate the list A

This is a very powerful feature

A lot more would be explored in this context

69
LISTS & STRINGS

s=“Hello”

a=list(s) # a=[‘H’,’e’,’l’,’l’,’o’]

a[4]=‘p’ # a=[‘H’,’e’,’l’,’l’,’p’] as list is mutable

b=‘’.join(a) # join combines elements of a as a string

b=‘-’.join(a) # string before join, is used as separator

# b=“H-e-l-l-o”

c=b.split(‘-’) # splits string b on character ‘-’ resulting in a list

# default splitting character is white space

70
DICTIONARIES

 Unordered Mutable collection of mapping objects

 Values accessed by key

 Heterogeneous

 Can be nested

 Can vary in size

 Modifiable in place

 Hash table based for efficiency

71
DICTIONARY OPERATIONS

D={} # creates an empty dictionary

D={ ‘rollno’ : 142, ‘name’ : ”Anurag”, ‘age’ : 26 }

D=dict(‘rollno’=142, ‘name’=“Anurag”, ‘age’=26)

Both the above statements make a dictionary having 3 key,value pairs

print ( D[‘rollno’] ) # prints 142

D[‘age’]=28 # changes value of ‘age’ key to 28

72
DICTIONARY OPERATIONS

len( D ) # returns total key,value pair count

D[ ‘city’ ] = “Delhi” # creates a new key,value pair

D.clear( ) # empties the dictionary

In the current example

D={ ‘rollno’ : 142, ‘name’ : ”Anurag”, ‘age’ : 26 }

The dictionary D may express a record of data

73
DICTIONARY OPERATIONS

D= { ‘Amit’:45 , ‘Rahul’: 80, ‘Vivek’: 78 , ‘Deepa’: 67 }

This dictionary is representing multiple records of student marks, with key as their name

if ‘Rahul’ in D: # checks existence of a key in the dictionary

del D[‘Rahul’] # deletes the key ‘Rahul’

D.pop(‘Rahul’) # removes and returns the value of key ‘Rahul’

D.pop(‘Dinesh’,0) # remove/return value of ‘Dinesh’ else 0

74
DICTIONARY OPERATIONS

D.get(‘Rahul’,12) # gives value of ‘Rahul’ else 12

D.setdefault(‘Dinesh’,5) # if exists, return value else create/return new

Building a dictionary by comprehension:

D = { x : x**2 for x in range(5) }

75
DICTIONARY OPERATIONS

D.update( D2 ) # Updates D, same keys updated, new added

D.keys( ) # returns an iterable of keys

D.values( ) # returns an iterable of values

list(D.keys( ) ) # Makes a list object from iterable of keys

list(D.values( ) ) # Makes a list object from iterable of values

for k in D.keys() : # iterate through the keys

for k in D.values() : # iterate through the values

76
DICTIONARY OPERATIONS

D.items( ) # returns an iterable of key,value tuples

for k,v in D.items( ): # usage of D.items()

77
DICTIONARY & LISTS

A dictionary is a heterogeneous collection, so it can contain any python type elements.

A list is also a heterogeneous collection, so it can also contain any python type elements.

L=[ ‘Joseph’, { ‘eng’:89, ‘math’:76, ‘physics’:80 }, ‘Delhi’ ]

In this list, element at index location 1, is a dictionary of subject:marks pairs.

L[1][‘math’] would give 76

78
DICTIONARY & LISTS

Similar to previous example

D={ ‘roll’:142, ‘marks’:[70,89,56,65], ‘city’:”Delhi” }

In the dictionary D, we have 3 key,value pairs.

D[‘marks’] is a list, that contains some marks

len( D[‘marks’] ) would give us the length of that list == 4

D[‘marks’][2] would give 56

for m in D[‘marks’]: # iterate through the marks one by one

79
LAB EXERCISES

 Input a sentence and display the longest word

 Input a sentence and input a word. We have to find out how many times the word occurred in
the sentence.

 Display all the words that are contained in a sentence. Words that come multiple times should
be displayed only once.

 We wish to display only those words from the sentence that do not occur in a set of excluded
words ( like : this, and, is, not etc. ). The set of excuded words would be maintained in your
code, and the sentence is input from the keyboard. We have to display all words that do not
exist in this set, and we have to take care that multiple occurring words are displayed only
once.

 From an input sentence, build a dictionary of words along with their frequency. Display the
words in sorted order along with their count.
80
ASSIGNMENT

 make string from an input string with words in reverse order.


"A CAT RAN" => "RAN CAT A“

 Get a list of words with their count in a sentence. The words should be in sorted order
alphabetically. Words should not be repeated. Assume space as a separator for words.

81
PART 3
Python Modular Programming (user defined functions (UDF))
USER DEFINED FUNCTIONS

def displayLine( ) : # def keyword defines a function

print(‘-’ * 20 ) # body of the function is indented

# main program

print(“Hello world”)

displayLine( ) # the function call

print(“End of my program”)

83
UDF : RETURNING VALUES

def displayLine( ) : # def keyword defines a function


print(‘-’ * 20 ) # function of the body is indented
return 20 # the return expression

# main program
print(“Hello world”)
x=displayLine( ) # the function call returns 20 into x
print(“End of my program”)

84
UDF : RETURNING MULTIPLE VALUES

def displayLine( ) : # def keyword defines a function


print(‘-’ * 20 ) # function of the body is indented
return 20 , 30 # the return expression returns a tuple

# main program
print(“Hello world”)
x , y=displayLine( ) # returns 20 into x and 30 into y
print(“End of my program”)

85
UDF : PASSING PARAMETERS

def greater( a , b ) : # a and b are parameters


if a>b : return a
else : return b

# main program
print(“Hello world”)
y=10
x=greater( 10 , y ) # 10 is first parameter and y the second one

86
UDF : PARAMETERS AND RETURN VALUES

• Any datatype can be passed as parameter(s)


• Any datatype element(s) can be returned
• Function variables are passed as call by value

Demonstration for call by value


As ordinary values
As lists

87
UDF : VARIABLE SCOPE

• All variables created in a function are local to it


• All parameters variables of a function are local to the function
• A global variable is accessible in functions but not modifiable
• A variable created in a function is not available to further child functions
• To get editable access to a global variable, specify it as global in the function
def test( ):
global interestRate, principal
# these two variables are global

88
LAB EXERCISES

 Make a function that inputs a string and a word, and returns the number of times the word
occurred in the string.

 Make a function to calculate the factorial of a number.

f=factorial(5)

89
ASSIGNMENT

Write a function that would return a list of factorial values


for example
L=factorialList(3,6) # get factorial of 3,4,5 into L
# L=[ 6, 24, 120 ]

Note: We will use the recursive factorial function that we made

90
PART 4
Files and Lambda/Map/Zip/Filter
OBJECTIVES

By the end of this course, you should be able to understand:

 File operations

 Comprehension tools like : zip, map, filter and lambda

92
FILES

File opening modes:

r : read mode w : write mode a : append mode

fo=open(“abc.txt”, “r”) # opens in read mode

w and a modes would allow writing to the file

in w mode, an existing file would be truncated

in a mode, the writing would happen at end of an existing file

a mode would create the file if it was not existing

93
FILES

File opening modes for BINARY files:

rb : read mode wb : write mode ab : append mode

We understand files as either text files or binary files

Text files are usual files that we can open and read in a text editor

Binary files contain bytes structured into records as per the application

examples of binary files : pdf, doc, xls etc.

94
FILES

Additional to the opening mode, we can append a ‘+’ symbol

r+ rb+ : Open in read mode, and we can also update the contents

Note: After some content has been read from a file, any write command would update content at
the place where the file reference is at that point in time. So to update an information that has
been read, we may have to reposition the file reference location so that the update happens at
the correct location.

95
FILES

fo.write(s) # Writes the string s to the file

fo.writelines(L) # Writes the list L to the file

96
FILES

fo.tell() # gives current offset

fo.seek( offset ) # Go to offset ( starting from beginning )

fo.seek(offset,0) # same

fo.seek(offset, 1 ) # Go to offset, from current location

fo.seek(offset,2 ) # Go to offset from end

97
FILES - DEMO

Problem :

Read a text file and convert it to upper case and write to a second file.

98
ZIP

Iterates over multiple iterables in parallel

Returns tuples containing ith element of each iterable

Returned tuple elements are in order of the iterables

99
ZIP

L1=[1,2,3]

L2=[5,6,7]

for x in zip( L1, L2 ):

print(x)

# displays (1,5) (2,6) (3,7) each tuple on separate line

100
ZIP

zip returns an iterable

Returned list contains tuples

Tuple elements are in order of the input iterables

Length of each tuple is equal to the number of input iterables

Returned iterable is of length of the shortest input iterables

101
ZIP

Use of zip in comprehension:

nList=[“Anurag”,”Deepti”,”Jack”,”Hina”]

mList=[ 56, 78, 63, 82]

D={ name:mark for name,mark in zip( nList, mList ) }

102
MAP()

Applies a function to every element of input Iterable(s)

Results an iterable

Function should take same number of arguments as the number of input iterable(s)

103
MAP()

def sum(a,b):

return a+b

L1=[1,2,3]

L2=[5,6,7]

L=[ x for x in map( sum, L1, L2 ) ]

print(L)

104
MAP()

map runs for the longest iterable

If any iterable finishes earlier, None is used as the value

105
FILTER ( )

Returns an iterable

Takes an expression returning True or False

Applies this expression to input iterable

Selects elements that return True with the expression

106
FILTER ( )

def even(a):

if a%2==0: return True

else: return False

L1=[1,2,3,8,6,11,7]

L=[ x for x in filter( even, L1) ] # even is the function name

print( L ) # selects even values from a list

107
LAMBDA ( )

Similar to inline functions of C

Also called anonymous functions in python

108
LAMBDA ( )

lambda x : x * 5

This expression takes one argument x

Result of the expression is x * 5

So if we call this expression as follows:

( lambda x : x * 5 ) ( 7 )

This would result in 35

So the lambda expression is exhibiting properties of a function

109
LAMBDA ( )

square=lambda x : x * x

cube=lambda x : x * x * x

print( square(5) ) # prints 25

print( cube(3) ) # prints 27

110
LAMBDA ( )

Lambda finds a lot of use in map/filter applications

For instance we wanted to create a list by comprehension, that contains the sum of corresponding
elements of two lists

111
LAMBDA ( )

def sum(a,b):

return a+b

L1=[1,2,3]

L2=[5,6,7]

L=[x for x in map( sum, L1,L2) ]

print(L)

112
LAMBDA ( )

We could compact our code by replacing the map function with a lambda, thus eliminating the need of
the sum function

L1=[1,2,3]

L2=[5,6,7]

L=[ x for x in map( lambda a,b : a+b, L1 , L2 ) ]

print( L )

This also reduces the overhead of function calls happening earlier

113
LAMBDA ( ) - EXERCISE

def even(a):

if a%2==0: return True

else: return False

L1=[1,2,3,8,6,11,7]

L=[x for x in filter( even ,L1) ]

print(L)

# eliminate even function by using lambda

114
LAB EXERCISES

Consider a file containing temperature data one reading per line

a) Load this file into a list as float numbers

b) Do this through comprehension

c) Filter the contents of the file based on a condition without having an interim list ( all values
>25 )

Try to use filter and lambda where possible

115
LAB EXERCISES

Consider a CSV file made through excel, containing student data such as rollno, name, gender and marks obtained such
as:

R010,Anurag,M,78

R012,Disha,F,67

R013,Gurvinder,M,72

Load this information into appropriate data structure so that we can query on a roll no and retrieve the name, gender or
marks.

Further write a function to get a list of names who have obtained higher than certain marks.

L=getHigherThan(60)

116
LAB EXERCISES

We have two text files article.txt and a file ignore.txt

Load the words of ignore.txt into a set as the words to be ignored

Now we have to build a dictionary of words along with their frequencies as they occur in the
article.txt after we have excluded the ignore words.

The final result should be sorted word list which do not occur in the ignore word list. And we wish to
get their frequency and density. Density is (frequency/total words) * 100

117
OBJECTIVES

By the end of this part, you should be able to understand:

 Goals

 Principles

 Classes & Objects

 Encapsulation of data and methods

 Constructors, Destructors

 Operator Overloading

118
PART 5
Object Oriented Programming
GOALS

 Robustness

 Adaptability

 Reusability

120
PRINCIPLES

 Modularity

 Abstraction

 Encapsulation

121
OBJECT ORIENTED BASICS

class – Is a template

object – An instance of a class

122
CLASS

A class as well as its instance are namespaces

class simplest:

pass # do nothing statement in python

s=simplest( ) # create an instance of simplest

123
CLASS AS A NAMESPACE

class simplest:

pass # do nothing statement in python

s=simplest( ) # create an instance of simplest

s.rate=10 # attaches an attribute rate to the object

# makes a variable rate in the namespace

124
CLASS AS A NAMESPACE - DEMO

class point:

pass

p=point()

p.x=10 # makes a variable x in p

p.y=20 # makes a variable y in p

print(p.x,p.y) # accesses these variables from p

125
CONSTRUCTOR

A special function that is called at time of instantiation

Usually used to setup the attributes of the object

126
CONSTRUCTOR

class point:

def __init__( self , a , b):

self.x=a

self.y=b

p=point(10,30) # reference to p is sent as first argument

print(p.x,p.y)

127
METHODS OF A CLASS

Methods are functions defined in the class

A reference to the namespace is passed as first parameter

The method accesses the attributes through this namespace

128
GIVING DEFAULT VALUES

class point:

def __init__( self , a=0 , b=0):

self.x=a

self.y=b

p=point( )

print(p.x,p.y) # displays 0,0

129
ADDING A METHOD

class point:

def __init__( self , a=0 , b=0):

self.x=a

self.y=b

def display( self ):

print( self.x, self.y )

130
OUR CLASS USAGE

p=point(10,20) # instantiates p with 10,20

p.display( ) # displays value of x and y

131
DESTRUCTOR FUNCTION

def __del__(self):

The destructor function of a class is automatically called when an instantiated object of that class is
deleted from memory by a del statement or due to end of scope region

132
OPERATOR OVERLOADING

Allows the class objects to behave similar to standard python objects.

Almost all operators can be overloaded

133
OPERATOR OVERLOADING

def __add__( self, n ): # overloading +

p+x

For object p, the __add__ method is called and value of x is sent as parameter, similar to saying :

p.__add__(x)

134
OPERATOR OVERLOADING

q=p+x

Now completing the expression, we need the result on LHS

so this expression is same as saying:

q= p.__add__(x)

Hence the __add__( ) method should return an appropriate value as is required by your application
on the LHS

135
METHODS RELATED TO +

__add__ # p+x

__iadd__ # += ( in place add )

Where p is the object for whom the above functions are called.

136
METHODS RELATED TO -

__sub__

__isub__ # -= ( in place add )

137
OVERLOADING LOGICAL OPERATORS

def __lt__( self, n ):

if p < q :

( where p and q are objects )

The __lt__ function of p is called and q is sent as parameter

The expression is equivalent to p.__lt__(q)

So whatever is the result of the function that will be used for the condition.

138
OVERLOADING LOGICAL OPERATORS

__lt__ , __gt__ , __le__ , __ge__

__eq__ , __ ne__

139
DOCUMENTING CLASSES

If a string is the very first line of a class, then it populates an attribute __doc__

The value of this attribute can be viewed

In Interactive interface : help(classname)


In programming : using __doc__ attribute

140
DOCUMENTING CLASSES

class test:

“This is what this class is about”

def __init__(self):

# code for the constructor

print(test.__doc__)

141
LAB QUESTIONS

1) Develop a class called TextReader which works as follows:

t=TextReader(“article.txt”) # loads text from this file

t.text # contains the entire text as string

t.lines # contains the total no of lines in the file

t.wordcount # contains total no of words in file

t.display() # displays the entire text

t.wordlist() # returns a list of words ( no duplicates )

142
LAB QUESTIONS

2) In the class created in question 1, add a function getWC() to get the count of some words which
can be provided through a list sent as parameter. The usage of this function would be as
follows:

d=t.getWC(wordList)# wordList is a ‘list’ of words

# return a dictionary { word:count } using

# the words from the wordList

143
LAB QUESTIONS

3) In the class created in question 1, add the following functionality

t.save(“abc.txt”) # writes the text into this file

t.replace(“this”,”that”) # replaces word ‘this’ with ‘that’

t+=“hello” # adds word “hello” to content of t

144
ASSIGNMENT

Create a class called Line.

A Line object should have 2 points.

Each point is a Cartesian coordinate ( so use class point )

Implement a method called length( ) to get the length of line

implement if L1 < L2 # where L1 and L2 are line objects

import math
math.sqrt ( math.pow((x2-x1),2) + math.pow ((y2-y1),2) )

145
THANK YOU

146

You might also like