0% found this document useful (0 votes)
38 views37 pages

Python UNIT4 Notes

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

Python UNIT4 Notes

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

Python Third Chapter Notes - GSM

UNIT 4

Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which can contain data and code: data in the form of fields (often known
as attributes or properties), and code, in the form of procedures (often known as methods).
A feature of objects is that an object's own procedures can access and often modify the data
fields of itself (objects have a notion of this or self ). In OOP, computer programs are
designed by making them out of objects that interact with one another. OOP languages are
diverse, but the most popular ones are class-based, meaning that objects
are instances of classes, which also determine their types.
Python is a multi-paradigm programming language. It supports different programming
approaches.

One of the popular approaches 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:

A parrot is can be an object,as it has the following properties:

 name, age, color as attributes


 singing, dancing as 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:

Class
A class is a blueprint for the object.

We can think of class as a 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, a parrot is an
object.

Jain College of BBA BCA & Commerce, Belagavi Page 1


Python Third Chapter Notes - GSM

The example for class of parrot can be :

class Parrot:

pass

Here, we use the 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 an object of class Parrot.

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

Example 1: Creating Class and Object in Python

class Parrot:

# class attribute
species = "bird"

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

Jain College of BBA BCA & Commerce, Belagavi Page 2


Python Third Chapter Notes - GSM

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

Output

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

In the above program, we created a class with the name Parrot. Then, we define attributes.
The attributes are a characteristic of an object.
These attributes are defined inside the __init__ method of the class. It is the initializer method
that is first run as soon as the object is created.
Then, we create instances of the Parrot class. Here, blu and woo are references (value) to our
new objects.
We can access the class attribute using __class__.species. Class attributes are the 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.

Python Constructor

A constructor is a special type of method (function) which is used to initialize the instance
members of the class.

Constructors can be of two types.

1. Parameterized Constructor
2. Non-parameterized Constructor

Jain College of BBA BCA & Commerce, Belagavi Page 3


Python Third Chapter Notes - GSM

Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough resources for the object to perform any start-up task.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method is called when the class
is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method
of the class.

Example
1. class Employee:
2. def init (self, name, id):
3. self.id = id
4. self.name = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % (self.id, self.name))
8.
9.
10. emp1 = Employee("John", 101)
11. emp2 = Employee("David", 102)
12.
13. # accessing display() method to print employee 1 information
14.
15. emp1.display()
16.
17. # accessing display() method to print employee 2 information
18. emp2.display()

Output:

ID: 101
Name: John
ID: 102
Name: David

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the
following example.

Example

Jain College of BBA BCA & Commerce, Belagavi Page 4


Python Third Chapter Notes - GSM

1. class Student:
2. # Constructor - parameterized
3. def __init (self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()

Output:

This is parametrized constructor


Hello John

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that becomes
the default constructor. It does not perform any task but initializes the objects. Consider the
following example.

Example

1. class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()

Output:

101 Joseph

Inheritance
Inheritance is a way of creating a new class for using details of an 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).

Jain College of BBA BCA & Commerce, Belagavi Page 5


Python Third Chapter Notes - GSM

Example 3: Use of Inheritance in Python

# parent class
class Bird:

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

Output

Bird is ready
Penguin is ready

Jain College of BBA BCA & Commerce, Belagavi Page 6


Python Third Chapter Notes - GSM

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
the swim() method.
Again, the child class modified the behavior of the parent class. We can see this from
the whoisThis() method. Furthermore, we extend the functions of the parent class, by
creating a new run() method.
Additionally, we use the super() function inside the __init__() method. This allows us to run
the __init__() method of the parent class inside the child class.

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

Example 4: Data Encapsulation in Python

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

Jain College of BBA BCA & Commerce, Belagavi Page 7


Python Third Chapter Notes - GSM

c.__maxprice = 1000
c.sell()

# using setter function


c.setMaxPrice(1000)
c.sell()

Output

Selling Price: 900


Selling Price: 900
Selling Price: 1000

In the above program, we defined a Computer class.


