0% found this document useful (0 votes)
8 views16 pages

Python Sem2

The document provides various examples and explanations of Python programming concepts, including string formatting, file handling, exception handling, and object-oriented programming. It covers methods like format(), read(), write(), and demonstrates polymorphism, constructors, and error handling with try-except blocks. Additionally, it includes examples of database connections and operations using MySQL with Python.

Uploaded by

aniruddh2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

Python Sem2

The document provides various examples and explanations of Python programming concepts, including string formatting, file handling, exception handling, and object-oriented programming. It covers methods like format(), read(), write(), and demonstrates polymorphism, constructors, and error handling with try-except blocks. Additionally, it includes examples of database connections and operations using MySQL with Python.

Uploaded by

aniruddh2573
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

C1tormattinq output Using the format Method corth earmp le.

manua effot thaun


’The format C) method tat es more
other metho d hle Use ?to mart the Sub gtitutiop
Vaables 4 pradle detailed formcrttinq drectives
need to Provì de the for matted
s the
infom dib n,hle can USe the Dumbe
brackets Positigna form a- ing
eeanple
F USin fomat c) method
Print( ? ? ovmat (' ello ', wbrld'))

FUSing for mat() method metering


POSiton the object
porint(o to 1 foTn at ('Welcome JavaTp oi nt'))
Priot1 to o . form ot (hlelcome',JavaTpoi)

Hello alord
elcom e to Javcl point
JavaTpoint to Welcome

Format ng ouput Using the stringq Method.


he carn also output
forma the Output Using the stri ng
Concot enation operutions. The string tYPe
has some method that help format Otputna
-fanie Uy-y: f e hneth du ohich helps to formn ati ng
output
U.
- strustC), Strjust (), 4 str.centre
Code to re dc file in python
redd file oirth cbsol e peth
P Open ("e:demos\.fileslread- derno. 4Kt ", l")
Priot (fp.read C))
f,clOsec)
tepept fileNotfounderor:
Print plece check the poth")
t ine
Second ioe
Third ine
Fowthn ine
une.

Q4 Any tuoo fAle eth od with eample


Read Wite afi\e we need to ppen
for
Dpen tnot te
pUpasepython provi de a bu |t in
e t openinq the tile wrth asolte pot h tuniom apen0mde
TO oPen a f le In q uorHe
$P=open( E:1deros\iles\sanple.tt' )

prit p.reado)
tetcThis DeL)
FclOsing the i\e COntert
afereadg ile
ting neo Coret to he
Macos
pa Open(Write _demotd
Sample. oct ") w')
ole welcome to Phottve.com fP,mte (te)
This)s asomple.to
Line 3
PintlDone iing)
y t ecept taemert orth eample.
-’Try 4 eccept stetements ou ujed to cotch handle
e cepttons in python, stetemerts that can raise ecepons
aUe tept instde the try Cauie the Stetem ent that
handle the ecception ove written inside ecept clauue
eannple
(et acces the aT ay elemet cohose indey
of bound e handle the cOTTespomcing
elceptt on.
Python Proqram to handle simple runti me error

a=,2, 3

Pfint second, elerpert dftet]))


error sinCe there
only
anay

rint(fowth element = lo d'" o/, (a [3]))


eecept
PrintAn e o T OccUmed')

Second e emert 2
An

Python
Pytho rovdes teyeoomd finaly ,ohic h s alwaus
eeeCut eo after the try and except blocks. The
final blocE afte nomal teming
tÌon of hry bloc afte ry blo ck terin Cttes dur
Some eceoti on
0. Polymor phisro in object oented python.
Poly morp higm conains 2 wordpo ly CMoTphi? Po ly me ans
many, 4morph means shupe. By polymorphis m, we onderstan d
4not
tha one teuk can be pertonedLin olitferent cwayi
for ecample -yOu have a
Specue. Buut they spedk di ffeno oty. tkee theCsPeaE"
be hav ior T3 Polymorphic in a sense d oepens m th
animab (ike doqs t cts) hove a con Crete implementa
of the atton 'speak"

Q Pthon on stuton corth example


A Construcer TS a spe chau ype Of method (tUnton)
which S used to nìttai ze the intane members G-f
the closs
CaamPle
class &mployee:
deinitset, name, id).
Self.id
gelf. name = name
Q. Re.moutch ) corth exom ple
Puthons e. matchC) tunctìon finds delives the very irt
clppeaT ance ot c mequta eX pression PatternJn puthon )

NatCh functton 3olels 3earched tor matChing.


