Python Operators: A Comprehensive Guide
Python Operators: A Comprehensive Guide
tII
Py
thon-Oper
ator
s
Let
'sRev
ise:
Programmingisapr ocessofcr
eat
ingasetofi
nst
ruct
ionsthatt
ellacomput erhowto
perf
orm [Link]
ngavari
etyofcomputerlanguagessuch
asJav a,
Python,
andC++.
Ther
earethreetypesofcomputerl
[Link]
elow l
evell
anguage,assembl
y
l
anguageandhighlev
ell
anguage.
Thetranslat
orsareusedt
ot r
ansl
atethehighlevell
anguagesi
ntol
ow l
evell
anguage.
Thesetransl
ator
sarecompil
er,
int
erpr
eterandassembler
.
Py
thonPr
ogr
ammi
ng:
Pyt
honisaverysi
mpl
elanguage,andhasav
eryst
rai
ght
for
war
dsy
ntax.
Thefi
l
eextensi
onofapyt
honf i
l
[Link]
Number
s:
Pythonsuppor
tstwotypesofnumbers-i
nteger
sandfloat
ingpoi
ntnumber
s.(
Ital
so
support
scomplexnumbers,
whi
chwill
notbeexpl
ainedi
nthi
stut
ori
al)
.
Todef
ineani
nteger
,uset
hef
oll
owi
ngsy
ntax:
Exampl
e:
Code:
my i
nt=7
pr
int
(my
int
)
Out
put
:
7
Todef
ineaf
loat
ingpoi
ntnumber
,youmayuseoneoft
hef
oll
owi
ngnot
ati
ons:
Code:
my f
loat=7.0
pri
nt(myfl
oat
)
my f
loat=fl
oat(
7)
pri
nt(myfl
oat
)
Output
:
7.0
7.0
St
ri
ngs:
St
ri
ngsar
edef
inedei
therwi
thasi
ngl
equot
eoradoubl
equot
e.
Code:
mystri
ng='hell
o'
pri
nt(myst
ri
ng)
mystri
ng=" hel
lo"
pri
nt(myst
ri
ng)
mystri
ng=" Don'twor
ryaboutapost
rophes"
pri
nt(myst
ri
ng)
Output
:
hel
lo
hel
lo
Don'tworr
yaboutapostrophes
Thediffer
encebet weent hetwoisthatusi
ngdoubl equot esmakesiteasytoincl
ude
apostr
ophes( whereasthesewouldter
minat
et hest
ringifusingsi
ngl
equotes)
Thereareaddi t
ionalv
ariati
onsondefi
ningst
ringsthatmakei teasi
ertoincl
udethi
ngs
suchascar r
iageretur
ns,backsl
ashesandUnicodecharacters.
EscapeChar
act
er:
Toi
nser
tchar
act
erst
hatar
eil
l
egal
inast
ri
ng,
useanescapechar
act
er.
Anescapechar
act
eri
sabacksl
ash\f
oll
owedbyt
hechar
act
ery
ouwantt
oinser
t.
Anexampleofani
l
legal
char
act
eri
sadoubl
equot
einsi
deast
ri
ngt
hati
ssur
roundedby
doubl
equotes:
t
xt="
Wear
etheso-
cal
l
ed"
Viki
ngs"f
rom t
henor
th.
"
Tofi
xt hi
spr
obl
em,uset
heescapechar
act
er\
",Ot
herescapechar
act
ersusedi
n
Py
thon:
\
' Si
ngl
eQuot
e
\
\ Backsl
ash
\
n NewLi
ne
\
r Car
ri
ageRet
urn
\
t Tab
\
b Backspace
\
f For
m Feed
\
ooo Oct
alv
alue
\
xhh Hexv
alue
Si
mpl
eoper
ator
scanbeexecut
edonnumber
sandst
ri
ngs:
Code:
one=1
two=2
thr
ee=one+t wo
pri
nt(thr
ee)
hel
lo=" hell
o"
world=" worl
d"
hel
lowor l
d=hello+""+wor
ld
pri
nt(hel
loworl
d)
Out
put
:
hel
l
owor
ld
Mi
xi
ngoper
ator
sbet
weennumber
sandst
ri
ngsi
snotsuppor
ted:
Code:
one=1
two=2
hel
lo="hell
o"
pri
nt(
one+t wo+hel
lo)
Output
:
TypeErr
or:
unsuppor
tedoper
andt
ype(
s)f
or+:
'i
nt'
and'
str
'
>>>
#Thi
swi
l
lnotwor
k!
Basi
cOper
ator
s
Thi
ssect
ionexpl
ainshowt
ousebasi
coper
ator
sinPy
thon.
Ar
it
hmet
icOper
ator
s
Justasanyotherpr
ogrammingl
anguages,
theaddi
ti
on,
subt
ract
ion,mul
ti
pli
cat
ion,
and
di
visi
onoper
atorscanbeusedwi
thnumbers.
Exampl
e1:
Code:
number=1+2*3/4.
0
pri
nt(
number
)
Out
put:
2.
5
Exampl
e2:
Code:
number=1+2*3/4.
0
pri
nt(
number
)
Out
put:
2.
5
Anotheroperatoravail
ableisthe modul
o(%)operat
or,whi
ch r
etur
ns t
he i
nteger
remainderoft
hedivi
[Link]
vi
dend%divi
sor=r
emai
nder.
Code:
squared=7* *2
cubed=2* *3
pri
nt(
squared)
pri
nt(
cubed)
Out
put
:
49
8
Usi
ngOper
ator
swi
thSt
ri
ngs
Py
thonsuppor
tsconcat
enat
ingst
ri
ngsusi
ngt
headdi
ti
onoper
ator
:
Code:
lot
sofhel
los="hel
l
o"*10
pri
nt(
lot
sofhel
l
os)
Out
put
:
hel
l
ohel
l
ohel
l
ohel
l
ohel
l
ohel
l
ohel
l
ohel
l
ohel
l
ohel
l
o
Rel
ati
onal
/Compar
isonOper
ator
s
Relat
ionaloperat
orsaresymbolsthatperf
orm operat
ionsondataandretur
nar esul
tas
true orf al
se depending on the comparison condit
[Link],they are cer
tain
funct
ionali
ti
esthatdosomet hi
ngwithyourvari
abl
[Link] oll
owi
ngtabl
egivesyoualist
ofalltherel
ati
onaloper
ator
s:
Rel
ati
onal Meani
ng Exampl
e
Operator
> Gr
eat
ert
han Code:
x=5
y=3
pr
int(x>y)
Output:
#returnsTr
uebecause5i
sgr
eat
ert
han3
< Lesst
han Code:
x=5
y=3
pr
int(
x<y )
Output:
#returnsFal
sebecause5i
snotl
esst
han
3
>= Gr
eat
ert
hanorequal Code:
to x=5
y=3
pr
int(
x>=y)
Output:
#retur
nsTr
uebecausef
ivei
sgr
eat
ert
han
3
<= Lesst
hanorequal
to Code:
x=5
y=3
pri
nt(
x<=y )
Output:
#r et
urnsFalsebecause5i
snei
therl
ess
thanorequalto3
== Equal
s Code:
x=5
y=3
pr
int(x==y)
Output:
#returnsFal
sebecause5i
snotequal
to3
!= Notequal
to Code:
x=5
y=3
pr
int(x!=y)
Output:
#returnsTruebecause5i
snotequal
to3
Rel
ati
onal
oper
ator
scanbeusedt
ocompar
enumber
saswel
lasst
ri
ngs.
Fi
ndt
heOut
putoff
oll
owi
ngcode:
Code:
x=10
y=12
#Output
:x>yisFal
se
pr
int
('
x>yis'
,
x>y)
#Output
:x<yisTrue
pr
int
('
x<yis'
,
x<y)
#Output
:x==yisFal
se
pr
int
('
x==yis'
,
x==y)
#Output
:x!
=yisTrue
pr
int
('
x!=yi
s'
,x!
=y)
#Output
:x>=yisFalse
pr
int
('
x>=yis'
,
x>=y)
#Output
:x<=yisTrue
pr
int
('
x<=yis'
,
x<=y)
Output:
x>yi sFalse
x<yi sTrue
x==yi sFalse
x!=yisTr ue
x>=yi sFalse
x<=yi sTrue
Logi
calOper
ator
s
Logi
caloper
ator
sareusedt ocombi
necondit
ionalst
atementsi.
[Link]
ueorfalse
val
uesofvar
iabl
es(
orexpr
essi
ons)
.Thr
eel
ogicaloper
atorsar
eavai
labl
einPyt
hon:
Oper
ator Descri
pti
o Exampl
e
n
and Retur
ns Code:
True if x=5
both pr
int(x>3andx<10)
stat
ement
s
aretr
ue Output:
#returnsTr
uebecause5i
sgr
eat
ert
han3AND5i
slesst
han
10
or Retur
ns Code:
Trueifone x=5
of the pr
int(
x>3orx<4)
st
atements Output:
i
str
ue #ret
urnsTr
uebecauseoneofthecondit
ionsar
etr
ue(
5is
gr
eatert
han3,
but5isnotlessthan4)
Fi
ndt
heout
putoff
oll
owi
ngcode:
Code:
x=True
y=False
pr
int
('
xandyis'
,xandy)
pr
int
('
xoryi
s',
xory )
pr
int
('
notxi
s'
,notx)
Output
:
xandyisFalse
xoryisTrue
notxisFal
se
Basi
cSt
ri
ngOper
ati
ons
St
ri
ngsar
ebi
tsoft
ext
.Theycanbedef
inedasany
thi
ngbet
weenquot
es:
Code:
astr
ing=" Hell
oworl
d!"
pri
nt("si
nglequot
esare''
"
)
pr
int
(len(ast
ri
ng))
Out
put
:
si
ngl
equot
esar
e''
12
Thatpri
ntsout12,because"
Hel
l
owor
ld!
"is12char
act
ersl
ong,i
ncl
udi
ngpunct
uat
ion
andspaces.
Code:
ast
ring=" Hel
l
owor l
d!"
pri
nt(ast
ri
ng.i
ndex
("o"
))
Out
put
:
4
Thatprintsout4,becauset helocationoft hef i
rstoccurrenceoft helet
ter"
o"is4
charact
ersawayf rom t hefir
[Link]
cehow t hereareactuall
ytwoo'sinthe
phrase-thismet hodonl yrecogni
zesthef ir
st.
Butwhydi dn'titprintout5?I sn'
t"o"t hefif
thcharacterinthestri
ng?Tomaket hi
ngs
mor esi
mpl e,Python( andmostot herpr ogr
ammi nglanguages)star
tthingsat0i
nstead
[Link] heindexof" o"is4.
Code:
ast
ring=" Hel
loworld!
"
pri
nt(ast
ri
[Link]
("
l")
)
Output
:
3
Code:
ast
ring=" Hel
loworl
d!"
pri
nt(ast
ri
ng[3:
7])
Out
put
:
l
ow
Thispri
ntsasli
ceoft
hestr
ing,st
art
ingatindex3,
andendi
ngatindex6.Butwhy6and
not7?Again,mostpr
ogr
ammi nglanguagesdothi
s-itmakesdoingmathinsi
det
hose
bracket
seasier
.
Ifyoujusthaveonenumberinthebrackets,i
twil
lgiveyouthesingl
echaracteratthat
i
[Link]
hefir
stnumberbutkeept hecol
on,itwi
llgiv
ey ouasl i
cefrom
thestartt
othenumberyoulefti
n.I
fy ouleaveoutthesecondnumber ,
itwi
llgiveyoua
sli
cefrom t
hefir
stnumbert
otheend.
Youcanev enputnegati
venumber
sinsi
det
hebracket
[Link]
eaneasywayof
star
tingattheendofthest
ringi
nst
eadoft
hebeginni
[Link]
sway,-
3means"
3rd
charact
erf
rom t
heend"
.
Code:
astr
ing="Ameri
can!"
pr
int
(ast
ri
ng[
3:7:
2])
Out
put
:
r
c
Thi
spr i
ntsthecharact
ersofthestr
ingfr
om 3t o7ski ppi
ngonechar
act
[Link]
sis
ext
endedsli
cesynt
[Link]
for
mi s[
star
t:
stop:
step]
.
Code:
ast
ring=" Hel
loworld!
"
pri
nt(ast
ri
ng[3:
7])
pri
nt(ast
ri
ng[3:
7:1]
)
Out
put
:
l
ow
l
ow
Not
ethatbot
hoft
hem pr
oducesameout
put
Butwi
tht
heabov
ement
ionedt
ypeofsl
i
cesy
ntaxy
oucaneasi
l
yrev
erseast
ri
ngl
i
ke
thi
s
Code:
astri
ng="Hel
lowor
ld!
"
print(
ast
ri
ng[:
:
-1]
)
Output
:
!
dlrowoll
eH
Code:
ast
ring=" Hel
loworl
d!"
pri
nt(ast
ri
[Link]
())
pri
nt(ast
ri
ng.l
ower()
)
Output
:
HELLOWORLD!
hel
lowor l
d!
Code:
astri
ng=" Hel
loworld!"
pri
nt(ast
ri
[Link]
tswith(
"Hel
lo"
))
pri
nt(ast
ri
[Link]("
asdf
asdfasdf
"))
Output
:
True
False
Thi
sisused to deter
minewhethert
hestr
ing st
artswi
thsomethi
ng orendswith
somet
hing,r
espect
ivel
[Link]
ir
stonewil
lpr
intTrue,ast
hestr
ingst
art
swith"Hel
l
o".
Thesecondonewi
l
lpr
intFal
se,
ast
hest
ri
ngcer
tai
nlydoesnotendwi
th"
asdf
asdf
asdf
".
Code:
astr
ing=" Hel
l
owor ld!"
afewwor ds=astr
[Link]
it
(""
)
pri
nt(afewwords)
Output
:
['
Hell
o',
'worl
d!'
]
Thisspli
tst
hestri
ngintoabunchofstri
ngsgroupedtogetherinali
[Link]
s
examplespl
i
tsataspace,t
hef
ir
sti
tem i
nthel
istwi
llbe"
Hello",andt
hesecondwil
lbe
"worl
d!"
.
Example:
Progr
am tofindsi
mpleint
erestforagivenpri
nci
pal
amount
,ti
meandrateofi
nter
est
.
Si
mpleinter
estfor
mulaisgivenby :
Si
mpleInter
est=(PxTxR) /100
Where,Pisthepri
nci
pleamount, Tist
het i
meand,Rist
her
ateofi
nter
est
Code:
p=3000
r=7
t=1
pr
int
('
Thepri
ncipalis'
,p)
pr
int
('
Theti
meper iodis',t
)
pr
int
('
Therat
eofi nter
estis',
r)
si
=(p*t*r )
/100
pr
int
('
TheSimpleInterestis'
,si
)
Out
put
:
Thepri
nci
palis3000
Theti
meperiodis1
Therat
eofinter
esti
s7
TheSimpl
eInter
esti
s210
Taki
ngi
nputf
rom user
:
i
nput():Thi sfunct
ionfir
sttakestheinputfr
om theuserandthenevaluat
est he
expressi
on,whichmeansPy thonautomati
cal
lyi
dent
ifi
eswhethert
heuserentereda
str
ingoranumberorl i
st.I
ftheinputpr
ovi
dedisnotcorr
ectt
heneit
hersy
ntaxerroror
excepti
onisrai
sedbypython.
Code:
#Py t
honpr ogr
am showingauseofi
nput
()
val=input(
"Ent
eryourvalue:
")
pri
nt(
v al
)
Out
put
:
Ent
ery
ourv
alue:
123
Example:
Progr
am takesatemperat
ureindegr
eeCel
siusandconv
ert
siti
ntodegr
eeFahr
enhei
t.
Theyarerel
atedbyt
heformula:
cel
sius*1.
8=f
ahr
enhei
t-32
Code:
#Py
thonPr
ogr
am t
oconv
ertt
emper
atur
eincel
siust
ofahr
enhei
t
celsius=i nput("
Entert
emperatureinCel
sius:
")
#gi vei nputas37. 5
#cal cul at
ef ahrenhei
t
fahrenhei t=( celsi
us*1.8)+32
pri
nt( celsius’degreeCelsi
usisequalto’
)
pri
nt( fahrenheit’degr
eeFahrenheit
’)
Out
put
:
Entert
emperatureinCel
sius:
(gi
vevalueas37.5)
37.
5degr eeCelsi
usisequalt
o99.
5degr
eeFahr
enhei
t
Quest
ionandAnswer:
[Link]?Whatarethebenefi
tsofusi
ngPy
thon?
[Link]
cat
ionsofPython?
[Link]
tet
hedi
ffer
encebetween‘
+’i
nari
thmet
icoper
atorandst
ri
ng.
[Link] i
neinpy
thon?
[Link]
sastr
inginPyt
hon?
[Link]
nginpy t
hon?
[Link]
stheoutputofpri
ntstri
f,st
r='HelloWor l
d!'
?
[Link]
lyouconvertastri
ngtoalluppercase?
[Link]
lyougetthelengthofthestr
ing?
10.
Howdoyoutakeinputfrom t
heuserinPy thon?
Codei
tup:
[Link]
teapythoncodet opri
ntyournameandaddr ess.
[Link]
teapythoncodet oaddthreenumbers,taki
ngt hev aluefrom t
heuser.
[Link]
teapythonpr ogr
am tofi
ndt heareaofasquar e,takingthevalueofthesi
de
ofasquar
ef r
om theuser.
[Link]
tetheprogram i
npythontoswapt wonumber s.
[Link]
teaprogram toaddyourfi
rstandthelastnameandpr intthef
ullname.
[Link]
teaprogram inpyt
hontofindtheareaofar ectangle.
[Link]
tetheprogram i
npythontofindt
hear eaofaci rcle.
[Link]
teaprogram inpyt
hontofindthelengthofast ringgiven.
[Link]
teaprogram inpyt
hontofindwhetherthegiv ennumberi soddoreven.
10.
Wri
teaprogram inpyt
hontofindtheareaofat ri
angl e.
Pr
oject
:
Makeasi
mpl
ecal
cul
atorpr
ogr
am i
npy
thon.