We used __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.
As shown, to change the value, we have to use a setter function i.e setMaxPrice() which takes
price as a parameter.

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

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

Example 5: Using Polymorphism in Python

class Parrot:

def fly(self):
print("Parrot can fly")

Jain College of BBA BCA & Commerce, Belagavi Page 8


Python Third Chapter Notes - GSM

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


flying_test(blu)
flying_test(peggy)

Output

Parrot can fly


Penguin can't fly

In the above program, we defined two classes Parrot and Penguin. Each of them have a
common fly() method. However, their functions are different.
To use polymorphism, we created a common interface i.e flying_test() function that takes any
object and calls the object's fly() method. Thus, when we passed the blu and peggy objects in
the flying_test() function, it ran effectively.

Method Overloading in Python


Overloading is the ability of a function or an operator to behave in different ways based on the
parameters that are passed to the function, or the operands that the operator acts on.

Jain College of BBA BCA & Commerce, Belagavi Page 9


Python Third Chapter Notes - GSM

In Python, you can create a method that can be called in different ways. So, you can have a
method that has zero, one or more number of parameters. Depending on the method
definition, we can call it with zero, one or more arguments.

Given a single method or function, the number of parameters can be specified by you. This
process of calling the same method in different ways is called method overloading.

In the following example, we will overload the area method. If there is no argument then it
returns 0. And, If we have one argument then it returns the square of the value and assumes
you are computing the area of a square. Also, if we have two arguments then it returns the
product of the two values and assumes you are computing the area of a rectangle.

# class
class Compute:
# area method
def area(self, x = None, y = None):
if x != None and y != None:
return x * y
elif x != None:
return x * x
else:
return 0
# object
obj = Compute()

# zero argument
print("Area Value:", obj.area())
# one argument
print("Area Value:", obj.area(4))
# two argument
print("Area Value:", obj.area(3, 5))

The above code will give us the following output:

Area Value: 0
Area Value: 16
Area Value: 15

Method Overriding in Python


Method overriding is a concept of object oriented programming that allows us to change the
implementation of a function in the child class that is defined in the parent class. It is the
ability of a child class to change the implementation of any method which is already provided
by one of its parent class(ancestors).

Following conditions must be met for overriding a function:

Jain College of BBA BCA & Commerce, Belagavi Page 10


Python Third Chapter Notes - GSM

1. Inheritance should be there. Function overriding cannot be done within a class. We


need to derive a child class from a parent class.
2. The function that is redefined in the child class should have the same signature as inthe
parent class i.e. same number of parameters.

Python Method Overriding Example


Let's take a very cool example which we also had in the inheritance tutorial. There is a parentclass
named Animal:
# parent class
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True

# function breathdef
breathe(self):
print("I breathe oxygen.")

