You are on page 1of 10

yLhon programs

rogram (or scrlpL) ls a sequence of


!"#$%&'$( and *'++,$!(
uenluons evaluaLed and commands execuLed by
yLhon lnLerpreLer ln a (-"..
Can be Lyped dlrecLly lnLo a shell, or sLored ln a
le LhaL ls read lnLo Lhe shell and evaluaLed
/'++,$! (or (0,0"+"$01 lnsLrucLs lnLerpreLer
Lo do someLhlng
Cb[ecLs
AL hearL, programs wlll manlpulaLe daLa
ob[ecLs
Lach ob[ecL has a 023" LhaL denes Lhe klnds
of Lhlngs programs can do Lo lL
Cb[ecLs are:
4*,.,5 (l.e. cannoL be subdlvlded), or
6'$7(*,.,5 (l.e. have lnLernal sLrucLure LhaL can be
accessed)
Scalar ob[ecLs
int - used Lo represenL lnLegers, e.g., 5 or 10082
float - used Lo represenL real numbers, e.g., 3.14
or 27.0
bool - used Lo represenL 8oolean values True and
False
1he bullL ln yLhon funcuon type reLurns Lhe Lype of
an ob[ecL
>>> type(3)
<type int>
>>> type(3.0)
<type float>
Lxpresslons
Cb[ecLs and operaLors can be comblned Lo
form "835"((%'$(, each of whlch denoLes an
ob[ecL of some Lype
1he synLax for mosL slmple expresslons ls:
<ob[ecL> <operaLor> <ob[ecL>
CperaLors on ints and floats
i + j - sum - lf boLh are ints, resulL ls int,
lf elLher ls float, resulL ls float
i - j - dlerence
i * j - producL
i/j - dlvlslon - lf boLh are ints, resulL ls int,
represenung quouenL wlLhouL remalnder
i%j - remalnder
i**j - i ralsed Lo Lhe power of j
Some slmple examples
>>> 3 + 3
8
>>> 3.14 * 20
62.8
>>> (2 + 3)*4
20
>>> 2 + 3*4
14



erformlng slmple operauons
arenLheses dene sub-compuLauons - compleLe
Lhese Lo geL values before evaluaung larger
expresslon
(2+3)*4
3*4
20
CperaLor precedence:
ln Lhe absence of parenLheses (wlLhln whlch
expresslons are rsL reduced), operaLors are execuLed
le Lo rlghL, rsL uslng **, Lhen * and /, and Lhen +
and -
Comparlson operaLors on ints and
floats
i > j - reLurns True lf sLrlcLly greaLer
Lhan
i >= j - reLurns True lf greaLer Lhan or
equal
i < j
i <= j
i == j - reLurns True lf equal
i != j - reLurns True lf noL equal
CperaLors on bools
a and b ls True lf boLh are True
a or b ls True lf aL leasL one ls True
not a ls True lf a ls False, lL ls False
lf a ls True
1ype converslons (Lype casung)
We can oen converL an ob[ecL of one Lype Lo
anoLher, by uslng Lhe name of Lhe Lype as a
funcuon
float(3) has Lhe value of 3.0
int(3.9) LruncaLes Lo 3

You might also like