0% found this document useful (0 votes)
10 views60 pages

Python Object-Oriented Programming Guide

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, encapsulation, and polymorphism. It explains the creation and use of classes and objects, constructors, destructors, and various types of inheritance. Additionally, it covers Python's access modifiers and built-in class functions for managing object attributes.

Uploaded by

babysmitha14
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views60 pages

Python Object-Oriented Programming Guide

This document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, inheritance, encapsulation, and polymorphism. It explains the creation and use of classes and objects, constructors, destructors, and various types of inheritance. Additionally, it covers Python's access modifiers and built-in class functions for managing object attributes.

Uploaded by

babysmitha14
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE - 3

Object-Oriented Programming in Python

In Python, object-oriented Programming (OOPs) is a programming paradigm that


uses objects and classes in programming. It aims to implement real-world entities
like inheritance, polymorphisms, encapsulation, etc. in the programming. The main
concept of OOPs is to bind the data and the functions that work on that together as
a single unit so that no other part of the code can access this data.

➢ OOPs Concepts in Python


Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
➢ Python Class :

A class is a collection of objects. A class contains the blueprints or the prototype from which the
objects are being created. It is a logical entity that contains some attributes and methods.

Some points on Python class:


• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator.
Eg.: [Link]

Class Definition Syntax:

class ClassName:
# Statement-1
.
.
# Statement-N
Creating an Empty Class in Python

class Student:
pass

➢ Python Objects :

The object is an entity that has a state and behavior associated with it. It may be any real-world
object like a mouse, keyboard, chair, table, pen, etc. Integers, strings, floating-point numbers, even
arrays, and dictionaries, are all objects. More specifically, any single integer or any single string is an
object.

An object consists of:

• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object
to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other
objects.
To understand the state, behavior, and identity let us take the example of the class Student.

• The identity can be considered as the name of the Student.


• State or Attributes can be considered as the name, age, or class of the Student.
• The behavior or method of student can be considered as learning.

✓ Creating an Object :

This will create an object named obj of the class Student.

obj = Student()

some basic keywords that will we used while working with objects and classes.
1. Python Self

• The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class. It holds the memory reference of object.

• It does not have to be named self , you can call it whatever you like, but it has to be the first
parameter of any function in the class:
2. The Python __init__ Method

"__init__" is a reserved method in python classes. It is known as a constructor in OOP concepts.


This method called when an object is created from the class and it allows the class to initialize the
attributes of a class.

Creating a class and object with class and instance attributes

class student:
def __init__(self,name,dept):
[Link]=name
[Link]=dept
def std_details(self):
print("Details of class student: ",[Link],[Link])

s1=student("any","BCA") #s1 is the first object of class Student


s2=student("kavya","Bcom") #s2 is the second object of class Student
print([Link], [Link])
print(s2.__dict__) #__dict__ is used to display all the content in student class in a dictionary
format.
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.

• Parameterized Constructor
• Non-parameterized Constructor
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.

We can pass any number of arguments at the time of creating the class object, depending upon
the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a
constructor, even if it simply relies on the default constructor.
Consider the following example to initialize the Employee class attributes.

Example :

class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name

def display(self):
print("employe details", [Link], [Link])

emp1 = Employee("anu", 101)


emp2 = Employee("arun", 102)

[Link]() # accessing display() method to print employee 1 information

[Link]() # accessing display() method to print employee 2 information


1. Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self.

Example :

class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name

