26 CHAPTER3. COMPUTINGWITHNUMBERS
aredecimalfractions.Insidethecomputer, wholenumbersandnumbersthathave fractionalcomponentsare
representeddifferently. Technically, wesaythatthesearetwo differentdatatypes.
Thedatatypeofanobjectdetermineswhatvaluesit canhave andwhatoperationscanbeperformedonit.
Wholenumbersarerepresentedusingtheintegerdatatype(intforshort).Valuesoftypeintcanbepositive
ornegative wholenumbers.Numbersthatcanhave fractionalpartsarerepresentedasfloatingpoint(orfloat)
values.Sohow dowetellwhethera numberis anintora float?Anumericliteralthatdoesnotcontaina
decimalpointproducesanintvalue,whilea literalthathasa decimalpointis representedbya float(evenif
thefractionalpartis 0).
Pythonprovidesa specialfunctioncalledtypethattellsusthedatatypeofany value. Hereisan
interactionwiththePythoninterpretershowingthedifferencebetweenintandfloatliterals.
type(3)
<type ’int’>
type(3.14)
<type ’float’>
type(3.0)
<type ’float’>
myInt = -32
type(myInt)
<type ’int’>
myFloat = 32.0
type(myFloat)
<type ’float’>
Youmaybewonderingwhytherearetwo differentdatatypesfornumbers.Onereasonhastodowith
programstyle.Valuesthatrepresentcountscan’t befractional;wecan’t have 3^12 quarters,forexample.Using
anintvaluetellsthereaderofa programthatthevaluecan’tbea fraction.Anotherreasonhastodowiththe
efficiency ofvariousoperations.Theunderlyingalgorithmsthatperformcomputerarithmeticaresimpler,
andthereforefaster, forintsthanthemoregeneralalgorithmsrequiredforfloatvalues.
Youshouldbewarnedthatthefloattypeonlystoresapproximations.Thereis a limittotheprecision,or
accuracy, ofthestoredvalues.Sincefloatvaluesarenotexact,whileintsalwaysare,yourgeneralruleof
thumbshouldbe:if youdon’t absolutelyneedfractionalvalues,useanint.
operator operation
addition
subtraction
multiplication
division
exponentiation
% remainder
abs() absolutevalue
Table3.1:Pythonbuilt-innumericoperations.
Avalue’s datatypedetermineswhatoperationscanbeusedonit. Aswehave seen,Pythonsupports
theusualmathematicaloperationsonnumbers.Table3.1summarizestheseoperations.Actually, thistable
issomewhatmisleadingsincethetwo numericdatatypeshave theirownoperations. Whenadditionis
performedonfloats,thecomputerperformsa floatingpointaddition. Whereas,withints,thecomputer
performsanintegeraddition.
ConsiderthefollowinginteractionwithPython:
3.0 + 4.0
7.0
3 + 4
7