0% found this document useful (0 votes)
106 views

Python Handwritten Notes

Python regular expressions or regex is used to search and find patterns in strings. Some key regex concepts include special characters like period, caret, dollar, brackets, parentheses; quantifiers like *, +, ?; character classes; and methods like search, findall, split, sub. Regex provides powerful string parsing capabilities in Python.

Uploaded by

Velammal .M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Python Handwritten Notes

Python regular expressions or regex is used to search and find patterns in strings. Some key regex concepts include special characters like period, caret, dollar, brackets, parentheses; quantifiers like *, +, ?; character classes; and methods like search, findall, split, sub. Regex provides powerful string parsing capabilities in Python.

Uploaded by

Velammal .M
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Python

Note
By – Samim Aktar
R. object orjeoled boqyowming
Concept of oop:
>’ cop is noking bat tie obect oaened
>Tws mainy
tocuses on pgyamig
72usable code- DXY con cept.
>O0p maKes the program eay to ondextavd az well nel| 4 fet.
class;
AclaAs is a blue paivt o the
class Bak: olject.
pass
obect:
An oljecf as
Instonce is an insntiation. of a dass
>Here varjale s ae alled
metkods, aribudes and fnctons
2-iit_method:
’ Atbibues are
defined in
the frst method to oum 9 SOonkisa2method of he alass and t is
cleds BGnk Aceount(J; the objeet is cseated.
defint. (self nome, balance) :
self.balance balan ce
s Creatvg okiect self. mame =mame
Useo 1= BamkAccount Samiwn'
Vses22 lo606)
Methods
Bam-Aca0unt
aka tuefons:
(A Rtor', 5000)

def disglay (sf):


defit-(selt name,
self. lbalamce. balambalan ce):
= ee
phnt(vailable bala
mee: ,
selt. name =name
det deposit (sefs def sithdraskadanee)
(sa,aman):
self. balanee amoont):
+= am OUnt sef. balanee -= amoun
25/0r/22
eode
class Bok Accoont():
def-it- (sef name, balance):u t
self. balance = balance
User2 Bam Accoont ('AKto
self. mame = name
20:t)
def cdepos (self, amoont) :
self. balan ce t- ambunt Userl. withdi(2s)
def oitt dru (sel amoont):he
self. balance -= amo ont Users. depo sit (1so)
Dserg.
det diaplag (se);
pint "Avaiable palance :',self. 2: Availae

balance)ealonce:
Dnheatance:
Snheitance is oay of creain memew elass b
the defails of
othex elass withoat
class Bann AeUnt :
def--tt (self, mome, balance):
self. balance mbalamcelass
Sef. nome = Mame ChiBanAccooteank
Aceoont):
defpost (Gelf. amoun):
sef. balonce + balmceeif amoont <= I000:
def witidow(self, am00nt): self. balanee
-= Qmoun
self. balance Qmount else
print( con not
paint'Available balance :
self, balan ee)
Csde
# paret class
class Bamk-A ccoont :
dof -- nit- (selt, mame,
self.mame. -=Mame balance) :
self. balance = balance
def deposit(ey,emouni):
Self. balon ce += aane anoun
def nitdasosdf, amount):

