34 CHAPTER3. COMPUTINGWITHNUMBERS
Ifyouhave anolderversionofPython(priortoversion2.0),theseanswerswillbeprintedwithan“L”
appended.Thisis Python’s wayofsayingthatthenumberis a longint.Innewerversions,thisartifactis
automaticallyremovedbytheprintstatement.Inthenextchapter, youwilllearnhow youcouldtake care
ofgettingthe“L” outyourself.
Now wehave a factorialprogramthatcancomputeinterestinglylargeresults.Longintsareprettycool;
youmightbetemptedtousethemallthetime.Thedown-sideofusinglongintsis thattheserepresentations
arelessefficientthantheplainintdatatype.Theoperationsneededtodoarithmeticonintsis builtintothe
CPUofthecomputer. Whendoingoperationsonlongints,Pythonhastoemploy algorithmsthatsimulate
longarithmeticusingthecomputer’s built-infixed-lengthoperations.Asa result,longintarithmeticismuch
slowerthanintarithmetic.Unlessyouneedverylargevalues,intsarepreferred.
3.6 TypeConversions.
Sometimesvaluesofonedatatypeneedtobeconvertedintoanother. Youhave seenthatcombininganint
withanintproducesanint,andcombininga floatwitha floatcreatesanotherfloat. Butwhathappensif
wewriteanexpressionthatmixesanintwitha float?Forexample,whatshouldthevalueofxbeafterthis
assignmentstatement?
x = 5.0 / 2
If thisis floatingpointdivision,thentheresultshouldbethefloatvalue 2 5.If integerdivisionis performed,
theresultis 2.Beforereadingaheadfortheanswer, take a minutetoconsiderhow youthinkPythonshould
handlethissituation.
Inordertomake senseoftheexpression5.0 / 2, Pythonmusteitherchange5.0to 5 andperform
integerdivisionorconvert 2 to2.0andperformfloatingpointdivision.Ingeneral,convertinga floattoan
intis a dangerousstep,becausesomeinformation(thefractionalpart)willbelost.Ontheotherhand,anint
canbesafelyturnedintoa floatjustbyaddinga fractionalpartof 0.So,inmixed-typedexpressions, Python
willautomaticallyconvertintstofloatsandperformfloatingpointoperationstoproducea floatresult.
Sometimeswemaywanttoperforma typeconversionourselves.Thisis calledanexplicittypeconver-
sion.Forexample,supposewearewritinga programthatfindstheaverageofsomenumbers.Ourprogram
wouldfirstsumupthenumbersandthendividebyn, thecountofhow many numbersthereare.Thelineof
codetocomputetheaveragemightlooklike this.
average = sum / n
Unfortunately, thislinemaynotalwaysproducetheresultweintend.
Considera specificexample.Thenumberstobeaveragedaretheints4, 5, 6, 7. Thesumvariable
willhold 22 , alsoanint,anddividingby 4 givestheanswer 5 , not5.5. Remember, anintdividedbyanint
alwaysproducesanint.
To solve thisproblem,weneedtotellPythontoconvertoneoftheoperandstoa floatingpointvalue.
average = float(sum)/ n
Thefloat()functionconvertsanintintoa float. We onlyneedtoconvertthenumerator, becausethis
producesa mixed-typeexpression,andPythonwillautomaticallyconvertthedenominator.
Noticethatputtingthefloat()aroundtheentireexpressionwouldnotwork.
average = float(sum/n)
Inthisform,sumandncouldbothbeintscausingPythontoperformanintegerdivisionandthenconvert
theresultingquotienttoa float.Ofcourse,thisfloatwouldalwaysendin 0,sinceit is beingconvertedfrom
anint.Thatis notwhatwewant.
Pythonalsoprovidesint()andlong()functionsthatcanbeusedtoconvertnumbersintointsand
longs,respectively. Herearea few examples.