PYTHON
PROGRAMMING
UNIT IV
Regular Expressions :
Concept of regular expression :
A regular expression is a special sequence of characters that helps you match or find
other strings or sets of strings, using a specialized syntax held in a pattern.
The module re provides full support for regular expressions in Python. The re module
raises the exception [Link] if an error occurs while compiling or using a regular
expression.
There are various characters, which would have special meaning when they are used in
regular expression. To avoid any confusion while dealing with regular expressions, we
would use Raw Strings as r'expression’.
Ex. "Hello, you can reach us at 9876543210 or 1234567890 for customer service. If
those lines are busy, try calling 5551234567 or 8889990001. We also have a toll-free
number at 8001234567 for your convenience.“
\d{10}
2)Various types of regular expressions:
Basic patterns that match single chars
a, X, 9 -- ordinary characters just match themselves exactly.
. (a period) -- matches any single character except newline '\n'
\w -- matches a "word" character: a letter or digit or underbar [a-zA-Z0- 9_].
\W -- matches any non-word character.
\b -- boundary between word and non-word
\s -- matches a single whitespace character -- space, newline, tab
\S -- matches any non-whitespace character.
\t, \n-- tab, newline
\d -- decimal digit [0-9]
^ -- matches start of the string
$ -- match the end of the string
\ -- inhibit the "specialness" of a character.
\d{1, 5} –- matches a digit between 1 and 5 in lengths
Using match function.:
This function attempts to match RE pattern to string with optional flags. Here is the
syntax for this function-
[Link](pattern, string, flags=0)
import re
# Example pattern: match the word "hello" at the start of the string, case-insensitive
pattern = r'hello’
# String to search
text = "Hello world“
# Use [Link]() with the IGNORECASE flag to ignore case sensitivity
match = [Link](pattern, text, flags=[Link])
if match:
print("Match found:", [Link]())
else:
print("No match")
O/p
Match found: Hello
Overview of OOP(Object Oriented Programming) :
Python is an object-oriented programming language, which means that it provides
features that support object-oriented programming (OOP).
Object-oriented programming has its roots in the 1960s, but it wasn’t until the mid
1990s that it became the main programming paradigm used in the creation of new
software.
Object Object is anything in the real world that contains some unique characteristics. It
has state and behavior. It may be physical and logical. For example: mouse, keyboard,
chair, table, pen etc.
Class: The Class is a collection of objects. It is a logical entity that has some specific
attributes and methods. For example: if you have a student class then it should contain
an attribute and method i.e. An name, standard, age etc.
Method: The method is defined as a group of statements enclosed together to achieve
specific task. It is associated with an object. In Python, method is not unique to class
instances. Any object type can have their own methods
Inheritance: Inheritance can be defined as characteristic transferring technique. A
feature of one class can be shared with another class through inheritance. It means one
object acquires the properties and behaviors of parent object. With inheritance you can
define a new class with a little or no changes to the existing class. The new class is
known as derived class or child class and from which it inherits the properties is called
base class or parent class. It provides re-usability of the code.
Polymorphism: Polymorphism is the ability to present the same interface for differing
underlying forms. Poly means many and Morphs means form, shape. Polymorphic
functions or methods can be applied to arguments of different types, and they can
behave differently depending on the type of the arguments to which they are applied.
Encapsulation: Encapsulation is used to restrict access to methods and variables. Here
code and data are wrapped together within a single unit from being modified by
accident
Data Abstraction: Hiding the implementation details is called as data abstraction. It
almost similar concept to encapsulation as data abstraction is achieved through
encapsulation only. It shows functionalities while hiding the internal details. Abstracting
something means to give names to things, so that the name captures the core of what
a function or a whole program does.
Class Definition:
The class statement creates a new class definition. The name of the class immediately follows the
keyword class followed by a colon as follows-
Syntax:
class class_name:
[statement 1]
[statement 2]
[statement N]
Ex:
#Pr.10.1 Program to write simple class demonstration.
class st():
def show(self):
print(“hello”)
s=st()
[Link]()
O/P
hello
Self attribute: The first argument of every class method is always a reference to the current instance of
the class. By convention, this argument is always named self. It is part of the Python syntax to access
members of objects.
Private variables: Private means the attributes are only available for the members of the class not for
the outside of the class. A private variable can only be changed within a class method and not outside
of the class. In python private variables begins with double underscores (_).
#Pr.10.2 Program to use private variable
class st():
y=2
_v=4 #private variable
def show(self):
print(“hello”) OUTPUT
hello
s=st()
2
[Link]() Traceback (most recent call last):
File “C:/Python34/[Link]”, line 10, in <module>
print(s.y)
print(s._v)
print(s._v) #Gives error because_v is private variable AttributeError: ‘st’ object has no attribute ‘_v’
Built-in Class Attributes:
Every Python class keeps the following built-in attributes and they can be accessed using dot
operator like any other attribute −
1.__doc__: It is a class documentation string or none, if undefined.
2.__dict__: It represents dictionary containing the class's namespace.
3. __name__: It represents class name.
4. __module__: It represents module name in which the class is defined. This attribute is
“__main__" in interactive mode.
6. __bases__: It represents empty tuple containing the base classes, in the order of their
occurrence in the base class list.
Ex: #Pr.10.4 Program to show built-in class attributes
class st:
“Hello”
s=2
_t=3 #Private variable not accessible for outside class
print(“sts: “,st.s)
print(“st._doc_ = “,st._doc_)
print(“st_dict_ = “,st._dict_)
print(“st_name_= “,st_name_)
print(“st_module_ = “,st_module_)
print(“st_bases_ = “,st._bases_)
OUTPUT
st.s: 2
st_doc_ Hello
st_dict_= {‘_doc_’: ‘Hello’, ‘_module_’: ‘_main_’, ‘_st_t’: 3, ‘_dict_’: <attribute ‘_dict_’ of ‘st’ objects>, ‘_weakref_’:
<attribute ‘_weakref_’ of ‘st’ objects>, ‘s’: 2)
st name =st
st_module=__main__
st_bases_ = (<class ‘object’>,)
Creating Objects:
After class definition we can create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
Syntax:
myObj=MyClass()
Ex: obj = MyClass()
The above syntax will create a new instance object named obj. We can access attributes of
objects using the object name prefix. Attributes may be data or method.
Ex.
class st():
def show(self):
print(“hello”)
s=st()
[Link]()
O/p
hello
Inheritance:
Inheritance refers to defining a new class with little or no modification to an existing class. The new class is called
derived class and the one from which it inherits is called the base class. The existing class is called the parent and
the new class is called the child.
Single Inheritance:
Syntax:
class BaseClass:
Statements
class DerivedClass(BaseClass):
Statements
Ex.#Pr.10.12 Program to use single inheritance
class st:
def s1(self):
print("Base Class")
class st1(st):
def s2(self):
print("Derived Class")
t=st1() OUTPUT
t.s1() Base Class
t.s2()
Derived Class
Multiple Inheritance in Python: In multiple Inheritance we can use more than one base
class to achieve single child class.
Syntax:
class BaseClass1:
Statements
class BaseClass2:
Statements
class DerivedClass (BaseClass1, BaseClass2):
Statements
#Pr.10.13 Program to use multiple inheritance
class st1:
def num1(self):
self.n1 = 7
print(“num1: “,self.n1)
class st2:
def num2(self):
self.n2=5
print(“num1: “,self.n2)
class st(st2,st1):
def add1 (self):
return self.n1+self.n2
s=st()
s.num1()
s.num2()
print(s.add1())
OUTPUT
num1: 7
num1: 5
12
Method Overriding:
The method overriding allows a subclass or child class to provide a specific implementation of a
method that is already provided by one of its super classes or parent classes. One reason for
overriding parent’s methods is because you may want special or different functionality in your
subclass.
Data Hiding:
Sometimes we want that object's attributes may or may not be visible outside the class
definition. You need to name attributes with a double underscore prefix, and those attributes then
will not be directly visible to outsiders.
Ex.
#Pr.10.17 Program to use data hiding
class st:
__p = 0
def show(self):
self. P = self._p+1
print(self._p)
OUTPUT
v = st() 1
[Link]() 2
Traceback (most recent call last):
[Link]() File “C:/Python34/[Link]”, line 10, in <module>
print(v._p)
#_p is hidden for outside class so error occurs
AttributeError: ‘st’ object has no attribute ‘_p’
print(v._p)
Modules:
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Python provides some built in modules that are very useful while creating the application in
python. We can also make our own modules which are referred as user defined modules.
Math module
The math module used to provide mathematical help in programs in the form of built in
functions and options. To use math module in our program we have to import it at the start
of be program as “import math”. The math module provides following built in functions:
1. abs(): This method returns absolute value of zero. X, as positive distance between x and
zero
Syntax: [Link](x)
Where x = This is a numeric expression.
2. ceil(): This method returns ceiling value of x, as smallest integer not less than x. Syntax:
[Link](x)
Where x = This is a numeric expression.
3. cmp(): This method returns the sign of the difference of two numbers as 1 if x < y, 0 if x
== y, or 1 if x > y.
Syntax: [Link](x, y)
Where x = This is a numeric expression.
Y = This is also a numeric expression.
4. exp(): This method returns exponential of x, ie. ex
Syntax: [Link](x)
Where x = This is a numeric expression.
5. floor(): This method returns floor of x means the largest integer not greater than x.
Syntax: [Link](x)
Where x = This is a numeric expression.
6. log(): This method returns natural logarithm of x, for x > 0
Syntax: [Link](x)
Where x = This is a numeric expression.
#Pr.11.5 Program to use math module
import math
print(“[Link](4): “,[Link](4))
print(“[Link]: “,[Link]) Output:
print(“[Link](5.1) : “,[Link](5.1)) [Link](4): 2.0
[Link]: 3.141592653589793
print(“[Link](5.1) : “,[Link](5.1))
[Link](5.1): 6
print(“[Link](3.0): “,[Link](3.0)) [Link](5.1): 5
[Link](3.0): 20.085536923187668
print(“[Link](3.0) : “,[Link](3))
[Link](2.0): 1.0986122886681098
print(“math.log10(2.0): “,math.log10(2)) math.log10(2.0):
print(“[Link](2,3): “,[Link](2,3))
0.3010299956639812
[Link](2,3): 8.0
print(“[Link](90): “,[Link](90)) [Link](90): 1.0
print(“[Link](45): “,[Link](45)) [Link](45): 0.7071067811865476
[Link](0): 0.0
print(“[Link](0) : “,[Link](0))
Time Module:
The time module is used to deal with the date and time related activity code in our program. It also used for
converting between representations. To use math module in our program we have to import it at the start of
program as “import time”. The time module provides following built in functions :
1. [Link]: This method returns the offset of the local DST timezone, in seconds west of UTC, if one is
defined.
Syntax: [Link]
2. [Link]([tupletime]): This method accepts a time-tuple and returns a readable 24-character string
such as ‘Tue Dec 11 [Link] 2008’.
Syntax: [Link]([t]))
Where t = This is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or
localtime() function.
3. [Link](): This method returns the current time instant, a floating-point number of seconds since the
epoch.
Syntax: [Link]()
4. [Link]([secs]): This method accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the UTC time.
Syntax: [Link]([sec])
Where sec = These are the number of seconds to be converted into structure struct_time representation.
5. [Link]([secs]): This method accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the local time.
Syntax: [Link]([sec])
Where sec These are the number of seconds to be converted into structure struct_time [Link]
Ex.
import time
print("1. [Link]:", [Link])
print("2. [Link]():", [Link]())
print("3. [Link]():", [Link]())
print("4. [Link]():", [Link]())
print("5. [Link]():", [Link]())
Output:
1. [Link]: -19800
2. [Link](): Sun Sep 29 [Link] 2024
3. [Link](): time.struct_time(tm_year=2024, tm_mon=9, tm_mday=29, tm_hour=7, tm_min=55,
tm_sec=46, tm_wday=6, tm_yday=273, tm_isdst=0)
4. [Link](): time.struct_time(tm_year=2024, tm_mon=9, tm_mday=29, tm_hour=13, tm_min=25,
tm_sec=46, tm_wday=6, tm_yday=273, tm_isdst=0)
5. [Link](): 1727596546.5289967