# function feed
def feed(self): print("I
eat food.")

# child class
class Herbivorous(Animal):

# function feed
def feed(self):
print("I eat only plants. I am vegetarian.")

herbi = Herbivorous()
herbi.feed()
# calling some other function
herbi.breathe()

OUTPUT:
I eat only plants. I am vegetarian.
I breathe oxygen.

What
Jain is Operator
College Overloading
of BBA BCA in Python
& Commerce, Belagavi Page 11

The operator overloading in Python means provide extended meaning beyond their predefined
Python Third Chapter Notes - GSM

operational meaning. Such as, we use the "+" operator for adding two integers as well as joining two
strings or merging two lists. We can achieve this as the "+" operator is overloaded by the "int" class
and "str" class. The user can notice that the same inbuilt operator or function is showing different
behaviour for objects of different classes. This process is known as operator overloading.

Example:

1. print (14 + 32)


2.
3. # Now, we will concatenate the two strings
4. print ("Java" + "Tpoint")
5.
6. # We will check the product of two numbers
7. print (23 * 14)
8.
9. # Here, we will try to repeat the String
10. print ("X Y Z " * 3)

Output:

46
JavaTpoint
322
X Y Z X Y Z X Y Z

How to Overload the Operators in Python?

Suppose the user has two objects which are the physical representation of a user-defined data type
class. The user has to add two objects using the "+" operator, and it gives an error. This is because the
compiler does not know how to add two objects. So, the user has to define the function for using the
operator, and that process is known as "operator overloading". The user can overload all the existing
operators by they cannot create any new operator. Python provides some special functions, or we can
say magic functions for performing operator overloading, which is automatically invoked when it is
associated with that operator. Such as, when the user uses the "+" operator, the magic function
__add__ will automatically invoke in the command where the "+" operator will be defined.

How to Perform Binary "+" Operator in Python:

When the user uses the operator on the user-defined data types of class, then a magic function that is
associated with the operator will be invoked automatically. The process of changing the behaviour of
Jain College
the operator is of
asBBA BCAas
simple & Commerce, Belagavi
the behaviour of the function or method defined. Page 12
Python Third Chapter Notes - GSM

The user define methods or functions in the class and the operator works according to that behaviour
defined in the functions. When the user uses the "+" operator, it will change the code of a magic
function, and the user has an extra meaning of the "+" operator.

Program 1: Simply adding two objects.

Python program for simply using the overloading operator for adding two objects.

Example:

1. class example:
2. def __init__(self, X):
3. self.X = X
4.
5. # adding two objects
6. def __add__(self, U):
7. return self.X + U.X
8. object_1 = example( int( input( print ("Please enter the value: "))))
9. object_2 = example( int( input( print ("Please enter the value: "))))
10. print (": ", object_1 + object_2)
11. object_3 = example(str( input( print ("Please enter the value: "))))
12. object_4 = example(str( input( print ("Please enter the value: "))))
13. print (": ", object_3 + object_4)

Output:

Please enter the value: 23


Please enter the value: 21
: 44
Please enter the value: Java
Please enter the value: Tpoint
: JavaTpoint

Program 2: defining Overloading operator in another object


Python program for defining the overloading operator inside another object.

ADVERTISEMENT

Jain College of BBA BCA & Commerce, Belagavi


Example: Page 13
Python Third Chapter Notes - GSM

1. class complex_1:
2. def __init__(self, X, Y):
3. self.X = X
4. self.Y = Y
5.
6. # Now, we will add the two objects
7. def __add__(self, U):
8. return self.X + U.X, self.Y + U.Y
9.
10. Object_1 = complex_1(23, 12)
11. Object_2 = complex_1(21, 22)
12. Object_3 = Object_1 + Object_2
13. print (Object_3)

Output:

(44, 34)

Program 3: Overloading comparison operators in Python


Python program for overloading comparison operators.

Example:

1. class example_1:
2. def __init__(self, X):
3. self.X = X
4. def __gt__(self, U):
5. if(self.X > U.X):
6. return True
7. else:
8. return False
9. object_1 = example_1(int( input( print ("Please enter the value: "))))
10. object_2 = example_1(int (input( print("Please enter the value: "))))
11. if(object_1 > object_2):
12. print ("The object_1 is greater than object_2")
13. else:
14. print ("The object_2 is greater than object_1")
Jain College of BBA BCA & Commerce, Belagavi Page 14
Output:
Python Third Chapter Notes - GSM

Case 1:

Please enter the value: 23


Please enter the value: 12
The object_1 is greater than object_2

Case 2:

ADVERTISEMENT
Please enter the value: 20
Please enter the value: 31
The object_2 is greater than object_1

Program 4: Overloading equality and less than operators


Python Program for overloading equality and less than operators:

Example:

1. class E_1:
2. def __init__(self, X):
3. self.X = X
4. def __lt__(self, U):
5. if(self.X < U.X):
6. return "object_1 is less than object_2"
7. else:
8. return "object_2 is less than object_1"
9. def __eq__(self, U):
10. if(self.X == U.X):
11. return "Both the objects are equal"
12. else:
13. return "Objects are not equal"
14.
15. object_1 = E_1(int( input( print ("Please enter the value: "))))
16. object_2 = E_1(int( input( print ("Please enter the value: "))))
17. print (": ", object_1 < object_2)
18.
19. object_3 = E_1(int( input( print ("Please enter the value: "))))
20. object_4 = E_1(int( input( print ("Please enter the value: "))))
21. print (": ", object_3 == object_4)

Output:
Jain College of BBA BCA & Commerce, Belagavi Page 15

ADVERTISEMENT
Python Third Chapter Notes - GSM
ADVERTISEMENT

Case 1:

Please enter the value: 12


Please enter the value: 23
: object_1 is less than object_2
Please enter the value: 2
Please enter the value: 2
: Both the objects are equal

Case 2:

Please enter the value: 26


Please enter the value: 3
: object_2 is less than object_1
Please enter the value: 2
Please enter the value: 5
: Objects are not equal

Python magic functions used for operator overloading:


Binary Operators:

Operator Magic Function

+ __add__(self, other)

- __sub__(self, other)

* __mul__(self, other)

/ __truediv__(self, other)

// __floordiv__(self, other)

% __mod__(self, other)

** __pow__(self, other)

>> __rshift__(self, other)

<< __lshift__(self, other)

& __and__(self, other)

| __or__(self, other)
Jain College of BBA BCA & Commerce, Belagavi Page 16
^ __xor__(self, other)
Python Third Chapter Notes - GSM

Comparison Operators:

Operator Magic Function

< __LT__(SELF, OTHER)

> __GT__(SELF, OTHER)

<= __LE__(SELF, OTHER)

>= __GE__(SELF, OTHER)

== __EQ__(SELF, OTHER)

!= __NE__(SELF, OTHER)

Assignment Operators:

Operator Magic Function

-= __ISUB__(SELF, OTHER)

+= __IADD__(SELF, OTHER)

*= __IMUL__(SELF, OTHER)

/= __IDIV__(SELF, OTHER)

//= __IFLOORDIV__(SELF, OTHER)

%= __IMOD__(SELF, OTHER)

**= __IPOW__(SELF, OTHER)

>>= __IRSHIFT__(SELF, OTHER)

<<= __ILSHIFT__(SELF, OTHER)

&= __IAND__(SELF, OTHER)

|= __IOR__(SELF, OTHER)

^= __IXOR__(SELF, OTHER)
Jain College of BBA BCA & Commerce, Belagavi Page 17
Unary Operator:
Python Third Chapter Notes - GSM

Operator Magic Function

- __NEG__(SELF, OTHER)

+ __POS__(SELF, OTHER)

~ __INVERT__(SELF, OTHER)

Python Modules
What are modules in Python?
Modules refer to a file containing Python statements and definitions.

A file containing Python code, for example: example.py, is called a module, and its module name
would be example.

We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.

We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""

result = a + b
return result

Here, we have defined a function add() inside a module named example. The function takes in two
numbers and returns their sum.

How to import modules in Python?


We can import the definitions inside a module to another module or the interactive interpreter in
Python.

We use the import keyword to do this. To import our previously defined module example, we type
the following in the Python prompt.
Jain College of BBA BCA & Commerce, Belagavi Page 18
Python Third Chapter Notes - GSM

>>> import example

This does not import the names of the functions defined in example directly in the current symbol
table. It only imports the module name example there.

Using the module name we can access the function using the dot . operator. For example:

>>> example.add(4,5.5)
9.5

Python has tons of standard modules. You can check out the full list of Python standard modules and
their use cases. These files are in the Lib directory inside the location where you installed Python.

Standard modules can be imported the same way as we import our user-defined modules.

There are various ways to import modules. They are listed below..

Python import statement


We can import a module using the import statement and access the definitions inside it using the
dot operator as described above. Here is an example.

# import statement example


# to import standard module math

import math
print("The value of pi is", math.pi)

When you run the program, the output will be:

The value of pi is 3.141592653589793

We can import a module by renaming it as follows:

# import module by renaming it

import math as m
print("The value of pi is", m.pi)

We have renamed the math module as m. This can save us typing time in some cases.

Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is the
correct implementation.
Jain College of BBA BCA & Commerce, Belagavi Page 19
Python Third Chapter Notes - GSM

Reading and Writing to text files in Python


Python provides inbuilt functions for creating, writing and reading files. There are two types of files that
can be handled in python, normal text files and binary files (written in binary language,0s and 1s).
 Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.
 Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file will be
used once its opened. These modes also define the location of the File Handle in the file. File handle is
like a cursor, which defines from where the data has to be read or written in the file. There are 6 access
modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file.
If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.
3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-
written. The handle is positioned at the beginning of the file. Creates the file if the file does not
exists.
4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated
and over-written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the
existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will be inserted at
the end, after the existing data.

It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should
be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special
character. For example, if there is \temp in the file address, then \t is treated as the tab character and
error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any
special characters. The r can be ignored if the file is in same directory and address is not being placed.
# Open function to open the file "MyFile1.txt" #

(same directory) in append mode and

file1 = open("MyFile.txt","a")
# store its reference in the variable file1 #

and "MyFile2.txt" in D:\Text in file2 file2 =

open(r"D:\Text\MyFile2.txt","w+")

Jain College of BBA BCA & Commerce, Belagavi Page 20


Python Third Chapter Notes - GSM

Here, file1 is created as object for MyFile1 and file2 as object for MyFile2
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the time
when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
# Opening and Closing a file "MyFile.txt" #

for object name file1.

file1 = open("MyFile.txt","a") file1.close()

Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most
n bytes. However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes
# Program to show various ways to read and #
write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes file1 =

open("myfile.txt","r+")
Jain College of BBA BCA & Commerce, Belagavi Page 21
Python Third Chapter Notes - GSM

print "Output of Read function is " print


file1.read()
print

# seek(n) takes the file handle to the nth #


bite from the beginning.
file1.seek(0)

print "Output of Readline function is " print


file1.readline()
print file1.seek(0)

# To show difference between read and readline print


"Output of Read(9) function is "
print file1.read(9) print

file1.seek(0)

print "Output of Readline(9) function is " print


file1.readline(9)

file1.seek(0)
# readlines function
print "Output of Readlines function is " print
file1.readlines()
print file1.close()

Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London

Output of Readline function is


Hello

Jain College of BBA BCA & Commerce, Belagavi Page 22


Python Third Chapter Notes - GSM

Output of Read(9) function is


Hello
Th

Output of Readline(9) function is


Hello

Output of Readlines function is


['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Appending to a file

# Python program to illustrate #

Append vs write mode

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

file1.close()

# Append-adds at last

file1 = open("myfile.txt","a")#append mode

file1.write("Today \n")

file1.close()

file1 = open("myfile.txt","r")

print "Output of Readlines after appending" print

file1.readlines()

print file1.close()

Jain College of BBA BCA & Commerce, Belagavi Page 23


Python Third Chapter Notes - GSM

# Write-Overwrites

file1 = open("myfile.txt","w")#write mode

file1.write("Tomorrow \n")

file1.close()

file1 = open("myfile.txt","r")

print "Output of Readlines after writing" print

file1.readlines()

print file1.close()

Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']

Output of Readlines after writing


['Tomorrow \n']

System Parametes & Functions


argv
The list of command line arguments passed to a Python script. argv[0] is the script
name (it is operating system dependent whether this is a full pathname or not). If the
command was executed using the -c command line option to the interpreter, argv[0] is
set to the string '-c'. If no script name was passed to the Python interpreter, argv has
zero length.

>>> import sys

>>> len(sys.argv)

Output

1
Jain College of BBA BCA & Commerce, Belagavi Page 24
Python Third Chapter Notes - GSM

copyright
A string containing the copyright pertaining to the Python interpreter.

>>> import sys

>>> sys.copyright

Output:

'Copyright (c) 2001-2018 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright


(c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for
National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting
Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.'

path
A list of strings that specifies the search path for modules. Initialized from the
environment variable $PYTHONPATH, or an installation-dependent default.

>>> import sys

>>> sys.path
['', 'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37- 32\\python37.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python37- 32\\lib\\site-packages']
>

platform
This string contains a platform identifier, e.g. 'sunos5' or 'linux1'. This can be used to
append platform-specific components to path, for instance.
prefix

>>> import sys

>>> sys.platform

OUTPUT

'win32'

Jain College of BBA BCA & Commerce, Belagavi Page 25


Python Fourth Chapter Notes-GSM

REGULAR EXPRESSION
A Regular Expression (RegEx) is a sequence of characters that defines a search pattern. For
example,
^a...s$

The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and
ending with s.
A pattern defined using RegEx can be used to match against a string.

Expression String Matched?


abs No match
alias Match
^a...s$ abyss Match
Alias No match
An abacus No match

Python has a module named re to work with RegEx. Here's an example:


import re

pattern = '^a...s$'

test_string = 'abyss'

result = re.match(pattern, test_string)

if result:

print("Search successful.")

else:

print("Search unsuccessful.")

Here, we used re.match() function to search pattern within the test_string. The method returns a
match object if the search is successful. If not, it returns None.

There are other several functions defined in the re module to work with RegEx. Before we explore
that, let's learn about regular expressions themselves.

Jain College of BBA BCA & Commerce, Belagavi Page 1


Python Fourth Chapter Notes-GSM

Specify Pattern Using RegEx


To specify regular expressions, metacharacters are used. In the above example, ^ and $ are
metacharacters.

MetaCharacters
Metacharacters are characters that are interpreted in a special way by a RegEx engine. Here's a listof
metacharacters:

[] . ^ $ * + ? {} () \ |

[] - Square brackets

Square brackets specifies a set of characters you wish to match.

Expression String Matched?


a 1 match
ac 2 matches
[abc]
Hey Jude No match
abc de ca 5 matches
Here, [abc] will match if the string you are trying to match contains any of the a, b or c.You
can also specify a range of characters using - inside square brackets.

• [a-e] is the same as [abcde].


• [1-4] is the same as [1234].
• [0-39] is the same as [01239].

You can complement (invert) the character set by using caret ^ symbol at the start of a square-
bracket.

• [^abc] means any character except a or b or c.


• [^0-9] means any non-digit character.

. - Period

A period matches any single character (except newline '\n').

Expression String Matched?


.. a No match

Jain College of BBA BCA & Commerce, Belagavi Page 2


Python Fourth Chapter Notes-GSM

Expression String Matched?


ac 1 match
acd 1 match
acde 2 matches (contains 4 characters)

^ - Caret

The caret symbol ^ is used to check if a string starts with a certain character.

Expression String Matched?


a 1 match
^a abc 1 match
bac No match
abc 1 match
^ab
acb No match (starts with a but not followed by b)

$ - Dollar

The dollar symbol $ is used to check if a string ends with a certain character.

Expression String Matched?


a 1 match
a$ formula 1 match
cab No match

* - Star

The star symbol * matches zero or more occurrences of the pattern left to it.

Expression String Matched?


mn 1 match
man 1 match
ma*n maaan 1 match
main No match (a is not followed by n)
woman 1 match

+ - Plus

The plus symbol + matches one or more occurrences of the pattern left to it.

Expression String Matched?


mn No match (no a character)
man 1 match
ma+n maaan 1 match
main No match (a is not followed by n)
woman 1 match

Jain College of BBA BCA & Commerce, Belagavi Page 3


Python Fourth Chapter Notes-GSM

? - Question Mark

The question mark symbol ? matches zero or one occurrence of the pattern left to it.

Expression String Matched?


mn 1 match
man 1 match
ma?n maaan No match (more than one a character)
main No match (a is not followed by n)
woman 1 match

{} - Braces

Consider this code: {n,m}. This means at least n, and at most m repetitions of the pattern left to it.

Expression String Matched?


abc dat No match
abc daat 1 match (at daat)
a{2,3}
aabc daaat 2 matches (at aabc and daaat)
aabc daaaat 2 matches (at aabc and daaaat)
Let's try one more example. This RegEx [0-9]{2, 4} matches at least 2 digits but not more than4
digits

Expression String Matched?


ab123csde 1 match (match at ab123csde)
[0-9]{2,4} 12 and 345673 2 matches (at 12 and 345673)
1 and 2 No match

| - Alternation

Vertical bar | is used for alternation (or operator).

Expression String Matched?


cde No match
a|b ade 1 match (match at ade)
acdbea 3 matches (at acdbea)
Here, a|b match any string that contains either a or b

() - Group

Parentheses () is used to group sub-patterns. For example, (a|b|c)xz match any string that
matches either a or b or c followed by xz

Expression String Matched?


(a|b|c)xz ab xz No match

Jain College of BBA BCA & Commerce, Belagavi Page 4


Python Fourth Chapter Notes-GSM

Expression String Matched?


abxz 1 match (match at abxz)
axz cabxz 2 matches (at axzbc cabxz)

\ - Backslash

Backlash \ is used to escape various characters including all metacharacters. For example,

\$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a
special way.

If you are unsure if a character has special meaning or not, you can put \ in front of it. This makes
sure the character is not treated in a special way.

Special Sequences
Special sequences make commonly used patterns easier to write. Here's a list of special
sequences:

\A - Matches if the specified characters are at the start of a string.

Expression String Matched?


the sun Match
\Athe
In the sun No match

\b - Matches if the specified characters are at the beginning or end of a word.

Expression String Matched?


football Match
\bfoo a football Match
afootball No match
the foo Match
foo\b the afoo test Match
the afootest No match

\B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word.

Expression String Matched?


football No match
\Bfoo a football No match
afootball Match
the foo No match
foo\B the afoo test No match
the afootest Match

\d - Matches any decimal digit. Equivalent to [0-9]

Jain College of BBA BCA & Commerce, Belagavi Page 5


Python Fourth Chapter Notes-GSM

Expression String Matched?


12abc3 3 matches (at 12abc3)
\d
Python No match

\D - Matches any non-decimal digit. Equivalent to [^0-9]

Expression String Matched?


1ab34"50 3 matches (at 1ab34"50)
\D
1345 No match

\s - Matches where a string contains any whitespace character. Equivalent to [ \t\n\r\f\v].

Expression String Matched?


Python RegEx 1 match
\s
PythonRegEx No match

\S- Matches where a string contains any non-whitespace character. Equivalent to [^ \t\n\r\
f\v].

Expression String Matched?


a b 2 matches (at a b)
\S
No match

\w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-9_].


By the way, underscore _ is also considered an alphanumeric character.

Expression String Matched?


12&": ;c 3 matches (at 12&": ;c)
\w
%"> ! No match

