3.7.EXERCISES 35
int(4.5)
4
int(3.9)
3
long(3.9)
3L
float(int(3.3))
3.0
int(float(3.3))
3
int(float(3))
3
Asyoucansee,convertingtoanintorlongintsimplydiscardsthefractionalpartofa float;thevalueis
truncated,notrounded. Ifyouwanta roundedresult,youcanadd0.5tothevaluebeforeusingint(),
assumingthevalueis positive.
A moregeneralwayofroundingoff numbersis tousethebuilt-inroundfunctionwhichroundsa float
off tothenearestwholevalue.
round(3.14)
3.0
round(-3.14)
-3.0
round(3.5)
4.0
round(-3.5)
-4.0
int(round(-3.14))
-3
Noticethatroundreturnsa float.Thelastexampleshowshow theresultcanthenbeturnedintoanintvalue,
if necessary, byusingint().
3.7 Exercises
- Show theresultofevaluatingeachexpression.Besurethatthevalueis intheproperformtoindicate
itstype(int,longint,orfloat).If theexpressionis illegal,explainwhy.
(a)4.0 / 10.0 + 3.5 * 2
(b)10 % 4 + 6 / 2
(c)abs(4 - 20 / 3) ** 3
(d)sqrt(4.5 - 5.0)+ 7 * 3
(e)3 * 10 / 3 + 10 % 3
(f)3L ** 3
- TranslateeachofthefollowingmathematicalexpressionsintoanequivalentPythonexpression.You
mayassumethatthemathlibraryhasbeenimported(viaimport math).
(a)
3 4 5
(b) n n 2 ^1
(c) 4 πr^2
(d) r
cosa^2 r
sina^2
(e) xy^22 yx 11