Sunteți pe pagina 1din 12

A decorator is a function that takes one function as input and returns another function.

add @decorator_name before the function that you want to decorate.


Example 1
def add_it(func1):
def new_func(*args,**kwargs):
result=func1(*args,**kwargs)
print('result',result)
return result
return new_func

def square_it(func2):
def new_func(*args,**kwargs):
result=func2(*args,**kwargs)
print('result',result)
return result
return new_func

@add_it
def add_ints(a,b):
return a+b

@square_it
def square_ints(a):
return a*a

c=add_ints(3,5)
print(c)
d=square_ints(5)
print(d)

Example2

def smart_divide(func):
def inner(a,b):
print("I am going to divide",a,"and",b)
if b == 0:
print("Whoops! cannot divide")
return

return func(a,b)
return inner

@smart_divide
def divide(a,b):
return a/b

Exception Handling

An exception is an error that happens during execution of a program. Exceptions are


convenient in many ways for handling errors and special conditions in a program. Illegal
operations can raise exceptions. There are plenty of built-in exceptions in Python that are
raised when corresponding errors occur.

Python Built-in Exceptions

Exception Cause of Error

AssertionError Raised when assert statement fails.

AttributeError Raised when attribute assignment or reference fails.

EOFError Raised when the input() functions hits end-of-file condition.

FloatingPointError Raised when a floating point operation fails.

GeneratorExit Raise when a generator's close() method is called.

ImportError Raised when the imported module is not found.

IndexError Raised when index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).

MemoryError Raised when an operation runs out of memory.

NameError Raised when a variable is not found in local or global scope.

NotImplementedError Raised by abstract methods.

OSError Raised when system operation causes system related error.

OverflowError Raised when result of an arithmetic operation is too large to be


represented.

Raised when a weak reference proxy is used to access a garbage


ReferenceError
collected referent.

RuntimeError Raised when an error does not fall under any other category.

Raised by next() function to indicate that there is no further item


StopIteration
to be returned by iterator.

SyntaxError Raised by parser when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TabError Raised when indentation consists of inconsistent tabs and spaces.

SystemError Raised when interpreter detects internal error.

SystemExit Raised by sys.exit() function.

Raised when a function or operation is applied to an object of


TypeError
incorrect type.

Raised when a reference is made to a local variable in a function


UnboundLocalError
or method, but no value has been bound to that variable.

Raised when a Unicode-related encoding or decoding error


UnicodeError
occurs.

UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.

UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.

UnicodeTranslateError Raised when a Unicode-related error occurs during translating.

Raised when a function gets argument of correct type but


ValueError
improper value.

Raised when second operand of division or modulo operation is


ZeroDivisionError
zero.
Built-in and user-defined exceptions in Python using try, except and finally statements.
user-defined exceptions
class CustomError(Exception):
"""Base class for other exceptions"""

class ValueSmall(CustomError):
"""Raised when the input value is too small"""

class ValueLarge(CustomError):
"""Raised when the input value is too large"""

number = 10

while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueSmall
elif i_num > number:
raise ValueLarge
break
except ValueSmall:
print("This value is too small, try again!")
print()
except ValueLarge:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

Regular expression

Regular expression is a sequence of character(s) mainly used to find and replace patterns
in a string or file. In Python, we have module “re” that helps with regular expressions. So
you need to import library re before you can use regular expressions in Python.

Import re

The most common uses of regular expressions are:


 Search a string (search and match)
Finding a string (findall)

Break string into a sub strings (split)

Replace part of a string (sub)

The ‘re’ package provides multiple methods to perform queries on an input string.
1. re.match()
2. re.search()
3. re.findall()
4. re.split()
5. re.sub()
6. re.compile()
Regular expressions can specify patterns, not just fixed characters. Here are the most
commonly used operators that helps to generate an expression to represent required
characters in a string or file. It is commonly used in web scrapping and text mining to
extract required information.