def show(self):
print("Hello",[Link]) Output:
This is parametrized constructor
student = Student(“anu") Hello anu
[Link]()
2. Python Non-Parameterized Constructor

The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument.

Example:

class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")

def show(self,name):
print("Hello",name)

student = Student()
[Link](“anu")
➢ 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.

Example

class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,[Link])

st = Student()
[Link]()

Method : The method is a function that is associated with an object.


example :
Python built-in class functions

SN Function Description
1 getattr (obj,name,default) It is used to access the attribute of the object.
It is used to set a particular value to the specific
2 setattr (obj, name,value)
attribute of an object.
3 delattr (obj, name) It is used to delete a specific attribute.
It returns true if the object contains some
4 hasattr(obj, name)
specific attribute.

Example

class Student:
def __init__(self, name, id, age):
[Link] = name
[Link] = id
[Link] = age
s = Student(“anu", 101, 22) # creates the object of the class Student

print(getattr(s, 'name’)) # prints the attribute name of the object s

setattr(s, "age", 23) # reset the value of attribute age to 23

print(getattr(s, 'age')) # prints the modified value of age

print(hasattr(s, 'id')) # prints true if the student contains the attribute with name id

delattr(s, 'age’) # deletes the attribute age

print([Link]) # this will give an error since the attribute age has been
deleted
Output:
anu
23
True
AttributeError: 'Student' object has no attribute 'age'
DESTRUCTORS IN PYTHON

• Destructors are called when an object gets destroyed.


• In Python, destructors are not needed as much as in C++ because Python has a
garbage collector that handles memory management automatically.
• The __del__() method is a known as a destructor method in Python.
• It is called when all references to the object have been deleted i.e when an object is
garbage collected.

➢ Syntax of destructor declaration :

def __del__(self):
# body of destructor

Note : A reference to objects is also deleted when the object goes out of reference or
when the program ends.
Example 1 : Here is the simple example of destructor. By using del keyword we deleted the all
references of object ‘obj’, therefore destructor invoked automatically.

# Python program to illustrate destructor


class Employee:
Output
# Initializing
def __init__(self): Employee created.
print('Employee created.') Destructor called, Employee deleted.

# Deleting (Calling destructor)


def __del__(self):
print('Destructor called, Employee deleted.')

obj = Employee()
del obj

➢ The destructor was called after the program ended or when all the references to object are
deleted i.e when the reference count becomes zero, not when object went out of scope.
EXAMPLE: # delete object reference s1
del s1
class Student:
print('After destroy of s1 ')
# constructor s2.student_details()
def __init__(self, name): del s2
[Link] = name

def student_details(self): Output:


print('Hello, my name is', [Link])
Hello, my name is Anu
# destructor After destroy of s1
def __del__(self): Hello, my name is Anu
print('Object destroyed') Object destroyed

# create object
s1 = Student('Anu')
# create new reference
# both reference points to the same object
s2 = s1
s1.student_details()
Python Inheritance

➢ Inheritance is the capability of one class to derive or inherit the properties from another class.

Benefits of inheritance are:


• Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e., derived
class.
• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write the same code again and again. Also, it
allows us to add more features to a class without modifying it.
• It is transitive in nature, which means that if class B inherits from another class A, then all the
subclasses of B would automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Less development and maintenance expenses result from an inheritance.
Python Inheritance Syntax :

Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Parent Class

A parent class is a class whose properties are inherited by the child class. create a parent class called
Person which has a Display method to display the person’s information.

# A Python program to demonstrate inheritance


Output:
class Person(object):
anu 100
# Constructor
def __init__(self, name, id):
[Link] = name
[Link] = id

# To check if this person is an employee


def Display(self):
print([Link], [Link])

# creating object for class person


emp = Person("anu", 100) # An Object of Person
[Link]()
Creating a Child Class

A child class is a class that drives the properties from its parent class. e1= Employee("Emy",11,"Female")
print([Link])
➢ Example of Inheritance in Python print([Link])
#parent class print([Link])
class Customer: print([Link])
def __init__(self,name): print(e1.__dict__)
[Link]=name
[Link]()
#child class inherit the property of parent class
class Employee(Customer): Output :
def __init__(self,name,age,gender): Emy
super().__init__(name) 11
[Link]=age Female
[Link]=gender 15000
[Link]=15000
{'name': 'Emy', 'age': 11, 'gender': 'Female',
'salary': 15000}
def show(self):
print("the name of Employee is ",[Link],"and age is ", the name of Employee is Emy and age is
[Link],"and gender is “ ,[Link],"salary is",[Link]) 11 and gender is Female salary is 15000
The super() Function

The super() function is a built-in function that returns the objects that represent the parent class. It
allows to access the parent class’s methods and attributes in the child class.

Types of Inheritance in Python

1. Single inheritance: When child class is derived from only one parent class.
Example:
Syntax of single inheritance:
class Parent: #parent_class
class class1: #parent_class
def method1(self):
pass
print("This is parent class")
class class2(class1): #child_class
class Child(Parent): #child_class
pass
def method2(self):
print("This is child class")
obj_name = class2()
c1=Child() # create object for child_class
c1.method1()
c1.method2()
2. Multiple Inheritance: When child class is derived or inherited from more than one parent
class.
• In multiple inheritance, we have two parent classes/base classes and one child class that
inherits both parent classes properties.

➢ Syntax of multiple inheritance Example :

class parent_1: class parent_1 :


def method1(self):
pass
print("This is parent 1 class")

class parent_2: class parent_2 :


pass def method2(self):
print("This is parent 2 class")
class child(parent_1,parent_2):
pass class Child(parent_1, parent_2):
def method(self):
obj = child() print("This is child class")
c1=Child()
c1.method1()
c1.method2()
3. Multilevel Inheritance: In multilevel inheritance, we have one parent class and child class that is
derived or inherited from that parent class.
Example :
➢ Syntax of multilevel inheritance
class P1:
class A: def method1(self):
pass print("This is parent 1 class")

class B(A): class Child(P1):


pass def method2(self):
print("This is child class")
class C(B):
pass class New(Child):
def method3(self):
obj = C() print("This is New class")
n1=New()
n1.method1()
n1.method2()
n1.method3()
4). Hierarchical inheritance: When we derive or inherit more than one child class from
one(same) parent class. Then this type of inheritance is called hierarchical inheritance.

➢ Syntax of hierarchical inheritance Example :

class A: #parent_class class P1:


pass def method1(self):
print("This is parent 1 class")
class B(A): #child_class
pass class Child_1(P1):
def method2(self):
print("This is child class 1")
class C(A): #child_class
pass class Child_2(P1):
def method3(self):
class D(A): #child_class print("This is child class 2")
pass
n1=Child_1()
obj_1 = B() #Object_creation n2=Child_2()
obj_2 = C() n1.method1()
obj_3 = D() n2.method1()
5). Hybrid Inheritance: Hybrid inheritance satisfies more than one form of inheritance ie. It may be
consists of all types of inheritance that we have done above. It is not wrong if we say Hybrid
Inheritance is the combinations of simple, multiple, multilevel and hierarchical inheritance.
Example :
Syntax Hybrid inheritance class School:
def func1(self):
class PC: print("This function is in school.")
pass class Student1(School):
def func2(self):
class Laptop(PC): print("This function is in student 1. ")
pass
class Student2(School):
def func3(self):
class Mouse(Laptop): print("This function is in student 2.")
pass
class Student3(Student1, School):
class Student3(Mouse, Laptop): def func4(self):
print("This function is in student 3.")
pass
object = Student3()
obj = Student3() object.func1()
object.func2()
Encapsulation in Python

• It describes the idea of wrapping data and the methods that work on data within one unit.
• This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data.
• To prevent accidental change, an object’s variable can only be changed by an object’s method.
Those types of variables are known as private variables.

Python Access Modifiers :

public
private
protected

➢ The public Access Modifier: The public member is accessible from inside or outside the class.

➢ The private Access Modifier : The private member is accessible only inside class. Define a private
member by prefixing the member name with two underscores.
Example : __age
➢ The protected Access Modifier : The protected member is accessible from inside the class
and its sub-class. Define a protected member by prefixing the
member name with an underscore.
Example : _age
Example : Example : To access the private variable, we have to create a
function and print the private variable inside the method. Call
class A(): the method from outside the method.
def __init__(self):
self.a=5 class A():
self._b=4 def __init__(self): Output :
self.__c=6 self.a=5
obj=A() self._b=4 value of a : 5
print(obj.a) self.__c=6 value of b : 4
print(obj._b) value of c : 6
print(obj.__c) #we can’t access the private variable def myfun(self):
print ("value of c :", self.__c)
Output :
obj=A()
AttributeError: 'A' object has no attribute '__c' print("value of a :", obj.a)
print ("value of b :", obj._b)
[Link]()
Data Abstraction in Python

➢ Data Abstraction in Python can be achieved through creating abstract classes and inheriting
them later.

Abstract Class : A class which contains one or more abstract methods is called an abstract class.

How Abstract classes work :

By default, Python does not provide abstract classes. Python comes with a module that
provides the base for defining Abstract Base classes(ABC) and that module name is ABC. ABC works
by decorating methods of the base class as abstract and then registering concrete classes as
implementations of the abstract base. We use the @abstractmethod decorator to define an
abstract method or if we don't provide the definition to the method, it automatically becomes the
abstract method.

Abstract class in Python :


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
• An abstract class must be declared with an abstract keyword.
• It can have abstract and non-abstract methods.
• It cannot be instantiated.

Syntax :
from abc import ABC,@abstractmethod
class Classname(ABC)

Abstract method : An abstract method is a method that has a declaration but does not have an
implementation.

Syntax :
from abc import ABC,@abstractmethod
class Classname(ABC):
def metodname(self):
pass
Example - # Driver code
t= Tesla ()
from abc import ABC, abstractmethod [Link]()
class Car(ABC):
s = Suzuki()
def mileage(self):
[Link]()
pass
d = Duster()
class Tesla(Car): [Link]()
def mileage(self):
print("The mileage is 30kmph") Output:

class Suzuki(Car): The mileage is 30kmph


def mileage(self): The mileage is 25kmph
print("The mileage is 25kmph ") The mileage is 24kmph
Explanation - In the above code, we have imported the abc module
class Duster(Car): to create the abstract base class. We created the Car class that
def mileage(self): inherited the ABC class and defined an abstract method named
mileage(). We have then inherited the base class from the two
print("The mileage is 24kmph ") different subclasses and implemented the abstract method
differently. We created the objects to call the abstract method.
Polymorphism in Python

The word polymorphism means having many forms. Polymorphism refers to having multiple
forms. Polymorphism is a programming term that refers to the use of the same function name,
but with different signatures, for multiple types.

➢ Example of inbuilt polymorphic functions:


#len () sows different behavior for different input Output :

# len() being used for a string 6


print(len("Python")) 3

# len() being used for a list


print(len([10, 20, 30]))

➢ Examples of user-defined polymorphic functions: Output :

# + operator sows different behavior for different input 40


Python Programming
print(10+30)
print("Python"+" Programming")
➢ Polymorphism with class methods:

class Apple():
def color(self):
print ("color is red")
def taste(self):
print ("always is sweet") Output:

class Orange(): color is red


def color(self): always is sweet
print ("color is orange") color is orange
def taste(self): taste is sour and sweet
print ("taste is sour and sweet")

def fruits(obj):
[Link]()
[Link]()

a_obj = Apple()
o_obj = Orange()
fruits(a_obj)
fruits(o_obj)
Python Exception Handling

➢ Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are problems in a
program due to which the program will stop the execution. On the other hand, exceptions are
raised when some internal events occur which change the normal flow of the program.

Different types of exceptions in python:

In Python, there are several built-in exceptions that can be raised when an error occurs during the
execution of a program. Here are some of the most common types of exceptions in Python:

1. SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
2. TypeError: This exception is raised when an operation or function is applied to an object of
the wrong type, such as adding a string to an integer.
3. NameError: This exception is raised when a variable or function name is not found in the
current scope.
4. IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
5. KeyError: This exception is raised when a key is not found in a dictionary.

6. ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when
the string does not represent a valid integer.

7. AttributeError: This exception is raised when an attribute or method is not found on an


object, such as trying to access a non-existent attribute of a class instance.

8. IOError: This exception is raised when an I/O operation, such as reading or writing
a file, fails due to an input/output error.

9. ZeroDivisionError: This exception is raised when an attempt is made to divide a number by


zero.

[Link]: This exception is raised when an import statement fails to find or load a
module.
Difference between Syntax Error and Exceptions

• Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It
leads to the termination of the program.

Example:
amount = 10000

if(amount > 2999)


print("You are eligible ")

Exceptions: Exceptions are raised when the program is syntactically correct, but the code results
in an error. This error does not stop the execution of the program, however, it changes the
normal flow of the program.
# initialize the amount variable Output:
Example: marks = 10000

# perform division with 0


a = marks / 0 In this example raised the ZeroDivisionError as we are trying to
print(a) divide a number by 0.
Example:

➢ TypeError: This exception is raised when an operation or function is applied to an object of


the wrong type.
x=5
y = "hello"
z = x + y # Raises a TypeError: unsupported operand type(s) for +: 'int' and 'str'

Exception handling blocks:

1. try block
2. except block
3. else block
4. finally block

➢ Syntax :
else:
try: #code to execute if no exception occurred
#code containing exception finally:
except[exception name]: #always executed
#code to handle exception
➢ Try and Except Statement – Catching Exceptions

• Try and except statements are used to catch and handle exceptions in Python.
• Statements that can raise exceptions are kept inside the try clause and the statements that
handle the exception are written inside except clause.

➢ Catching Specific Exception

A try statement can have more than one except clause, to specify handlers for different
exceptions.
The general syntax for adding specific exceptions are –

try:
Example : Output :
# statement(s)
except (exception name): num1 = 4 File"F:/python s4/try and [Link]", line 3, in <module>
# statement(s) num2 = 0 sum=num1/num2
except (exception name): sum=num1/num2 ZeroDivisionError: division by zero
# statement(s) print(sum)
Explanation - As we can see from the code above, a ZeroDivisionError error occurred. The reason
for this is that we are doing a 4 by 0 division here. Python understands that an integer cannot be
split by a zero. We apply exception handling techniques to deal with this exception.

Example : exception handled wit try and except block.


Output :
num1 =int(input("enter the first number : “))
num2 = int(input("enter the second number : ")) enter the first number : 4
try: enter the second number : 0
sum=num1/num2 ZeroDivisionError handled
print(sum)

except(ZeroDivisionError):
print("ZeroDivisionError handled ")

➢ Try with Else Clause


In Python, you can also use the else clause on the try-except block which must be present
after all the except clauses. The code enters the else block only if the try clause does not raise an
exception
Syntax : Example : Output :

try: num1 =int(input("enter the first number : ")) enter the first number : 4
# statement(s) num2 = int(input("enter the second number : ")) enter the second number : 2
except (exception name): try: 2.0
# statement(s) sum is : 2.0
sum=num1/num2
else: print(sum)
# statement(s) except(ZeroDivisionError):
print("ZeroDivisionError handled ")
else:
print("sum is : ",sum)

➢ Finally Keyword in Python :

• Python provides a keyword finally, which is always executed after the try and except blocks.
• The final block always executes after the normal termination of the try block or after the try block
terminates due to some exception.
Syntax: Example : Output :

try: num1 =4 2.0


# Some Code.... num2 = 2 sum is : 2.0
except: try: rest of code
# Handling of exception (if required) sum=num1/num2
else: print(sum)
# execute if no exception except(ZeroDivisionError):
finally: print("ZeroDivisionError handled ")
# Some code .....(always executed) else:
print("sum is : ",sum)
finally:
➢ Argument of an Exception in Python print("rest of code ")
An exception can have an argument, which is a value that gives additional information about the
problem. The contents of the argument vary by exception.

try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable follow the name of the
exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.

This variable receives the value of the exception mostly containing the cause of the exception.
The variable can receive a single value or multiple values in the form of a tuple. This tuple usually
contains the error string, the error number, and an error location.

➢ Python Raise an Exception

The raise statement in Python is used to raise an exception. Try-except blocks can be
used to manage exceptions, which are errors that happen while a program is running. When an
exception is triggered, the program goes to the closest exception handler, interrupting the
regular flow of execution.

• The raise keyword is typically used inside a function or method, and is used to indicate an
error condition.
• We can throw an exception and immediately halt the running of your program by using the
raise keyword.
➢ Python looks for the closest exception handler, which is often defined using a try-except block,
when an exception is triggered.
➢ If an exception handler is discovered, its code is performed, and the try-except block's starting
point is reached again.
➢ If an exception handler cannot be located, the software crashes and an error message appears.
Advantages of Exception Handling:

1. Improved program reliability: By handling exceptions properly, you can prevent your program
from crashing or producing incorrect results due to unexpected errors or input.
2. Simplified error handling: Exception handling allows you to separate error handling code from the
main program logic, making it easier to read and maintain your code.
3. Cleaner code: With exception handling, you can avoid using complex conditional statements to
check for errors, leading to cleaner and more readable code.
4. Easier debugging: When an exception is raised, the Python interpreter prints a traceback that
shows the exact location where the exception occurred, making it easier to debug your code.

Disadvantages of Exception Handling:

Performance overhead: Exception handling can be slower than using conditional statements to check
for errors, as the interpreter has to perform additional work to catch and handle the exception.
1. Increased code complexity: Exception handling can make your code more complex, especially if
you have to handle multiple types of exceptions or implement complex error handling logic.
2. Possible security risks: Improperly handled exceptions can potentially reveal sensitive information
or create security vulnerabilities in your code, so it’s important to handle exceptions carefully and
avoid exposing too much information about your program.
Python assert keyword

Python Assertions in any programming language are the debugging tools that help in the
smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants
to be true and hence puts them in code so that failure of these doesn’t allow the code to execute
further.
Assert Keyword in Python
In simpler terms, we can say that assertion is the Boolean expression that checks if the
statement is True or False. If the statement is true then it does nothing and continues the execution,
but if the statement is False then it stops the execution of the program and throws an error.

Flowchart of Python Assert Statement


Python assert keyword Syntax

In Python, the assert keyword helps in achieving this task. This statement takes as input a
Boolean condition, which when returns true doesn’t do anything and continues the normal flow of
execution, but if it is computed to be false, then it raises an AssertionError along with the optional
message provided.

Syntax : assert condition, error_message(optional)

Parameters:

• condition : The Boolean condition returning true or false.


• error_message : The optional argument to be printed in console in case of AssertionError
• Returns: Returns AssertionError, in case the condition evaluates to false along with the error
message which when provided.

➢ Why Use Python Assert Statement?


In Python, the assert statement is a potent debugging tool that can assist in identifying
mistakes and ensuring that your code is operating as intended. Here are several justifications for
using assert:
▪ Debugging: Assumptions made by your code can be verified with the assert statement. You may
rapidly find mistakes and debug your program by placing assert statements throughout your
code.

▪ Documentation: The use of assert statements in your code might act as documentation. Assert
statements make it simpler for others to understand and work with your code since they
explicitly describe the assumptions that your code is making.

▪ Testing: In order to ensure that certain requirements are met, assert statements are frequently
used in unit testing. You can make sure that your code is working properly and that any changes
you make don’t damage current functionality by incorporating assert statements in your tests.

▪ Security: You can use assert to check that program inputs comply with requirements and
validate them.
Regular Expression in Python

A Regular Expressions (RegEx) is a special sequence of characters that uses a search


pattern to find a string or set of strings. It can detect the presence or absence of a text by
matching it with a particular pattern, and also can split a pattern into one or more sub-patterns.
• Python provides a re module that supports the use of regex in Python.
• Its primary function is to offer a search, where it takes a regular expression and a string.
• Here, it either returns the first match or else none.

Regex Module in Python

Python has a module named re that is used for regular expressions in Python. We can
import this module by using the import statement.

Example: Importing re module in Python

import re

➢ Functions in regular expression(regex) : findall() , match(), search(), split(),sub()

1. findall() : finds *all* the matches and returns them as a list of strings, with each string
representing one match.
Syntax :
[Link](<pattern>, source_string)

pattern = A pattern defines what to match in a string.


source_string = The source_string defines where to match in a string .

Example :

import re Output :
str="hello everyone this is python"
x = [Link]("h",str) ['h', 'h', 'h']
print(x)

2. [Link]() : This function attempts to match pattern to whole string.


The [Link] function returns a match object on success, None on failure.
Synatx:
[Link](pattern, string)

pattern : Regular expression to be matched.


string : String where pattern is searched
Example : If the pattern match : Example : If the pattern doesn't match :

import re import re
str="hello everyone this is python" str="hello everyone this is python"
x=[Link]("h",str) x=[Link]("abc",str)
print(x) print(x)

Output : Output :
<[Link] object; span=(0, 1), match='h'> []

3. [Link]() : This method either returns None (if the pattern doesn’t match), or a
[Link] that contains information about the matching part of the
string. This method stops after the first match, so this is best suited for testing a
regular expression more than extracting data.

Example : If the pattern matches search method will return the match object :
import re
str="hello everyone this is python" Output :
x= [Link]("h",str) <[Link] object; span=(0, 1), match='h'>
print(x)
Example : If the pattern doesn't matches search method will return none :

import re Output :
str="hello everyone this is python" none
x=[Link]("abc",str)
print(x)

➢ Using the search method, it will only return match objects. To see the original result match
object, provide some methods.

1. start
2. span
3. String

1. start(): start will display the position of the occurrence.


Example : Output :
import re 6
str="hello everyone this is python"
x=[Link]("everyone",str)
print([Link]())
2. span() : span will display tuple of start and end position of match.

Example: Output:
import re (6, 14)
str="hello everyone this is python"
x=[Link]("everyone",str)
print([Link]())

3. string(): string will return the actual string used for pattern matches.

4. Split() : Split the string from given pattern. Example 3:


import re
Example 1: Example 2: str="hello everyone "
import re import re x=[Link](" ",str)
str="hello everyone this is python" str="hello everyone this is python" print(x)
x=[Link]("h",str) x=[Link]("hello",str)
print(x) print(x) Output:

Output: Output: ['', 'h', 'e', 'l', 'l', 'o', ' ', 'e', 'v', 'e', 'r',
['', 'ello everyone t', 'is is pyt', 'on'] ['', ' everyone this is python'] 'y', 'o', 'n', 'e' '']
Example:
5. sub() : substitute new string to old string
import re
Syntax: str="python programming"
[Link]("old_string","new_string",source_string) x=[Link]("p","r",str)
print(x)
Python RegEx Meta Characters Output : rython rrogramming

Metacharacters are part of regular expression and are the special characters that
symbolize regex patterns or formats. Every character is either a metacharacter or a regular
character in a regular expression. However, metacharacters have a special meaning. They are
not used to match any patterns but to define some rules to find the specific pattern in the
statement. Metacharacters are also known as operators, signs, or symbols.

1. [] : It represent set of characters


Example : Output :
import re ['h', 'h', 'h']
str="hello everyone this is python"
x=[Link]("h",str)
print(x)
2. caret ( ^ ) : A caret matches the start of a line or a particular string.

Example : Example : if the pattern is not the first string


import re import re
str="hello everyone this is python" str="hello everyone this is python"
x=[Link]("^hello",str) x=[Link]("^everyone",str)
print(x) print(x)

Output : Output:
['hello’] []

3. Dollar Metacharacter($): It is used to match the end of a string.

Example : Output:
import re [python]
str="hello everyone this is python"
x=[Link]("python$",str)
print(x)
Example : if the pattern is not the last string
import re Output:
str="hello everyone this is python" []
x=[Link]("everyone$",str)
print(x)

4. dot Metacharacter('.') : dot matches any single character except a newline.

example 1 : It checks if there are 3 characters before the pattern L. If yes, it will return that
pattern. If not, it will return an empty list.
import re output:
str="hello everyone this is python" [hello]
x=[Link]("...lo",str)
print(x)

example 2 : output:
import re
[hello eve]
str="hello everyone this is python"
x=[Link]("hel......",str)
print(x)
example 3 : output:
import re []
str="hello everyone this is python"
x=[Link]("python...",str)
print(x)

5. question mark (?) : matches zero or one occurrences of the regular expression.

Example 1: 1 occurrence of n Example 2: 0 occurrence of n Example 3: 2 or more occurrence of n


import re import re import re
str="ana" str="au" str="anna"
x=[Link]("an?a",str) x=[Link]("an?u",str) x=[Link]("an?a",str)
print(x) print(x) print(x)

Output: Output: Output:


['ana'] ['au'] []
6. Plus metacharacter (+) : matches one or more occurrences of the regular expression.

Example 1 : 2 occurrence of n Example 2 : 1 occurrence of n Example 3 : no occurrence of n


import re import re import re
str="anna" str="anu" str="ammu"
x=[Link]("an+a",str) x=[Link]("an+u",str) x=[Link]("an+u",str)
print(x) print(x) print(x)

Output: ['anna'] Output: ['anu'] Output: []

7. asterisk (*) or star metacharacter : means “match zero or more occurrence of the
preceding character.”
Example 1: 1 occurrence of m Example 2: no occurrence of m Example 3: more occurrence of m
import re import re import re
str="amu" str="au" str="ammmmmmmu"
x=[Link]("am*u",str) x=[Link]("am*u",str) x=[Link]("am*u",str)
print(x) print(x) print(x)

output: Output: Output :


['amu'] ['au'] ['ammmmmmmu']
8. {} curly brackets : The curly brackets are used to match exactly n instances of the
proceeding character or pattern.

Example 1: Example 2:
import re import re
str="my name is ammu, my ae is 20, i love my self" str="my name is ammu, my ae is 20, i love my self"
x=[Link]("my{1,3}",str) x=[Link]("my{5,6}",str)
print(x) print(x)

Output: Output:
['my', 'my', 'my'] []

Character Sets
[abc] a, b, or c (simple class)
[^abc] Any character except a, b, or c (negation)
[a - z] a to z
[A - Z] A to Z
[a - z A - Z] a to z , A to Z
[0 - 9] 0 to 9
Special Characters
1. \d Returns a match where the string contains digits (numbers from 0-9)
Example 1 : Example 2 :
import re import re
txt = "The rain 123" txt = "The rain "
#Check if the string contains any digits (numbers from 0-9): #Check if the string contains any digits (numbers from 0-9):
x = [Link]("\d", txt) x = [Link]("\d", txt)
print(x) print(x)

Output: Output:
['1', '2', '3'] []

2. \D Returns a match where the string DOES NOT contain digits


Example 1: Example 2:
import re import re
txt = "rain" txt = "rain 123"
#Return a match at every no-digit character: #Return a match at every no-digit character:
x = [Link]("\D", txt) x = [Link]("\D", txt)
print(x) print(x)

Output : Output:
['r', 'a', 'i', 'n'] ['r', 'a', 'i', 'n', ' ']
3. \w Returns a match where the string contains any word characters (characters from a to Z,
digits from 0-9, and the underscore _ character)

Example 1: Example 2:
import re import re
txt = "The rain 123" txt = "The rain 123 &%#"
x = [Link]("\w", txt) x = [Link]("\w", txt)
print(x) print(x)

Output: Output:
['T', 'h', 'e', 'r', 'a', 'i', 'n', '1', '2', '3'] ['T', 'h', 'e', 'r', 'a', 'i', 'n', '1', '2', '3']

4. \W Returns a match where the string DOES NOT contain any word characters

Example 1: Example 2:
import re import re
txt = "The rain " txt = "The rain &**"
x = [Link]("\W", txt) x = [Link]("\W", txt)
print(x) print(x)

Output: Output:
[' ', ' '] [' ', ' ', '&', '*', '*']
5. \s Returns a match where the string contains a white space character

Example 1: Example 2:
import re import re
txt = "This is regular expression" txt = "regularexpression"
#Return a match at every white-space character: #Return a match at every white-space character:
x = [Link]("\s", txt) x = [Link]("\s", txt)
print(x) print(x)

Output: Output:
[' ', ' ', ' '] []

6. \S Returns a match where the string DOES NOT contain a white space character

Example 1: Example 2:
import re import re
txt = "Python" txt = "Python"
#Return a match at every NON white-space character: #Return a match at every NON white-space character:
x = [Link]("\S", txt) x = [Link]("\S", txt)
print(x) print(x)

Output: Output:
['P', 'y', 't', 'h', 'o', 'n'] ['P', 'y', 't', 'h', 'o', 'n']
7. \b Returns a match where the specified characters are at the beginning or at the end of a word

Example 1: Example 2:
import re import re
txt = "hello World" txt = "hello World"
#Check if "hello" is present at the beginning of a WORD: #Check if "ello" is present at the beginning of a WORD:
x = [Link]("\bhello", txt) x = [Link]("\bello", txt)
print(x) print(x)

Output: Output:
['hello'] []

Example 1:
Example 2:
import re
import re
txt = "The rain"
txt = "The rain"
#Check if "ain" is present at the end of a WORD:
#Check if "ra" is present at the end of a WORD:
x = [Link](r"ain\b", txt)
x = [Link]("ra\b", txt)
print(x)
print(x)
Output:
Output:
['ain']
[]
Returns a match where the specified characters are present, but NOT at the beginning (or at the end)
8. \B of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw string")

Example 1: Example 2:
import re import re
txt = "The rain" txt = "The rain"
#Check if "ain" is present, but NOT at the beginning of a word: #Check if "ain" is present, but NOT at the end of a word:
x = [Link](r"\Bain", txt) x = [Link](r"ain\B", txt)
print(x) print(x)

Output: Output:
['ain'] []

9. \Z Returns a match if the specified characters are at the end of the string

Example:
import re Output:
txt = "The rain" ['rain']
#Check if the string ends with “rain":
x = [Link]("rain\Z", txt)
print(x)

You might also like