pint( Avalicksle eaance:', self. balance)


# cild class
class child Gontecount (eomAcant :
def woitcaa (self, amoont):
ifamount < 2000 : o
sett. balance =
else:
pont ('oith dsaus amoort
eeede,)
Usex ct =
ehildBanKAceount('chldname o)
uSes
UScs
iHthdrau so, Userci,di spay
s)
USer . wiow
22/0F/22
> Nesy creted chss is deved claS O8 child alas and
class is alled se oX pesent clads .
ensin
’ Since class is shamble code can be reusakte
’ Mulfiple inhesitance, multipla leel inhetance
fmoiple nhe itance #molti level Shhetan ce
clss Base4:
paAs o i o e pass
hestus
e a poot ckus Deaived1(Gase).
class Base2i
pass pas
class MulhDe jved (B aJel,Bas2): class Deied2 (Dejvedj
pasc paes
# Encapsolaion: o
>Restict divect
nethods present inacess or madfcation of ag
a class is
Pivde aibes: 0' called encapsWati.
Dota is safe and ondexscoYe.
’ Use seaue.coe
getex ao setex
dass Bike:
metkods to aecess pivcje vaioblec

def--iit(self):
Sef. -mupice =900
def sel (se):
def cetMakice (sef pice):
setf mtprice pice
= 0Sa seter fonchon
Csell 0 e. setMonfice( tor)
C. Sell (U
#toy to clang tle price
e. selt l)
# Polymoaphism :
’he iond fehynoxphism means haw

Þh poogyamhg polygmosphism meons houri sone tmetion.


mame but diffeent sghetes
’ same intesfaoe
> Metkod overádig
fatRon doent vs function arguments <fox method sgane
tRats ohy metiod 'sesoading is nbt supposted in
cass Rbit)
def
plint(is fonction ceBemines he age of Kabbit.")
def color(set):
pint ("Tis funcien detesmines the dox of
chis Horse U: 21 220 kabit."

color
pint ("
(" thisfunfion dele~ nines the colbr of tose.")

def fun interface (okj):


Ob. co toaCJ
fen interfaee (o)
fon - intertace (okj?y
Nompy
isa packye for scientfe comldion. Usig Nong
D6/oF/2
we can peom mahemahcal and toglcal opexcicn on amays.

psint(ar)
pint (aar)
2: Ce.2x3 45]

point (am)
pont 'nombes of simenicon :', G8. ndin)
(ttC 123 J]J] pint (omttpr)
numbes of dimen son :4
np.arey CC2,3,45
pönt{'2rd dement o 1t din:', m prntLast elemet fom
2hd elenent on 19t din:7t 2nd dim: ', am-2
Lastelemert fom 2nd din:to
O# slicing staot: end: ste

pint iipint(am, dhype)

pint (mew- am)


) print (ne ar dhyel
9,10, M, )
pint (es an
point(aw)
newa=aareshpe(-)
point (rao am)
[4,5,6]
L12345]
o4/bg2
np ancom. nd int (to, 50, size=6)
emag (C21, s5, 43, 23, 34,24)
- mpamay(Ce,2,)
b

print (at
print a
point (Y)
pint (at)
Pondaa
>fondes is the Pythoni libraay vsed-to anayze he
sesies: Apaudaa sexies is ike acoun inn atable.
a
data.
g+ is me-dimentionl amay haldug,data gf an) e.
a Dalafone: Apavdo, batafiame is a zdimen sional da sucre
ike a2-cdimcnsioral amay,oY a table ik
colwms
# mpovhig tie egiad tibaies!
imposf pavdas a pd
pd.
o Renlar expression
>legulor Expession ox KeEx is used to seach
stivg
oG|o2
pytfion but n module e gor egularpeon.
Rezx Syrext te functonNome(atem, stsin
finctions:
) semch- vetums match object if there is match ia
the sting
Dfndall- vetvms a tist containg al matehes
u)Sub - eplate One og mamy mtches itHG a
i) soltt- getuons a ist hen he hao lbeen
spit at each match! ,0.0.) staiug
import
-'Samim Artar,° kegular Expression
out
efndad (iAvtar,
pint (out) stig)
Retun an
import matchfod.
"Samim treaa, Kgular Expression"
out'e oe fin dal!"Rabul, sting)

out =e
prnt (out)
4one,
impoat re
stilng -"Neoton schol,Reglar Exrpression'
out = e spit(.,

'Neatn schol, Regular Expecdon sehoo!'.B


ot =2
pänt (ou) substitude
2 NaNton schonl. fgyulor
Out e,sub
xpression.k
paint(o)
.N.e.Dto. n. S. C.h,o, 0.(... Re.g.u.l.a.r. Exp,T.e, s.s.i.6H
paltem='...(!
Aest stoig = Wewtont'
Result e. mateh (ptem, 4est staig)
if desult:
point"seanch successul.")
else:
point ("se anch onsuccessfu.")
e Metachaactexs:

co-qyane brackets: Square brackets se cifies a setof


charactess gou oishto match,
e [abe - opanssion o ta-e)- a,bjc, d, e
Co- - o, 1, 2..9,
stig
B5)
> Apeiod matches ang singe ehoacfer (ex cept eslme
A
set of chaces

occutYen ces
t : One ox more ccC umences HdT
tie specfed mumber
mUmbey of ccuYren ce.

Dr: coptuse ad
:Retums a mateh if the spe ofed chma ctexs ane
bejnning he s t a i g i e
\w: Rtuns a nateh hee'
staingcontains
charatkxs (charachess fom
rom a to 2, digis fom
e onderscore_ charaater)6u o-q,and
s:Retusns a matoh oheve
chanacter, ke staiv contains
conans a niBe space
D\d: Retvns a mateh
nhee the staig cortain
containss dits
"\ (ronber
inpoat e
stig -'hello 12 hi 89., Ho
patfean = 'la'
45
"4,'5]
deSUlt = e findall (patem, stai) pairnt ( teslt) )t
impost e mpot.ve
staing = 'hello 12 hi e9.to 45 ema) ="SamimaKBar. ee egmail.can"
palfern = Teg=-2 0-+[v-?e204
Pesu|t =eindal! (elfem, staing)
Pairt (gesul) out 2. seorth| agen,sbgenal)
'2', '39, 45|