\W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_]

Expression String Matched?


1a2%c 1 match (at 1a2%c)
\W
Python No match

\Z - Matches if the specified characters are at the end of a string.

Expression String Matched?


I like Python 1 match
\ZPython I like Python No match
Python is fun. No match

Jain College of BBA BCA & Commerce, Belagavi Page 6


Python Fourth Chapter Notes-GSM

Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This
tool not only helps you in creating regular expressions, but it also helps you learn it.

Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code.

Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import the
module.
import re

The module defines several functions and constants to work with RegEx.

re.findall()
The re.findall() method returns a list of strings containing all matches.

Example 1: re.findall()
# Program to extract numbers from a stringimport

re

string = 'hello 12 hi 89. Howdy 34'

pattern = '\d+'

result = re.findall(pattern, string)

print(result)

# Output: ['12', '89', '34']

If the pattern is no found, re.findall() returns an empty list.

re.split()
The re.split method splits the string where there is a match and returns a list of strings wherethe
splits have occurred.

Example 2: re.split()
import re

string = 'Twelve:12 Eighty nine:89.'

Jain College of BBA BCA & Commerce, Belagavi Page 7


Python Fourth Chapter Notes-GSM

pattern = '\d+'

result = re.split(pattern, string)

print(result)

# Output: ['Twelve:', ' Eighty nine:', '.']

