Documente Academic
Documente Profesional
Documente Cultură
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
KeyboardInterrupt Raised when the user hits interrupt key (Ctrl+c or delete).
RuntimeError Raised when an error does not fall under any other category.
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()
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
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() 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.
import re
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
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.
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>
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")
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()