tet to be
the beqinning of tne Providleol
Searched. The matchìng object is Produced
mtch S
is fo und in he f i t ine. If a mot Ch 1S found
i n a Subs eque nt line, the python eeqtx tch funiop
qives Outpt ay nul.
ample
impot re
Rne Lean python rough futoritls m avapoint
ine,re. Mbo1)
match- object = re,mee ch (r'. w (. w?) (. w*).
Q Re. Searchl coith eam ple
The e.seachC) unctton oil |ook for the firt O CCUes
o reaqular epTeision Sequence & delive it. It
will Veity aul os of the Supplied string, onite python's
re. mad chC), I4 Hhe Pattern
Pattern 5 mtch ed,the re.S earChC)
Funtton Produces a match obË ect; otheru se , it return
null'
Coxanaple
-mpot
ìmport re
line Learn ython tnrouqh tutomal
en jay Ot point S
5eaTc h-obËect=re.searCh ( ' , ? . t ) ( . ? ) , ine)
.rendaul C)
The ndallO function is often 0sed to loot fo "aur"
appearances Of PateYn. The search CJ module,
the other hand, oill only Provide the eariert
OccTe ce that matches the descripti On. Tn a
Sinqle OPeraion , findall cJ coill toop over oul tthe
docunen ¢4 Prov\de
ov
oV rlLpping meqular matChes
ale a ine of t
have fent
et, cwe
ocCences from the contet So we e
prthon refind dul ) funcH on, It wil Sach
the entte cotent provided to t
Code to mysQI daabeue
import mysql. Conn ectoT
conn ecttonmySql. conn etor. Connect (
0)
host = tocoulhot
User =roO4
)
Passuod

prrint db connectton)
op <usql.conn ectoT . connecon MysoLonnecton obiect at
Ox 000002338A4C6B O0>
Here output shous the Con necthon ected
0 PetchoneC), FetchaliC),fetchmany J methods to redd dasa
Rrorn mysq1taole
fetchong C) -ek Ches +he nexk oo ln the rest of a
Ctch CLII Petrieves
C a auey 4 metuns them as (t st f tupfes
fet chnany) Similar tothe fetchone C) but +
et eves ne nect s ows inthe r e s t
query, instead t a sinqle roo.

SeetJ Nethod n 4ile


o pevattons
TThe seck C) Nethod 4 Cued to Change o m
-the -file's h an dlo Position to the Specified tocati on,
The CUUhior decins Cohere -the data haJ to be
redd COitten in -fhe file

Q2 lonq Oue tions


Q Progam to dem on stcde inheritane in Python
clas s Animal:
det speaklseif ):
Prit("Animal Speating")
#chld class Dog inher its the boue ctaus Apima
cl ass Doq (Anima) :
det bark (Self):
Print doq barking"
d.bark
d.speak )
/p: dog byting
Ari mal Spatinq
to create a Tab le ep ysaL coith python
-SImpot mysai.connetor
db_ connection =mysql.connetor. connect
host ="localhot"
User 2root"
Passuod
detobae z'muCirt_db'"

