3.FPP Class Note Unit-Iii
3.FPP Class Note Unit-Iii
PYTHON 5 w
It opens the file to write only. It overwrites the file if previously
exists or creates a new one if no file exists with the same name.
UNIT-III The file pointer exists at the beginning of the file.
It opens the file to write only in binary format. It overwrites the file
6 wb if it exists previously or creates a new one if no file exists with the
same name. The file pointer exists at the beginning of the file.
Python provides the open() function which accepts two arguments, file name and open() : it is to open a file.
access mode in which the file is accessed. The function returns a file object Example: To open a file named "file.txt" (stored in the same directory) in read
which can be used to perform various operations like reading, writing, etc. mode.
#opens the file file.txt in read mode
fileptr = open("file1.txt","r")
The syntax to use the open() function is given below. if fileptr:
file object = open(<file-name>, <access-mode>, <buffering>) print("file is opened successfully")
The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.
Output:
Access
SN Description
mode <class '_io.TextIOWrapper'>
file is opened successfully
It opens the file to read-only. The file pointer exists at the
1 r beginning. The file is by default open in this mode if no access
mode is passed. close() : it is used to close an opened file.
It opens the file to read only in binary format. The file pointer
2 rb it is good practice to close the file once all the operations are done.
exists at the beginning of the file.
It opens the file to read and write both. The file pointer exists at The syntax to use the close() method is given below.
3 r+
the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file Ex: fileobject.close()
Example Example
# opens the file file.txt in read mode #open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r") fileptr = open("file.txt","r");
if fileptr: #stores all the data of the file into the variable content
print("file is opened successfully") content = fileptr.readline();
#closes the opened file # prints the type of the data stored in the file
fileptr.close() print(type(content))
read() : it is used to read data content of a file. It can also read data in binary format. #prints the content of the file
Syntax: print(content)
fileobj.read(<count>)
#closes the opened file
fileptr.close()
Here, the count is the number of bytes to be read from the file starting from the
beginning of the file. If the count is not specified, then it may read the content of
the file until the end. Output:
<class 'str'>
Consider the following example.
Hi, I am the file and being used as
Example
Looping through the file :
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file.txt","r");
By looping through the lines of the file, we can read the whole file.
#stores all the data of the file into the variable content
content = fileptr.read(9); Example
# prints the type of the data stored in the file
#open the file.txt in read mode. causes an error if no such file exists.
print(type(content))
fileptr = open("file.txt","r");
#prints the content of the file
#running a for loop
print(content)
for i in fileptr:
print(i) # i contains each line of the file
#closes the opened file
fileptr.close()
Output:
Output:
Hi, I am the file and being used as
an example to read a
<class 'str'>
Hi, I am file in python.
The readline() method reads the lines of the file from the beginning, i.e., if we To write some text to a file, we need to open the file using the open method with
use the readline() method two times, then we can get the first two lines of the one of the following access modes.
file.
a: It will append the existing file. The file pointer is at the end of the file. It Consider the following example.
creates a new file if no file exists.
Example
w: It will overwrite the file if any file exists. The file pointer is at the beginning of #open the file.txt in read mode. causes error if no such file exists.
the file. fileptr = open("file2.txt","x");
Consider the following example. print(fileptr)
Example 1
#open the file.txt in append mode. Creates a new file if no such file exists.
if fileptr:
fileptr = open("file.txt","a"); print("File created successfully");
Output:
#appending the content to the file File created successfully
fileptr.write("Python is the modern day language. It makes things so simple.")
Example 2 The with statement is useful in the case of manipulating the files.
#open the file.txt in write mode.
fileptr = open("file.txt","w"); Syntax:
with open(<file name>, <access mode>) as <file-pointer>:
#overwriting the content of the file
fileptr.write("Python is the modern day language. It makes things so simple.")
It is always suggestible to use the with statement in the case of files
because, It doesn't let the file to be corrupted.
#closing the opened file
fileptr.close(); Example:
Now, we can check that all the previously written content of the file is overwritten with the
new text
with open("file.txt",'r') as f:
content = f.read();
print(content)
Creating a new file
tell():
The new file can be created by using one of the following access modes
with the function open() method which is used to print the byte number at which the file pointer
exists. Consider the following example.
x: it creates a new file with the specified name. It causes an error a file
Example
exists with the same name.
# open the file file2.txt in read mode
a: It creates a new file with the specified name if no such file exists. It
appends the content to the file if the file already exists with the specified fileptr = open("file2.txt","r")
name.
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.
#reading the content of the file
content = fileptr.read();
print(txt.read())
#after the read operation file pointer modifies. tell() returns the location of
the fileptr. file_read('test.txt')
print("After reading, the filepointer is at:",fileptr.tell())
Output: Program1: to read a sample file from the present working directory by
The filepointer is at byte : 0 default:
After reading, the filepointer is at 26 fileptr = open(r"c:\\users\\mural\\file1.txt","r")
if fileptr:
seek(): This method which enables us to modify the file pointer position print("file is opened successfully")
externally. content = fileptr.read();
The seek() method accepts two parameters: print(type(content))
offset: It refers to the new position of the file pointer within the file. print(content)
fileptr.close()
from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference o/p:
position. If it is set to 1, the current position of the file pointer is used as file is opened successfully
the reference position. If it is set to 2, the end of the file pointer is used as <class 'str'>
the reference position. hello this is a sample file
this is 2nd line
Consider the following example. this is 3rd line or sentence
Example program2: to open a file and reading line by line and then display it.
# open the file file2.txt in read mode fileptr = open("file1.txt","r");
fileptr = open("file2.txt","r") content = fileptr.readline();
print(content)
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell()) content = fileptr.readline();
print(content)
#changing the file pointer location to 10.
fileptr.seek(10); content = fileptr.readline();
print(content)
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell()) #closes the opened file
fileptr.close()
Output:
o/p:
hello this is a sample file
The filepointer is at byte : 0
After reading, the filepointer is at 10 this is 2nd line
this is 3rd line or sentence
Exercises:
Program3: reading all the content using loop control:
1. Write a Python program to read an entire text file. fileptr = open("file1.txt","r");
def file_read(fname):
txt = open(fname) #running a for loop
for i in fileptr:
print(i) Program7: write a program to input a sample paragraph from user.
else: fileptr = open("file2.txt","a");
print("EOF") fileptr.write(input("enter a sentence"))
o/p: fileptr.close();
hello this is a sample file with open("file2.txt",'r') as f:
this is 2nd line content = f.read();
this is 3rd line or sentence print(content)
EOF fileptr.close()
Example
import os; Object Oriented Programming:
#creating a new directory with the name new
It allows to create their own objects that have methods and attributes.
os.mkdir("new")
The commonly repeated tasks and objects can be defined with OOP to create
code that is more usable.
Changing the current working directory class: the basic way to define an object is using class keyword.
Major principles of OOP system are:
The chdir() method is used to change the current working directory to a specified 1) object
directory. 2) class
3) method
The syntax to use the chdir() method is given below. 4) inheritance
5) polymorphism
6) data abstraction
1. chdir("new-directory")
7) encapsulation
Example
import os; class: A class is a blue print for the object.
It is a virtual entity. It comes into existence when its object is created.
Syntax: * Here x is an object which allows to call a function. Such as x.display(). When
class classname: an object calls its method the object itself is passed as the 1st argument to it. So,
#statements or members x.display() is converted as:
Ex1:Create a class named MyClass, with a property named x: emp.display(x)
class MyClass:
x=5 So, for this reason the 1st argument of the function in the class must be the
object itself referred by self-variable.
Ex4:
Object: It is an instance of a class class lib:
Syntax:
Object name=<class name> (<arguments>)
bookid=1
Ex1: Now we can use the class named myClass to create objects. bookname="a"
Create an object named p1, and print the value of x: bookauthor="b"
p1 = MyClass() bookcost=1.1
print(p1.x) bookqty=1
def accept(self):
ex1: bookid=int(input("enter book id"))
class myclass: self.bookname=input("enter book name")
x=25 self.bookauthor=input("enter book author")
obj=myclass() self.bookcost=float(input("enter book cost"))
print(obj.x) self.bookqty=int(input("enter quantity"))
def display(self):
ex2: print("the book details are\n")
class emp: print(self.bookid,self.bookname,self.bookauthor, self.bookcost,self.bookqty)
empid=1
ename="alok" obj=lib()
def display(self): obj.accept()
print(self.empid,self.ename) obj.display()
obj=emp()
obj.display() ex5:wap to create a class having member data a,b,c and member functions:
obj.empid=2 accept(), sum() and display()
obj.ename="sam" class myclass:
obj.display() a=0
b=0
o/p: c=0
1 alok result=0
2 sam
def accept(self, x,y,z):
self.a=x
Ex3: self.b=y
class emp: self.c=z
id=1 def sum(self):
name="abc" self.result=self.a+self.b+self.c
def display(self): def display(self):
print(self.id, self.name) print("sum is",self.result)
x=emp() obj=myclass()
x.display() n1=int(input("enter 1st no"))
n2=int(input("enter 2nd no"))
o/p: n3=int(input("enter 3rd no"))
1 abc
print("addition is",obj.add())
obj.accept(n1,n2,n3)
obj.sum() o/p:
obj.display() enter 1st no12
enter 2nd no13
addition is 25
Example: solution:
class person: class product:
def input(obj, name, age): pno=0
obj.name = name pname=" "
obj.age = age cost=qty=amt=0
def input(self,p,q,r,name):
def myfunc(abc): self.pno=p
print("Hello my name is " + abc.name)
self.cost=q
p1=person()
self.qty=r
p1.input(“murali”,32) self.pname=name
p1.myfunc() def calc(self):
self.amt=self.cost*self.qty
when a function is called using the object, actually it is passed as the 1st def display(self):
argument to the function. print("product no is :",self.pno)
Ex: print("product name is :", self.pname)
p1.myfunc() print("product cost is : ",self.cost)
is modified by interpreter as: print("product quantity is :", self.qty)
person.myfunc(p1) print("product amount is :",self.amt)
So, for this reason the 1st argument of the function in class must be the object ob=product()
itself referred by self variable. p=int(input("product no"))
q=int(input("product quantity"))
Example2: input two numbers and perform addition r=int(input("product cost"))
class A: name=input("product name")
def input(self, x,y): ob.input(p,q,r,name)
self.a=x ob.calc() # product.calc(ob)
self.b=y ob.display() # product.display(ob)
def add(self):
return self.a+self.b;
def display(self): o/p:
product no1
print(self.a, self.b); product quantity25
product cost10
obj=A() product namelux
t1=int(input("enter 1st no")) product no is :1
product name is : lux
t2=int(input("enter 2nd no")) product cost is : 25
obj.input(t1,t2) or it means A.input(obj,t1,t2) product quantity is : 10
product amount is : 250 count=0
def _ _init_ _(self):
python constructor: student.count=student.count+1
A constructor is a special type of method which is used to initialize the object s1.student()
members of the class. s2.student()
s3.student()
creating the constructor in python: print(“no. of students are “,student.count)
In python the method _ _init_ _ simulates the constructor of the class. This o/p:
method is called automatically when the class is initiated. no. of students are 3
So, the __init__ function used to initialize the class attributes. So, every class
should have a constructor. Parameterized constructor:
Ex: The constructor needs parameters to be passed when it is invoked.
class emp:
def __init __(self, name, id): Example1:
self.id=id Create a class named Person, use the __init__() function to assign values for
self.name=name name and age:
def display(self): class Person:
print(self.id, self.name) def __init__(self, name, age):
emp1=emp(“john”,101) self.name = name
emp2=emp(“David”,102) self.age = age
emp1.display()
def myfunc(self):
emp2.display()
print("Hello my name is " + self.name)
o/p: p1 = Person("murali", 32)
101 john p1.myfunc()
102 david
example2: write a program to store N persons details using class concept.
Constructors can be of two types: class student:
1) non-parameterized constructor def __init__(self,name,age):
2) parameterized constructor self.name=name
self.age=age
# def display(self):
Non-parameterized constructor: # print(self.name,self.age)
A constructor invoked without parameters during declaring an object. list1=[]
Example1:
class student: for i in range(1,4):
n=input("enter name")
def __init__(self):
a=int(input("enter age"))
print(“it is not parametrised constructor”) # obj=student(n,a)
def show(self, name): list1.append(student(n,a))
print(“hello”,name) for obj in list1:
s1=student() print(obj.name,obj.age)
s1.show(“john”)
o/p: o/p:
This is not a parametrized constructor enter nameaa
enter age1
Hello John enter namebb
enter age2
Example2: enter namecc
Counting the no. of objects of a class. enter age3
aa 1
class student: bb 2
cc 3 print("age attribute exist?",hasattr(s,"age"))
o/p:
python built-in class functions: age attribute exist? True
age attribute exist? False
They are:
getattr(obj,name,default)
It is used to access the attribute of the object. built-in class attributes:
setattr(obj,name,value) along with other attributes python also contains some built in class attributes
it is used to set a particular value to the specific attribute of an object. If attribute which provides information about the class. They are accessed using objects.
does not exist, then it would create. They are:
delattr(obj,name) _ _dict_ _
it is used to delete a specific attribute. It is dictionary containing the class’s namespace
hasattr(obj,name) _ _doc_ _
it returns TRUE if the object contains some specific attribute. It contains a string which have the class document
Example1: _ _name_ _
class student: It is used to access the class name.
def __init__(self,name,id ,age): _ _module_ _
self.name=name It is used to access the module in which the class is defined.
self.id=id _ _bases_ _
self.age=age It contains a tuple including all base classes. It is possibly an empty tuple.
s=student("john",101,22)
print(getattr(s,"id")) Example1:
print(getattr(s,"name")) class student:
o/p: def __init__(self,name,age):
101 self.name=name
john self.age=age
def display(self):
example2: print("name %s and age %d"%(self.name,self.age))
class student: s=student("john",21)
def __init__(self,name,id ,age): print(s._ _dict_ _)
self.name=name print(s._ _doc_ _)
self.id=id print(s._ _module_ _)
self.age=age
s=student("alok",101,21) o/p:
setattr(s,"age",25) {'name': 'john', 'age': 21}
print(getattr(s,"name")) None
print(getattr(s,"age")) _ _main_ _
o/p:
alok
25
_ _name_ _ (A Special variable) in Python
Example3: Since there is no main() function in Python, when the command to run a python
class student: program is given to the interpreter, the code that is at level 0 indentation is to be
def __init__(self,name,id ,age): executed. However, before doing that, it will define a few special variables.
self.name=name __name__ is one such special variable. If the source file is executed as the main
self.id=id program, the interpreter sets the __name__ variable to have a value “__main__”.
self.age=age If this file is being imported from another module, __name__ will be set to the
s=student("alok",101,21) module’s name.
print("age attribute exist?",hasattr(s,"age")) __name__ is a built-in variable which evaluates to the name of the current
delattr(s,"age") module. Thus it can be used to check whether the current script is being run on
its own or being imported somewhere else by combining it with if statement, as These are the variables which are common for all instances or objects of a class.
shown below. Example:
Class employes:
Consider two separate files File1 and File2. Count=0
Def __init__(self, name, salary):
# File1.py Self.name=name
Self.salary=salary
print "File1 __name__ = %s" %__name__
Employee.count=employee.count+1
Def displaycount(self):
if __name__ == "__main__":
Print(“total employees”,employee.count)
print "File1 is being run directly"
else: Def display(self):
Print(self.name, self.salary)
print "File1 is being imported"
o/p:
# File2.py
import File1 The count variable is a class variable whose value is shared among all objects of
the class. It can be accessed using class name or using object either inside or
outside the class.
print "File2 __name__ = %s" %__name__
Emp1=employee(“Zam”,2000)
if __name__ == "__main__":
print "File1 is being run directly" Emp2=employee(“mani”,5000)
Emp1.display()
else:
Emp2.display()
print "File1 is being imported"
Print(“total employees “,employee.count)
o/p:
Now the interpreter is given the command to run File1.py.
python File1.py
Output : destructor:
File1 __name__ = __main__ A class can implement a special method __del__() called a destructor. It is
File1 is being run directly invoked when the instance or object of a class is to be destroyed.
Example1:
class point:
And then File2.py is run. def __init__(self, x=1, y=2):
python File2.py self.x=x
Output : self.y=y
File1 __name__ = File1 print("created")
File1 is being imported def __del__(self):
File2 __name__ = __main__ print(point, "destroyed")
File2 is being run directly p1=point()
p2=p1
As seen above, when File1.py is run directly, the interpreter sets the __name__ p3=p1
variable as __main__ and when it is run through File2.py by importing, the print(p1.x,p1.y)
__name__ variable is set as the name of the python script, i.e. File1. Thus, it can del p1
be said that if __name__ == “__main__” is the part of the program that runs print(p2.x,p2.y)
when the script is run from the command line using a command like del p2
python File1.py. print(p3.x,p3.y)
del p3
Class variables: o/p:
created Class baseclass:
12 Body of the baseclass
12 Class derivedclass(baseclass):
Body of the derivedclass
12
Types of inheritance:
<class '__main__.point'> destroyed 1) single inheritance
2) multiple inheritance
The destroyer will be called after the program ended. When all the references to 3) multilevel inheritance
object are deleted.
The __del__ () method is the destructor method which is used for garbage single inheritance:
collection for handling memory management automatically. It is called
automatically when all the references to the object has been deleted. In python, a derived class can inherit base class by just mentioning the base in
By using del keyword we delete the references, there by destructor is invoked the bracket after the derived class name. Consider the following syntax to inherit
automatically. a base class into the derived class.
Example2:
class emp:
def __init__(self):
print("employee initialized: constructor called")
def display(self):
print("display method executing")
def __del__(self):
print("destructor called")
def create_obj():
print("making object") Syntax
inobj=emp()
print("function ends")
class derived-class(base class):
return inobj
<class-suite>
print("calling create_obj function")
example:
outobj=create_obj()
class base:
outobj.display()
def __init__(self, fname, lname):
del outobj
self.firstname = fname
print("end")
self.lastname = lname
def printname(self):
o/p:
print(self.firstname, self.lastname)
calling create_obj function
making object
#Use the base class to create an object, and then execute the #printname
employee initialized: constructor called
method:
function ends
x = Person("John", "Doe")
display method executing
x.printname()
destructor called
class Student(Person):
end
def disp(self):
print(“derived class function”)
python inheritance: x = Student("Mike", "Olsen")
It enables us to define a class that takes all the functionality from parent class. Here the x.printname()
parent class is also called base class and the new class is called derived class. x.disp()
Syntax: o/p:
John Doe print("Animal Speaking")
Mike Olsen
Derived class function #The child class Dog inherits the base class Animal
Example2: class Dog(Animal):
class Animal: def bark(self):
def speak(self): print("dog barking")
print("Animal Speaking")
#child class Dog inherits the base class Animal #The child class Dogchild inherits another child class Dog
class Dog(Animal): class DogChild(Dog):
def bark(self): def eat(self):
print("dog barking") print("Eating bread...")
d = Dog()
d.bark() d = DogChild()
d.speak() d.bark()
d.speak()
o/p: d.eat()
dog barking
Animal Speaking o/p:
dog barking
Animal Speaking
Python Multi-Level inheritance Eating bread...
Syntax Syntax
class B:
Case 1 def process(self):
print('B process()')
This is a simple case where we have class C derived from both A and B. When class C(A, B):
method process() is called with object of class C then process() method in class pass
A is called.
obj = C()
obj.process()
Case 4
When you run the above code, it prints the following:
A process() Now, lets change the hierarchy. We create B and C from A and then D from B
Python calls process() method in class A. According to MRO, it searches and C. Method process() is present in both A and C.
A first and then B. So if method is found in A then it calls that method.
However, if we remove process() method from class A then process()
method in class B will be called as it is the next class to be searched
according to MRO.
*The ambiguity that arises from multiple inheritance is handled by
Python using MRO.
Case 3
class A:
def process(self):
In this case, we create D from C and B. Classes C and B have process() method print('A process()')
and as expected MRO chooses method from C. Remember it goes from left to
right. So it searches C first and all its super classes of C and then B and all its class B(A):
super classes. We can observe that in MRO of the output given below. pass
class C(A):
def process(self):
print('C process()')
class D(B,C):
pass
o/p:
the data are 10 20
the data are A B
class A: ex:
def process(self):
print('A process()')
#!/usr/bin/env python
Output:
The number of employees 2 Output
AttributeError: 'Employee' object has no attribute '__count'
Traceback (most recent call last):
File "F:/NETJS/NetJS_2017/Python/Test/Test.py", line 9, in <module>
OPERATOR OVERLOADING: print(p1+p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'
#using + operator with integers to add them Overloading ‘+’ operator to work with custom objects
print(5 + 7)
#using + operator with Strings to concatenate them
print('hello ' + 'world') class Point:
a = [1, 2, 3] def __init__(self, x, y):
b = [4, 5, 6] self.x = x
# using + operator with List to concatenate them self.y = y
print(a + b) def __add__(self, other):
return self.x + other.x, self.y + other.y
Output p1 = Point(1, 2)
p2 = Point(3, 4)
12 print(p1+p2)
hello world
[1, 2, 3, 4, 5, 6]
Output
When is Operator overloading required? (4, 6)
if you want to use operator with custom objects. For example if you want to use What actually happens is that, when you do p1 + p2, Python will call p1.__add__(p2)
‘+’ operator with your custom class objects. which in turn is Point.__add__(p1,p2). Similarly, we can overload other operators as
well. The special function that we need to implement is tabulated below.
In the example there is a class Point with two variables x and y. Two objects of
Point class are instantiated and you try to add those objects with the intention to
Operator Overloading Special Functions in Python
add the data (p1.x + p2.x) and (p1.y + p2.y) of these two objects.
Operator Expression Internally
class Point: Addition p1 + p2 p1.__add__(p2)
def __init__(self, x, y):
self.x = x Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2) __ifloordiv__(self, Division with integer result, discarding any
//=
Power p1 ** p2 p1.__pow__(p2) other) fractional part
p1 = Point(12)
Comparison Operator Overloading in Python p2 = Point(5)
print(p1*p2)
Operator Expression Internally
Less than p1 < p2 p1.__lt__(p2) Output
Less than or equal to p1 <= p2 p1.__le__(p2)
Equal to p1 == p2 p1.__eq__(p2) 60
O/P:
Transpose a Matrix
X = [[1,2],
[4,5],
[7,8]]
Result = [[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
Multiply Two Matrices print(r)
X = [[1,2,3], Output:
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
Result = [[0,0,0],
[0,0,0],
[0,0,0]]
NumPy Arrays
NumPy is a package for scientific computing which has support for
a powerful N-dimensional array object.
import numpy as np
a = np.array([1, 2, 3])
print(a) # Output: [1, 2, 3]
print(type(a)) # Output: <class 'numpy.ndarray'>
[[1 2 3]
[3 4 5]]
[[1.1 2. 3. ]
[3. 4. 5. ]]
import numpy as np
'''
Product Output:
[[ 1 2 3]
[ 1 1 -3]]
Two types of multiplication or product operation can be done on NumPy matrices '''
Syntax errors or compile time errors are the errors due to which your program except exception1:
fails to compile. Such errors are detected at the compile time itself, file name, block1 code
line number and error description is displayed so you know where to look for the except exception2:
error and how to correct it.
block2 code
For example if you don’t write colon after if statement- Finally:
Python RegEx Square brackets specifies a set of characters you wish to match.
Here, [abc] will match if the string you are trying to match contains any of the a,
Expression String Matched?
b or c.
abs No match
alias Match You can also specify a range of characters using - inside square brackets.
^a...s$ abyss Match
Alias No match [a-e] is the same as [abcde].
An abacus No match [1-4] is the same as [1234].
[0-39] is the same as [01239].
Python has a module named re to work with RegEx. Here's an example: You can complement (invert) the character set by using caret ^ symbol at the
start of a square-bracket.
Ex:
import re [^abc] means any character except a or b or c.
[^0-9] means any non-digit character.
pattern = '^a...s$' . - Period
test_string = 'abhas' A period matches any single character (except newline '\n').
result = re.match(pattern, test_string)
Expression String Matched?
if result:
print("Search successful.") a No match
else: ac 1 match
..
print("Search unsuccessful.") acd 1 match
o/p: acde 2 matches (contains 4 characters)
Search Successful
^- Caret ?- Question Mark
The caret symbol ^ is used to check if a string starts with a certain The question mark symbol ? matches zero or one occurrence of the
character. pattern left to it.
\b - Matches if the specified characters are at the beginning or end of a word. Expression String Matched?
1ab34"50 3 matches (at 1ab34"50)
Expression String Matched? \D
1345 No match
football Match
\bfoo a football Match
afootball No match w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-
the foo Match zA-Z0-9_]. By the way, underscore _ is also considered an alphanumeric character.
foo\b the afoo test Match
the afootest No match Expression String Matched?
12&": ;c 3 matches (at 12&": ;c)
\w
\B- Opposite of \b. Matches if the specified characters are not at the beginning or %"> ! No match
end of a word.
The re module offers a set of functions that allows us to search a string for a match:
re.findall()
re.sub()
The re.findall() method returns a list of strings containing all matches.
The syntax of re.sub() is:
Example 1: re.findall()
re.sub(pattern, replace, string)
# Program to extract numbers from a string The method returns a string where matched occurrences are replaced with the content of
replace variable.
import re
Example 3: re.sub()
string = 'hello 12 hi 89. Howdy 34'
pattern = '\d+'
# Program to remove all whitespaces
result = re.findall(pattern, string) import re
print(result)
# multiline string
# Output: ['12', '89', '34'] string = 'abc 12\
de 23 \n f45 6'
import re
Special Sequences
string = "Python is fun"
A special sequence is a \ followed by one of the characters in the list below, and has a
# check if 'Python' is at the beginning special meaning:
match = re.search('\APython', string)
\ Signals a special sequence (can also be used to escape special characters) "\d" Returns a match where the
. Any character (except newline character) "he..o" string contains any word
\w characters (characters from "\w" \w
^ Starts with "^hello"
a to Z, digits from 0-9, and
$ Ends with "world$" the underscore _ character)
* Zero or more occurrences "aix*" Returns a match where the
+ One or more occurrences "aix+" \W string DOES NOT contain "\W" \W
{} Exactly the specified number of occurrences "al{2}" any word characters
| Either or "falls|stays" \Z Returns a match if the "Spain\Z" \Z
specified characters are myit = iter(mytuple)
at the end of the string
print(next(myit))
print(next(myit))
Sets print(next(myit))
o/p:
A set is a set of characters inside a pair of square brackets [] with a special meaning: apple
banana
Character Description Example
cherryTry it
Returns a match where one of the specified characters (a, r, or
[arn]
n) are present
example2:
Returns a match for any lower case character, alphabetically
[a-n]
between a and n Strings are also iterable objects, containing a sequence of characters:
[^arn] Returns a match for any character EXCEPT a, r, and n
Returns a match where any of the specified digits ( 0, 1, 2, or 3) mystr = "banana"
[0123]
are present myit = iter(mystr)
[0-9] Returns a match for any digit between 0 and 9
print(next(myit))
[0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
print(next(myit))
Returns a match for any character alphabetically between a print(next(myit))
[a-zA-Z]
and z, lower case OR upper case
print(next(myit))
In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means:
[+]
return a match for any + character in the string
print(next(myit))
print(next(myit))
o/p:
Match(): b
It contains: span(), string(), group() a
span() : It returns the tuple containing the starting and end position of the match. n
string() : it returns a string passed into the function a
group() : the part of the string is returned where the match is found. n
a
Example1: The __iter__() method acts similarly, we can do same operations , but it must always
mytuple = ("apple", "banana", "cherry") return the iterator object itself.
To prevent the iteration, we can use the StopIteration statement.
Example2: Create an iterator that returns numbers, starting with 1, and each In the __next__() method, we can add a terminating condition to raise an error.
sequence will increase by one (returning 1,2,3,4,5 etc.):
Example1:without StopIteration
class MyNumbers: class MyNumbers:
def __iter__(self): def __iter__(self):
self.a = 1 self.a = 1
return self return self
def __next__(self):
x = self.a def __next__(self):
self.a += 1 if self.a<=5:
return x x = self.a
self.a += 1
myobj= MyNumbers() return x
myiter = iter(myobj) myobj= MyNumbers()
print(next(myiter)) myiter = iter(myobj)
print(next(myiter))
print(next(myiter)) for i in range(10):
print(next(myiter)) print(next(myiter), end=",")
print(next(myiter)) o/p:
1,2,3,4,5,None,None,None,None,None,
o/p:
1
2
3
Example2:
4
5 Stop after 10 iterations:
Example3:
class MyNumbers: class MyNumbers:
def __iter__(self): def __iter__(self):
self.a = 1 self.a = 1
return self return self
def __next__(self): def __next__(self):
x = self.a
self.a += 1
if self.a <= 10:
return x x = self.a
self.a += 1
myobj= MyNumbers() return x
myiter = iter(myobj) else:
raise StopIteration
for i in range(10):
print(next(myiter), end=",") myclass = MyNumbers()
o/p:
myiter = iter(myclass)
1,2,3,4,5,6,7,8,9,10,
for x in myiter:
print(x,end=" ")
o/p:
******StopIteration 1 2 3 4 5 6 7 8 9 10
yield vs. return
The yield statement is responsible for controlling the flow of the generator
function.
GENERATOR
It pauses the function execution by saving all states and yielded to the caller.
Generators are the functions that return the traversal object and used to create iterators. Later it resumes execution when a successive function is called.
It traverses the entire items at once.
There is a lot of complexity in creating iteration in Python; we need to implement We can use the multiple yield statement in the generator function.
__iter__() and __next__() method to keep track of internal states. It is a lengthy process
to create iterators. The return statement returns a value and terminates the whole function and
only one return statement can be used in the function.
That's why the generator plays an essential role in simplifying this process. If there is no
value found in iteration, it raises StopIteration exception.
Using multiple yield Statement:
How to Create Generator function in Python? We can use the multiple yield statement in the generator function. Consider the
following example.
It is similar to the normal function defined by the def keyword and uses a yield
def multiple_yield():
keyword instead of return. str1 = "First String"
yield str1
Or we can say that if the body of any function contains a yield statement, it
automatically becomes a generator function. str2 = "Second string"
yield str2
Example: Write a program to print the table of the given number using the str3 = "Third String"
generator. yield str3
obj = multiple_yield()
def table(n): print(next(obj))
for i in range(1,11): print(next(obj))
yield n*i print(next(obj))
i = i+1
Output:
for x in table(15):
print(x) First String
Second string
o/p: Third String
15
30 Ex2: # A simple generator function
45 def my_gen():
60 n=1
75 print('This is printed first')
90
# Generator function contains yield statements
105
120
yield n
135
150 n += 1
print('This is printed second')
yield n
n += 1 StopIteration exception is raised automatically when the function
print('This is printed at last') terminates.
yield n
def __iter__(self):
Python Generators with a Loop self.n = 0
return self
Normally, generator functions are implemented with a loop having a suitable terminating
condition. def __next__(self):
an example of a generator that reverses a string. if self.n > self.max:
def rev_str(my_str): raise StopIteration
length = len(my_str)
for i in range(length-1,-1,-1): result = 2 ** self.n
yield my_str[i] self.n += 1
return result
# For loop to reverse the string x=powtwoiter(3)
myit=iter(x)
for c in rev_str("hello"): print(next(myit))
print(c) print(next(myit))
o/p: o/p:
o 1
l 2
l
e
h Now lets do the same using a generator function.
# Output: 9
Example of list comprehension:
print(next(a))
List comprehension consists of an expression followed by for statement inside # Output: 36
square brackets. print(next(a))
Here is an example to make a list with each item being increasing power of 2. # Output: 100
print(next(a))
pow2 = [2 ** x for x in range(10)]
# Output: StopIteration
# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)
next(a)
pow2 = []
for x in range(10):
Python Decorator
pow2.append(2 ** x)
"In Decorators, functions are passed as an argument into another function and
A list comprehension can optionally contain more for or if statements. An optional then called inside the wrapper function."
if statement can filter out items for the new list. Here are some examples.
It is also called meta programming where a part of the program attempts to
>>> pow2 = [2 ** x for x in range(10) if x > 5] change another part of program at compile time.
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1] Before we go for decorator, ffirst you have to know or remember that function names
>>> odd are references to functions and that we can assign multiple names to the same function:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Ex1:
def func1(msg):
The major difference between a list comprehension and a generator print(msg)
expression is that while list comprehension produces the entire list, func1("Hii")
generator expression produces one item at a time. func2 = func1
func2("Hii")
Example1: del func1
# Initialize the list func1(“hello”) #error
my_list = [1, 3, 6, 10] func2(“hello”)
o/p:
Hii return x-1
Hii def operator(func, x):
temp = func(x)+x
Ex2: return temp
>>> def succ(x): print(operator(sub,10))
... return x + 1 print(operator(add,20))
...
Output:
>>> successor = succ
19
>>> successor(10)
41
11
>>> succ(10)
11 Python decorators allows us to decorate a function.
It allows you to take on extra functionality to an existing function.
In the above program, we need to understand the following concept of the Ex:
function: def simple_function():
#do something
The function can be referenced and passed to a variable and returned
To add more functionality to this function if we require, then there is a problem.
from other functions as well.
Here we have two options:
The functions can be declared inside another function and passed as an
1) Add extra code to the old function
argument to another function.
2) Create a new function by copying the old code and then adding
new code to that.
Inner Function But again if we want to remove the extra functionality then, we need to delete
them manually or check for the old function if it is exist.
Python provides the facility to define the function inside another function. These
types of functions are called inner functions. Consider the following example: If we have some ON/OFF switch for adding functionality to the existing function
then it is called decorator.
def func():
print("We are in first function") For it we use the @ operator at the top of the original function.
def func1(): Example:
print("This is first child function") @some_decorator
def func2(): def simple_function():
print(" This is second child function") #dop something
func1()
func2()
Now let us go through the steps of manually building a decorator to know what
func()
@ operator is doing behind the scene.
Output: Ex1:
def func():
We are in first function return 1;
This is first child function
This is second child function
func()
o/p:
1
function that accepts other function as an argument is also called higher order
function. Consider the following example:
If we type:
func
def add(x): then the error displayed as:
return x+1
< function__main__.func>
def sub(x):
result = "It's " + str(celsius2fahrenheit(t)) + " degrees!"
So, it is showing error message that we have a function func return result
Ex2: print(temperature(20))
def hello(): The output:
return “hello” It's 68.0 degrees!
hello()
o/p:
hello
passing a function into another
if we type: we can pass functions - or better "references to functions" - as parameters to a
greet=hello function. We will demonstrate this in the next simple example:
greet() def g():
print("Hi, it's me 'g'")
o/p: print("Thanks for calling me")
hello
def f(func):
Here actually greet is pointing to the function object hello(). print("Hi, it's me 'f'")
print("I will call 'func' now")
Here even we delete hello(), then also the greet() will be exist and will func()
work.
Ex: f(g)
del hello
hello() # it will error The output looks like this:
greet() Hi, it's me 'f'
I will call 'func' now
Hi, it's me 'g'
o/p: Thanks for calling me
hello
def g():
define a function inside another. print("Hi, it's me 'g'")
print("Thanks for calling me")
def f(): def f(func):
print("Hi, it's me 'f'")
def g(): print("I will call 'func' now")
print("Hi, it's me 'g'") func()
print("Thanks for calling me") print("func's real name is " + func.__name__)
print("This is the function 'f'") f(g)
print("I am calling 'g' now:")
g()
The output explains once more what's going on:
Hi, it's me 'f'
I will call 'func' now
Hi, it's me 'g'
f()
Thanks for calling me
func's real name is g
We will get the following output, if we start the previous program:
This is the function 'f'
I am calling 'g' now: EXAMPLE USING PYTHON DECORATOR:
Hi, it's me 'g'
Thanks for calling me
Ex1:consider a function and observe the output
def newfun(original):
Another example using "proper" return statements in the functions:
def temperature(t):
def func():
def celsius2fahrenheit(x): print("extra code before");
return 9 * x / 5 + 32 original();
print("extra code after"); extra code after
return func
Note: When we call the original() function actually this function is supplied as
def original(): argument to the newfun(), as because we have written @followed by decorator
print("I m original") function newfun.
original() So, now we can go for switch ON or OFF to the statement written with @
Eg:
o/p: @newfun
I m original Or
#@newfun
Ex2: observe the 2nd output
def newfun(original): Decorators are mainly used in web frame work applications and other software
def func(): development fields.
print("extra code before");
original();
print("extra code after");
return func
def original():
print("I m original")
d=newfun(original)
d()
o/p:
extra code before
I m original
extra code after
Now the function which needed to be decorated i.e: original() can be modified by
prefix one statement as: @newfun
Ex3:
def newfun(original):
def func():
print("extra code before");
original();
print("extra code after");
return func
@newfun
def original():
print("I m original")
original() # d=newfun(original)
o/p:
extra code before
I m original