If the pattern is no found, re.split() returns a list containing an empty string.

You can pass maxsplit argument to the re.split() method. It's the maximum number of
splits that will occur.
import re

string = 'Twelve:12 Eighty nine:89 Nine:9.'

pattern = '\d+' # maxsplit = 1# split only at the first occurrence

result = re.split(pattern, string, 1)

print(result) # Output: ['Twelve:', ' Eighty nine:89 Nine:9.']

By the way, the default value of maxsplit is 0; meaning all possible splits.

re.sub()
The syntax of re.sub() is:
re.sub(pattern, replace, string)

The method returns a string where matched occurrences are replaced with the content of replace
variable.

Example 3: re.sub()
# Program to remove all whitespaces

import re # multiline string

string = 'abc 12\de 23 \n f45 6'# matches all whitespace characters

pattern = '\s+'# empty string

replace = ''

new_string = re.sub(pattern, replace, string)

print(new_string)

Jain College of BBA BCA & Commerce, Belagavi Page 8


Python Fourth Chapter Notes-GSM

# Output: abc12de23f456

If the pattern is no found, re.sub() returns the original string.

You can pass count as a fourth parameter to the re.sub() method. If omited, it results to 0. This
will replace all occurrences.
import re# multiline string

string = 'abc 12\de 23 \n f45 6'# matches all whitespace characters