MuH Taskigs Ere carting eeral tasks simultaneousy


tooo
» focess based: Each ask isa sepante independot
proes-0s level.
D T5xead kased Each task is incependent of same
programftow f recution - app lovel.
wheze vex thexe is independent pb zuiement
cam vse mull; heading camcept.
muli the
Using multh threadi pestosnmance is going to incxease ard
jobs Cam be H6 mless thme
>
L> General sense mulhtreacig is the ability ofa poe
ssoy to ecude muliple tieas concuaenthy.
madule to mgemment tais
mtivreacing
e
concep
Each tbrend hae its on ife cycle.
Main ineod is independen f Lfechildcycle.
toead
Using Thead cdass we cioate 4read objeef.
t- Thyeod (taaget =chidhzeot)
Code
fom threndig import **
def childtread (): t ltt
for e in Tange (i59):
pint (" child Thveod')
4= Tiyeod (target =ethread).

pint "Man Thread )


clas abj csaafng hreacl:
class wyelaus):
def fon- mame (sel):
tox iin range (19:
oQj- Mycess0
t- The.ad (taget= ojfen. ame)
# set ond get tread name.:
class Myclass (): |pent (cuinent. hendu-geNond)
def Jon-name (satf): eunent_trebd ). sefvomelilat
pant (cunenttread ): getNomd)
point ("c Hhread')
pornt (cunenreodi).nawme)
t= Threodtarget =obj.fun- mame, name= "Cild Thread-1)
Get identfcation mumber of threads: :0
’ paint (cuwent. ead U. idest)
Get number of aetle trends:
’ point (aehve-counk)
>T6 check tread is alie oy not ?
’point (4.is Actve )
code: Impoxt tne
cloas Myclass ):
for i in Tange (s):
paint ("child thead ")
point (curentreod name)
prin (aetie- coont 0)
pint (4 isActie u)
o Myclass ()
t= Thyeod(target=ojon mame, nome, ="chid Threod)
t. tat
psint (cuert thread (U. ident)
pönt (activeicoont 0)
pint (tisAlve) eo
# Serators:
o teralle:
tat can Loop oveY in Pon is caled iterasle.
d, tuple, set
>S Pgton, an aiject wlich imglements ke -teyJmely
is alled an iteeble.
’ exator in pthon is simply an olject tiat an atusn data
One ata time le teat oves i
’fox obiect to a Shertor t must implemants too mehods:
--ter)
ext ()h2g
avoide tais, covpleatt Gene atort
# Gereatr :
Qeneraor is tie elerpt aoy to iCeate custori teator.
Thee i a lot ok inin
lot of sok
we have to imglement a cdass bulding an terator in ption .
oit-tex) andnt)
metiod, keep tackk of intemal stales,
hen there are ho
avd 7aise stoplteraion
values to be retugned
Sinpypeoa enesator is a funcHon. hat retuns an
alject (testoy) we Cam
iterae over ne vale at atime
9 is a
defing a nogml -fncfon, but
staemen ingte ofa retüm staement. at azied
he dfe yerce is hat oile a etn stotement tmirade
a fonction enterehy, ield ctanent pause the
finchon.
al, its stakes ond loter cotinee_ fon tßere SUCe
#peesraor
Adecovato takes n afcton, cdds sone tumeton ality
Gnd etuÝs it
ytfion hos an htegestirg fectre caled decsratos to odd
Jfncienality to an oachcode.
Code
def printey):
print ("slep s)
paint("Helo Nesto')
sep
def dglytn):
pant* stepi)
def imer (0:
pint ("step 2) Aished eeouton
print("Eeoting fone...ame mctis,")
ouncQ
pirt ("Fniched eoution) aptnisaton
pont (" step 12) def dagay fne)
tetun nney def iner U:
digplag (inte) pit ("EKecuting" fonc
n) -nam --)foncion)

obe Exeoutig poihter fenction ohnt("Finished exeenho!)


Hello Neton 2etun innex

fAnished etecrtion. dieploy


def pimter):
point ("Hello Nlaton")
pintex ()

You might also like