db cursor db
COnnetion, cUrsoT)
Here (reting datobaye teble as studet'
CUsor. ececte (ceEATE TABLE Studet (id INT,Dame
VAeCHAe (os))
# ek databaye tab le)
dbcosor, ececute (SHUW ABLES')
Por table in db Cus
Prit (tab le)
olp (lstudent,)

Puthon roqram for simple Using the overoadinq ofoperOOT


Cor addbng tu0 objects.
>class eanple
defiot(self, x):

t+ ad dunq ttoo objeets


det aldd (self, u):
getm elf.X +U.x
ObËect1=eample itnput Cerit Plecre epter the
objecd_2- eveample value: ")) 1)
Porint( . ) intinputlPint
objectIt object _2)
Please enter the value:"))))
obiect_3= eample (stlinpt P t(Pleae
Obi ectueanple enterthe value: "))
Prrint ( " obect3tGtunputPint
object_u) Pleaie epter the va lue:")NN
Please enter the vale:23
o/p Ple
please enter the value'. 21

please enter the value Jav


please eteY the volue '. Tpoint
JavaTpoint

C. Proqra m to pertorn tti ple inhs tance in python


class Calcolatton 1.
det sunmatt on (self, a,b)'.
return atb
Ls5 Cal culation 2
ef Nuutiplicati on lself, o ,b)
metun atb'
Clays Deriv ed (calc lction 1. , calculton 2).
def Divide ( self, a, b);
retun a/b'
d Derived()
Prriot d.Sumnati on (1o, 20))
printd. Nutiplicettion (i0,20)
Poriot d. Divide (io, 2o))
30
200
0.5

Q. Proam to demon trate parameric Contrutor


clas s Student
t Con strutor - Parrdmeterized
definit (3et name)
DorintThis is Paro metriz ed contuetom")
Se.name name
def show(selfJ
Prtot (Hetlo", sele.name)
Stadent = udent ( Tohn") olr Ths is para metire Contrte
Studert shouo() Hetlo John
Q Proqars to demonstrete non-paa metrte Conttrue o
ass stuclent:
tt cntructornon perametetee

oefinit (oetf)
rint(This s non parrametized conthructe)
dee show (ieC,nane):
rint ('Helo" nam)
Gtudent tudent C)
Student how (Iohn'")
his is nUn
Hello John

Crect e ctays instancL of employ<


Cmployee
nanm
def diplay (selr):
Print ( io: lod \nName; bs" %lsele,id, sete. name))
tt Cre ceti no a emp instenCe of tmptoy ce clesy
emp Gmployee)
emp. diaplouy C)
Name John

Q Program to depict Rcusin g Exception


Proqram to depict Raning excepti on
raise Name Cror Hi there ") tt PaNe
except Nem eeror
Print An ee Ception')
raise tt to determne whether the eccetton
-eLpuet ot-the cbore cocle uor Slmply ne prtnted ay An e xception "
but a Purrtime aso ocCLIr in the (ayt due
tote weae stetemert
So the outpt on you
the tout ne, commandne wttt toot
Libe,
Traceback (mot mecent caul at) , io
File (borpe/d6 ecl4o s95b9bff sdyo34bbf21 2a9f.py'" tine
<modeel e lase trror
ras e Name Error CHii there) t+
Name Error :Hi there

Co Pytnon proqram to demonstrate finally


python rogram to demonstrcte fi nally
tt No ee ceptton Ccepton ralsed in try bloct
try.
k=Slo + cses divide by zero evception
Print
t t handles Zerocvìsi on eception
except z erosivistopErom
Porint ( cant dìvide by zemo")
finuly'
this bl0 Ck is ececLted
cluays
tE req avdless o-f encceptiop
print (This is dlways ence cut ed')
Car 't dvi de by Zer

7his dllways exeted

Progra) to handle multiple erons wrth on e eeept


8tcteme rt
> program to hand le mnultiple
e ept Statement.
t pyth on 3
det fun Ca);

+throws ZerobivisinEr0Y or q 3
b= /a-)
tE th0ws NameÃr if d>4
print (C value of b= ", b)
try
fun (3)
funls)
brucesC) a e neCess ars here for
tt mwltiple
ecepti ons,
Coccept Zerobivision erro
Print(zerogivisionError occumed d Handled")
ecept Nam eCrro:
pint "NameError occued d Handled')
ZeroDivsiontm 0ccuUh ed d Hanled
IH you Comn ent on the ine fuol(3), the oupt wrll be
NameGror Occored

Q Proqram to handle simple runtime eOr

a - ,2,3]
try
Print (second element = o/o d oo a 1 )
tt Tbows e m r r s n e there are on ly elemets in
array.
print (" Fowrth element = o(o d" o)s(a l3]))
eg Cept.
Prt t (An e r r occumed)
Secon d elem ent =2
An err oCeured

Q Pythom program to demonstete strljwt 0, tr


and sr. centre c) ,muotC),
Str1=I love Tayalpoint
FPrinting the cetem alrgned
frmatting.
t string oith frllchr
print Center aliqned Jtrinq coith fi llehr;")
print (str1.Center (30 '$)

t-Pritinq the eft aign ed


Btng toth »
3)

padding
Piot ( The left aigned shi ng t )
prit Cstri.sjust (40)4'))
tt printing the mght aigned thinq.
)
with
Print he padding
ight aligned shring is")
Print (trl mjust(40,))
Center aigned string orth fillchr:
$$*$$ I love JavaTpoit $44134
The let al'qned strnq is!
Llove TavaTpoirt& 4e&lR444 ¢4
The maht aliqned string Ro!
1 love Tavalpoint
to demon Strat e mehod overTidinq
. Proqrarn
1as$ Aninal
det speat (se1f):
Prit (hpcaeing
Clnss Deq[Arima ):
dle Speak (3e1f):
Print ("Bor kinq)

o.spea
lp Bar Fing
e opercer cver lo adi nq
Proeram to demonstred
C3PrD+ (ta+92)

the too 51nqs


+ NO, coe oit| Concatencete
Priot"TavaTooi n4)

t* 3e 0 checE -th e prroduet of tuo nurrbes

*Hee, ue wil to epeat he sthng.


Pri t zua)
46
JavaTpoit
322

Q Pytnon proaran to chreote file menu havinq Neo

bpen options

from tkinter innport


root TEC)
menu = Menu (root)
root. ConEtq (menu amenu)
Rilemenu = Meou(men) fElemenu)
menu add -cascade clab el Fitemenu
tilem enu add com mand Clabeltuu')
filemenu add Cormmand CIahel pen
filemenu add- epavnt or 0
filemenu-add - command Clab elExlt, commandrot qut)
helpmenu enu(menu)

Pytncn Progam to fetch recorrdy froo employee table of


databdse dsp tay thnem
3iport nysql. ornector
ttestablrshing the Con nect10n
CoDo = mysql ConneetoT connect
(USer oot! Passoovd atPassuasvd, hot i24,0 o.1' datbtue nydb)
Ccaing o ctrrsoY obect 0sing theCursorU msnod

Sqlselecs from empleyee"


t Executing tne quer
Cuto execLte (aqu)
Fetching 1 Tow trorm the table
ret cursor fetchone 0
Posi nt (esutt)
4 c hing t ou from the table
resut =Cusor fetchal|C)
frin (result)
4clotinq the connection
conn cloce )
ole CErishno','shavma 19M 2000. o)
['Ea' Ean dukr 20,,o00o),
CRamyaBan qriya 1.5M So0o,0))

You might also like