Python Programming Unit IV
Python Programming Unit IV
UNIT IV
PROF.AJAY PASHANKAR
ASSISTANT PROFESSOR DEPARTMENT OF CS & IT
K.M.AGRAWAL COLLEGE KALYAN
www.profajaypashankar.com
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. Regular expressions are
widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module
raises the exception re.error if an error occurs while compiling or using a regular expression.
We would cover two important functions, which would be used to handle regular expressions.
Nevertheless, a small thing first: 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'.
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, return, tab
• \S -- matches any non-whitespace character.
• \t, \n, \r -- tab, newline, return
• \d -- decimal digit [0-9]
• ^ = matches start of the string
• $ = match the end of the string
• \ -- inhibit the "specialness" of a character.
Using match function.:
This function attempts to match RE pattern to string with optional flags. Here is the syntax for
this function-
re.match(pattern, string, flags=0)
The re.match function returns a match object on success, None on failure. We use
group(num) or groups() function of match object to get matched expression.
Classes and Objects:
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.
It was developed as a way to handle the rapidly increasing size and complexity of software
systems, and to make it easier to modify these large and complex systems over time. Up to this
point we have been writing programs using a procedural programming paradigm.
In procedural programming the focus is on writing functions or procedures which operate on
data. In object-oriented programming the focus is on the creation of objects which contain both
data and functionality together.
Overview of OOP (Object Oriented Programming):
a. Class: A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance variables)
and methods, accessed via dot notation.
b. Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used as
frequently as instance variables are.
c. Data member: A class variable or instance variable that holds data associated with a class
and its objects.
d. Function overloading: The assignment of more than one behavior to a particular function.
The operation performed varies by the types of objects or arguments involved.
e. Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
f. Inheritance: The transfer of the characteristics of a class to other classes that are derived
from it.
g. Instance: An individual object of a certain class. An object obj that belongs to a class Circle,
for example, is an instance of the class Circle.
j. Object: A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
k. Operator overloading: The assignment of more than one function to a particular operator.
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-
The variable empCount is a class variable whose value is shared among all the instances of a in this class.
This can be accessed as Employee.empCount from inside the class or outside the class.
• The first method init () is a special method, which is called class constructor or initialization method that
Python calls when you create a new instance of this class.
• You declare other class methods like normal functions with the exception that the first argument to each
method is self. Python adds the self argument to the list for you; you do not need to include it when you
call the methods.
Creating Objects:
To create instances of a class, you call the class using class name and pass inwhatever arguments its init
method accepts.
This would create first object of Employee class emp1 = Employee("Zara", 2000)
This would create second object of Employee class emp2 = Employee("Manni", 5000)
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be accessed
using class name as follows-
emp1.displayEmployee() emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
(4) Instances as Arguments:
Instance variables are always prefixed with the reserved word self. They are typically introduced and
initialized in a constructor method named init .
In the following example, the variables self.name and self.grades are instance variables, whereas the
variable NUM_GRADES is a class variable:
For the above class let us try to access all these attributes-
Inheritance:
Instead of starting from a scratch, you can create a class by deriving it from a pre- existing class by listing
the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were
defined In the child class. A child class can also override data members and methods from the parent.
In a similar way, you can drive a class from multiple parent classes as follows-
You can use issubclass() or isinstance() functions to check a relationship of two classes and instances.
• The issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the
superclass sup.
• The isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an
instance of a subclass of Class.
Method Overriding:
You can always override your parent class methods. One reason for overriding parent's methods is that you
may want special or different functionality in your subclass.
Data Encapsulation:
Simplifying the script by identifying the repeated code and placing it in a function. This is called
’encapsulation’.
Encapsulation is the process of wrapping a piece of code in a function, allowing you to take advantage of all
the things functions are good for.
Generalization means taking something specific, such as printing the multiples of 2, and making it more
general, such as printing the multiples of any integer. This function encapsulates the previous loop and
generalizes it to print multiples of n:
With the argument 4, the output is:
By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly
with different arguments. In fact, we can use another loop:
By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly
with different arguments. In fact, we can use another loop:
Data Hiding:
An 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.
Multithreaded Programming:
(1)Thread Module:
The newer threading module included with Python 2.4 provides much more
powerful, high-level support for threads than the thread module discussed in the
previous section.
The threading module exposes all the methods of the thread module and provides
some additional methods:
• threading.activeCount(): Returns the number of thread objects that are
active.
• threading.currentThread(): Returns the number of thread objects in the
caller's thread control.
• threading.enumerate(): Returns a list of all the thread objects that are
currently active.
In addition to the methods, the threading module has the Thread class that implements
threading. The methods provided by the Thread class are as follows:
• run(): The run() method is the entry point for a thread.
• start(): The start() method starts a thread by calling the runmethod.
• join([time]): The join() waits for threads to terminate.
• isAlive(): The isAlive() method checks whether a thread is still executing.
• getName(): The getName() method returns the name of a thread.
• setName(): The setName() method sets the name of a thread.
Creating a thread:
To implement a new thread using the threading module, you have to do the following−
• Define a new subclass of the Thread class.
• Override the init (self [,args]) method to add additional arguments.
• Then, override the run(self [,args]) method to implement what the thread should do when started.
Once you have created the new Thread subclass, you can create an instance of it and then start a new
thread by invoking the start(), which in turn calls the run()method.
Synchronizing threads:
The threading module provided with Python includes a simple-to-implement locking mechanism that allows
you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force the threads to run synchronously. The
optional blocking parameter enables you to control whether the thread waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a
1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer required.
------------------------------------------------------------------------------------------------------------
multithreaded priority queue:
The Queue module allows you to create a new queue object that can hold a specific number of items. There
are following methods to control the Queue −
• get(): The get() removes and returns an item from the queue.
• put(): The put adds item to a queue.
• qsize() : The qsize() returns the number of items that are currently in the queue.
• empty(): The empty( ) returns True if queue is empty; otherwise, False.
• full(): the full() returns True if queue is full; otherwise, False.
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. A module is a Python object with arbitrarily named attributes that you
can bind and reference.
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.
Example
The Python code for a module named a name normally resides in a file namedaname.py. Here is an example
of a simple module, support.py
1)Importing module:
The import Statement
You can use any Python source file as a module by executing an import statement in some other Python
source file. The import has the following syntax-
When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following command at the top of the
script
Import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following command at the top of the
script-
Import module support import support
# Now you can call defined function that module as follows support.print_func("Zara")
A module is loaded only once, regardless of the number of times it is imported.
This prevents the module execution from happening repeatedly, if multiple imports occur.
The from...import Statement
Python's from statement lets you import specific attributes from a module into the current namespace. The
from...import has the following syntax-
This provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparingly.
(2) Creating and exploringmodules: Creating modules
Creating/Writing Python modules is very simple. To create a module of your own, simply create a new .py
file with the module name, and then import it using the Python file name (without the .py extension) using
the import command.
Exploring built-in modules
Two very important functions come in handy when exploring modules in Python - the dir and help functions.
We can look for which functions are implemented in each module by using the dir function:
Example:
>>> import urllib
>>> dir(urllib)
[' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' path ', ' spec ', 'parse']
Math module :
This module is always available. It provides access to the mathematical functions defined by the C
standard.
These functions cannot be used with complex numbers; use the functions of the same name from the
cmath module if you require support for complex numbers. The distinction between functions which
support complex numbers and those which don’t is made since most users do not want to learn quite as
much mathematics as required to understand complex numbers.
Receiving an exception instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it was generated in
the first place.
The following functions are provided by this module. Except when explicitly noted otherwise, all return
values are floats.
(a) Number-theoretic and representation functions
math.ceil(x)
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
math.copysign(x, y)
Return x with the sign of y. On a platform that supports signed zeros, copysign(1.0, - 0.0) returns -1.0.
New in version 2.6.
math.fabs(x)
Return the absolute value of x.
math.factorial(x)
Return x factorial. Raises ValueError if x is not integral or is negative.
New in version 2.6.
math.floor(x) Return the floor of x as a float, the largest integer value less than or equal to x.
math.fmod(x, y)
Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y
may not return the same result. The intent of the C standard is
that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some
integer n such that the result has the same sign as x and magnitude less than abs(y).
Python’s x % y returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -
1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to
the surprising 1e100. For this reason, function fmod() is generally preferred when working with
floats, while Python’s x % y is preferred when working with integers.
math.frexp(x)
Random module:
This module implements pseudo-random number generators for various distributions. For integers, there is
uniform selection from a range. For sequences, there is uniform selection of a random element, a function
to generate a random permutation of a list in-
Time Module:
Time Module:
Thank you stay connected :
VISIT
https://www.profajaypashankar.com
For more study material and notes .
VISIT
https://www.youtube.com/channel/UCu4Bd22zM6RpvHWC9YHBh5Q?view_as=subscriber
For more lectures .