0% found this document useful (0 votes)
5 views11 pages

Python Mod 3

Uploaded by

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

Python Mod 3

Uploaded by

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

Sakshi Jain 45208210753 F029

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'.

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.
Syntax:
re.match(pattern, string, flags=0)

Parameter Description
pattern This is the regular expression to be matched.
string This is the string, which would be searched to match the pattern at the beginning of string.
flags You can specify different flags using bitwise OR (I). These are modifiers, which are listed in
the table below.

Flag Meaning
Sakshi Jain 45208210753 F029
ASCII, A Makes several escapes like \w, \b, \s and \d match only on ASCII
characters with the respective property.
DOTALL, S Make, match any character, including newlines
IGNORECASE, I Do case-insensitive matches
LOCALE, L Do a locale-aware match
MULTILINE, M Multi-line matching, affecting ^ and $
VERBOSE, X (for 'extended') Enable verbose REs, which can be organized more cleanly and
understandably

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.

Match Object Methods Description


group(num=0) This method returns entire match (or specific subgroup num)
groups() This method returns all matching subgroups in a tuple (empty if there weren't
any)

Example:
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?).*, line, re.Mre.I) if matchObj:
print ("matchObj.group(): ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1)) print ("matchObj.group(2): ", matchObj.group(2)) else:
print ("No match!!")
Output:
matchObj.group(): Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2): smarter

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)
Sakshi Jain 45208210753 F029
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.
h. Instantiation: The creation of an instance of a class.
i. Method: A special kind of function that is defined in a class definition.
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:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary): # Fixed: added an underscore
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name: ", self.name, ", Salary: ", self.salary)

 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.
Sakshi Jain 45208210753 F029
 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-
o emp1.displayEmployee()
o emp2.displayEmployee()
o print ("Total Employee %d" % Employee.empCount)

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:
Example:
class Student:
NUM_GRADES = 5
def __init__(self, name):
self.name = name
self.grades = []
for i in range(Student.NUM_GRADES):
self.grades.append(0)

Here “self” is a instance and “name” is a argument


The PVM automatically calls the constructor method when the programmer requests a new instance of the
class, as follows: s = Student('Mary')
Sakshi Jain 45208210753 F029
The constructor method always expects at least one argument, self. When the method is called, the object
being instantiated is passed here and thus is bound to self throughout the code. Other arguments may be
given to supply initial values for the object’s data.
Instances as return values:
class Numbers:
MULTIPLIER = None -Here return
def __init__(self, x, y): (self.x+self.y) are the

self.x = x instances as return values.


-Where self is a instance
self.y = y
and .x and .y
def add(self):
are variable associated
return (self.x + self.y) with the instance.

print("Enter two numbers for addition")


x = int(input())
y = int(input())
n = Numbers(x, y)
print("Addition is:", n.add())

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:
o dict: Dictionary containing the class's namespace.
o doc: Class documentation string or none, if undefined.
o name: Class name.
o module: Module name in which the class is defined. This attribute is “main “in interactive mode.
o bases : A possibly empty tuple containing the base classes, in the order of their occurrence in the
base class list.

For the above class let us try to access all these attributes:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Sakshi Jain 45208210753 F029
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, ", Salary:", self.salary)
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)

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.
 Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, ", Salary:", self.salary)
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
Sakshi Jain 45208210753 F029
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)

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.
Example:
class Parent: # Define parent class
def myMethod(self):
print('Calling parent method') Output: Calling child method

class Child(Parent): # Define child class


def myMethod(self):
print('Calling child method')
c = Child() # Instance of Child
c.myMethod() # Child calls overridden method

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:
def print_multiples(n):
i=1
while i <= 6:
print (n * i, "\t",)
i += 1
print()
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.
Sakshi Jain 45208210753 F029

Multithreaded Programming
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:
o threading.activeCount(): Returns the number of thread objects that are active.
o threading.currentThread(): Returns the number of thread objects in the caller's thread control.
o 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.
Sakshi Jain 45208210753 F029
 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.

1) Importing module
a. The import Statement:
 You can use any Python source file as a module by executing an import statement in some other Python
source file.
 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:
Syntax: 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.

b. The from...import Statement


 Python's from statement lets you import specific attributes from a module into the current namespace.
 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 exploring modules: Creating modules


Sakshi Jain 45208210753 F029
 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


o math.ceil(x): Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
o 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.


o math.fabs(x): Return the absolute value of x.
o math.factorial(x): Return x factorial. Raises ValueError if x is not integral or is negative.
o math.floor(x): Return the floor of x as a float, the largest integer value less than or equal to x.
o 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.
o math.frexp(x)
Sakshi Jain 45208210753 F029

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:

Sr.No Function with Description


.
1 time.altzone: The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe, including the
UK). Use this if the daylight is nonzero.
2 time.asctime([tupletime]): Accepts a time-tuple and returns a readable 24-character string such
as 'Tue Dec 11 18:07:14 2008'.
3 time.clock(): Returns the current CPU time as a floating-point number of seconds. To measure
computational costs of different approaches, the value of time.clock is more useful than that of
time.time().
4 time.ctime([secs]): Like asctime(localtime (secs)) and without arguments is like asctime()
5 time.gmtime([secs]): Accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the UTC time. Note: t.tm_isdst is always 0
6 time.localtime([secs]): Accepts an instant expressed in seconds since the epoch and returns a
time-tuple t with the local time (t.tm_isdst is 0 or 1, depending on whether DST applies to instant
secs by local rules).
7 time.mktime(tupletime): Accepts an instant expressed as a time-tuple in local time and returns a
floating- point value with the instant expressed in seconds since the epoch.
8 time.sleep(secs): Suspends the calling thread for secs seconds.
9 time.strftime(fmt[,tupletime]): Accepts an instant expressed as a time-tuple in local time and
returns a string representing the instant as specified by string fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y'): Parses str according to format string
fmt and returns the instant in time-tuple format.
11 time.time( ): Returns the current time instant, a floating-point number of seconds since the
epoch.
12 time.tzset(): Resets the time conversion rules used by the library routines. The environment
variable TZ specifies how this is done.

You might also like