Operators Description
. Matches with any single character except newline ‘\n’.
? match 0 or 1 occurrence of the pattern to its left
+ 1 or more occurrences of the pattern to its left
* 0 or more occurrences of the pattern to its left
Matches with a alphanumeric character whereas \W (upper case W) matches non a
\w
character.
\d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
Matches with a single white space character (space, newline, return, tab, form) and \S (u
\s
matches any non-white space character.
\b boundary between word and non-word and /B is opposite of /b
Matches any single character in a square bracket and [^..] matches any single character
[..]
bracket
\ It is used for special meaning characters like \. to match a period or \+ for plus sign.
^ and $ ^ and $ match the start or end of the string respectively
Matches at least n and at most m occurrences of preceding expression if we write it as
{n,m}
will return at least any minimum occurrence to max m preceding expression.
a| b Matches either a or b
() Groups regular expressions and returns matched text
\t, \n, \r Matches tab, newline, return
Regular expression Sample

Match

If zero or more characters at the beginning of string match the regular expression
pattern, return a corresponding MatchObject instance. Return None if the string
does not match the pattern; note that this is different from a zero-length match.

import re
st="The rain and spain in plain"
r=re.match("The",st)
if(r):
print("there is amatch")
else:
print("no match")
print(r.start())
print(r.end())
print(r.span())

Note: If you want to locate a match anywhere in string, use search() instead.

Search

Scan through string looking for a location where the regular expression pattern
produces a match, and return a corresponding MatchObject instance.
Return None if no position in the string matches the pattern; note that this is
different from finding a zero-length match at some point in the string.

import re
st="The rain and spain in plain"
r=re.search("spain",st)
if(r):
print("there is amatch")
else:
print("no match")
print(r.start())
print(r.end())
print(r.span())
Note: Python offers two different primitive operations based on regular
expressions: match checks for a match only at the beginning of the string,
while search checks for a match anywhere in the string

The re.findall() method

The re.findall() helps to get a list of all matching patterns. It searches from start or
end of the given string. If we use method findall to search for a pattern in a given
string it will return all occurrences of the pattern. While searching a pattern, it is
recommended to use re.findall() always, it works like re.search() and re.match()
both.

The split() Function


The split() function returns a list where the string has been split at each match:

import re

str = "The rain in spain is on plain"


x = re.split("\s", str)
print(x)

The sub() Function


The sub() function replaces the matches with the text of your choice:

Replace every white-space character with the number 9:


import re

str = "The rain in Spain"


x = re.sub("\s", "9", str)
print(x)

To check the validity of a phone number

import re
li=['9842710025','0000000900','99999x9999']
for val in li:
if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
print("yes")
else:
print("no")
Print Email Address

search() versus match()


The match() function checks for a match only at the beginning of the string (by default)
whereas the search() function checks for a match anywhere in the string.
findall(pattern, string, flags=0)
Finds all the possible matches in the entire sequence and returns them as a list of strings.
Each returned string represents one match.

Calendar in Python
Calendar module in Python has the calendar class that allows the calculations for various
task based on date, month, and year. Python defines an inbuilt module “calendar” which
handles operations related to calendar.

Calendar class creates a Calendar object. A Calendar object provides several methods that
can be used for preparing the calendar data for formatting. This class doesn’t do any
formatting itself. This is the job of subclasses. Calendar class allows the calculations for
various task based on date, month, and year.

Display calendar of the given year

month (year, month, w, l) :- This function prints the month of a specific yearmentioned
in arguments. It takes 4 arguments, year, month, width of characters and no. of lines
taken by a week.

Packages in Python

A package is basically a directory with Python files and a file with the name __init__.py. This
means that every directory inside of the Python path, which contains a file named __init__.py,
will be treated as a package by Python. It's possible to put several modules into a Package.

Packages are a way of structuring Python’s module namespace by using "dotted module names".
A.B stands for a submodule named B in a package named A. Two different packages like P1 and
P2 can both have modules with the same name, let's say A, for example. The submodule A of the
package P1 and the submodule A of the package P2 can be totally different.
A package is imported like a "normal" module.
from <package_name> import <modules_name>[, <module_name> ...]
from <package_name> import <module_name> as <alt_name>

To import more than one module


from <package_name> import *

First of all, we need a directory. The name of this directory will be the name of the package,
which we want to create. We will call our package "simple_package". This directory needs to
contain a file with the name "__init__.py". This file can be empty, or it can contain valid Python
code. This code will be executed when a package will be imported, so it can be used to initialize
a package, e.g. to make sure that some other modules are imported or some values set. Now we
can put into this directory all the Python files which will be the submodules of our module.
We create two simple files a.py and b.py just for the sake of filling the package with modules.
The content of a.py:
def bar():
print("Hello, function 'bar' from module 'a' calling")

The content of b.py:


def foo():
print("Hello, function 'foo' from module 'b' calling")
We can see that the package simple_package has been loaded but neither the module "a" nor the
module "b"! We can import the modules a and b in the following way:
>>> from simple_package import a, b
>>> a.bar()
Hello, function 'bar' from module 'a' calling
>>> b.foo()
Hello, function 'foo' from module 'b' calling
>>>
As we have seen at the beginning of the chapter, we can't access neither "a" nor "b" by solely
importing simple_package.

Yet, there is a way to automatically load these modules. We can use the file __init__.py for this
purpose. All we have to do is add the following lines to the so far empty file __init__.py:
import simple_package.a
import simple_package.b
It will work now:
>>> import simple_package
>>>
>>> simple_package.a.bar()
Hello, function 'bar' from module 'a' calling
>>>
>>> simple_package.b.foo()
Hello, function 'foo' from module 'b' calling

Subpackages
Packages can contain nested subpackages to arbitrary depth.
Inheritance and method overriding

Override means having two methods with the same name but doing different tasks. It means that
one of the methods overrides the other. If there is any method in the superclass and a method
with the same name in a subclass, then by executing the method, the method of the
corresponding class will be executed.

Example1
class Person:
def __init__(self, name,age):
self.name = name
self.age = age

def display(self):
print("Name", self.name,"Age",self.age)

class Employee(Person):
def __init__(self, name,age,salary):
self.name = name
self.age = age
self.salary=salary
def display(self):
print("Name", self.name,"Age",self.age,"Salary",self.salary)
class Student(Person):
def __init__(self, name,age,marks):
self.name = name
self.age = age
self.marks=marks
def display(self):
print("Name", self.name,"Age",self.age,"Marks",self.marks)
p1=Person("Kalai",23)
p1.display()
e1=Employee("Deepa",45,60000)
e1.display()
s1=Student("Suganth",10,100)
s1.display()

Example2

Since the method from the coressponding class came into action, it means that one overrode the
other. Execution of 'getArea' on the object of Rectangle (r) printed "8 is area of rectangle" from
the 'getArea' defined in the Rectangle class whereas, execution of 'getArea' on the object of
Square (s) printed "16 is area of square" from the 'getArea' defined in the Square class.
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
print(self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()

S-ar putea să vă placă și