pattern = '\s+'

replace = ''

new_string = re.sub(r'\s+', replace, string, 1)

print(new_string)

# Output:# abc12de 23# f45 6

re.subn()
The re.subn() is similar to re.sub() expect it returns a tuple of 2 items containing the new
string and the number of substitutions made.

Example 4: re.subn()
# Program to remove all whitespaces

import re # multiline string

string = 'abc 12\de 23 \n f45 6'# matches all whitespace characters

pattern = '\s+'# empty string

replace = ''

new_string = re.subn(pattern, replace, string)

print(new_string)

# Output: ('abc12de23f456', 4)

re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the
Jain College of BBA BCA & Commerce, Belagavi Page 9
Python Fourth Chapter Notes-GSM

first location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)

Example 5: re.search()
import re

string = "Python is fun"# check if 'Python' is at the beginning

match = re.search('\APython', string)

if match:

print("pattern found inside the string")

else:

print("pattern not found")

# Output: pattern found inside the string

Here, match contains a match object.

Match object
You can get methods and attributes of a match object using dir() function.
Some of the commonly used methods and attributes of match objects are:

match.group()
The group() method returns the part of the string where there is a match.

Example 6: Match object


import re

string = '39801 356, 2102 1111'# Three digit number followed by space followed
by two digit

numberpattern = '(\d{3}) (\d{2})'# match variable contains a Match object.

match = re.search(pattern, string)

if match:

print(match.group())

else:
Jain College of BBA BCA & Commerce, Belagavi Page 10
Python Fourth Chapter Notes-GSM

print("pattern not found")# Output: 801 35

Here, match variable contains a match object.

Our pattern (\d{3}) (\d{2}) has two subgroups (\d{3}) and (\d{2}). You can get the
part of the string of these parenthesized subgroups. Here's how:
>>> match.group(1)

'801'

>>> match.group(2)

'35'

>>> match.group(1, 2)

('801', '35')

>>> match.groups()

('801', '35')

match.start(), match.end() and match.span()


The start() function returns the index of the start of the matched substring. Similarly, end()
returns the end index of the matched substring.
>>> match.start()

>>> match.end()

The span() function returns a tuple containing start and end index of the matched part.
>>> match.span()

(2, 8)

match.re and match.string


The re attribute of a matched object returns a regular expression object. Similarly, string
attribute returns the passed string.
>>> match.rere.compile('(\\d{3}) (\\d{2})')>>> match.string'39801 356, 2102
1111'

We have covered all commonly used methods defined in the re module. If you want to learn more,

Jain College of BBA BCA & Commerce, Belagavi Page 11


Python Fourth Chapter Notes-GSM

Using r prefix before RegEx


When r or R prefix is used before a regular expression, it means raw string. For example, '\n'
is anew line whereas r'\n' means two characters: a backslash \ followed by n.

Backlash \ is used to escape various characters including all metacharacters. However, using r
prefix makes \ treat as a normal character.

Jain College of BBA BCA & Commerce, Belagavi Page 12

You might also like