30 CHAPTER3. COMPUTINGWITHNUMBERS
initializationensuresthatfacthasa valueontheveryfirstiteration.Wheneveryouusetheaccumulator
pattern,make sureyouincludetheproperinitialization. Forgettingit isa commonmistake ofbeginning
programmers.
Ofcourse,therearemany otherwayswecouldhave writtenthisloop.Asyouknowfrommathclass,
multiplicationis commutative andassociative, soit reallydoesn’t matterwhatorderwedothemultiplications
in.We couldjustaseasilygotheotherdirection.Youmightalsonoticethatincluding 1 inthelistoffactors
is unnecessary, sincemultiplicationby1 doesnotchangetheresult.Hereis anotherversionthatcomputes
thesameresult.
fact = 1
for factor in [2,3,4,5,6]:
fact = fact * factor
Unfortunately, neitheroftheseloopssolvestheoriginalproblem.We have hand-codedthelistoffactors
tocomputethefactorialofsix.Whatwereallywantis a programthatcancomputethefactorialofany given
inputn. We needsomewaytogenerateanappropriatelistfromthevalueofn.
Luckily, thisis quiteeasytodousingthePythonrangefunction.Recallthatrange(n)producesa list
ofnumbersstartingwith0 andcontinuingupto,but notincluding,n. Thereareothervariationsofrangethat
canbeusedtoproducedifferentsequences.Withtwo parameters,range(start,n)producesa sequence
thatstartswiththevaluestartandcontinuesupto,butnotincluding,n. A thirdversionrange(start,
n, step)is like thetwo parameterversion,exceptthatit usesstepastheincrementbetweennumbers.
Herearesomeexamples.
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(5,10)
[5, 6, 7, 8, 9]
range(5, 10, 3)
[5, 8]
Givenourinputvaluenwehave a coupleofdifferentrangecommandsthatproduceanappropriatelist
offactorsforcomputingthefactorialofn. To generatethemfromsmallesttolargest(ala oursecondloop),
wecoulduserange(2,n+1). Noticehow I usedn+1asthesecondparameter, sincetherangewillgoup
to,butnotincludingthisvalue.We needthe+1tomake surethatnitselfis includedasthelastfactor.
Anotherpossibilityis togeneratethefactorsintheotherdirection(alaourfirstloop)usingthethree-
parameterversionofrangeanda negative steptocausethecountingtogobackwards:range(n,1,-1).
Thisoneproducesa liststartingwithnandcountingdown(step-1)to,butnotincluding 1.
Herethenis onepossibleversionofthefactorialprogram.
factorial.py
Program to computethe factorial of a number
Illustrates for loopwith an accumulator
def main():
n = input("Pleaseenter a whole number: ")
fact = 1
for factor in range(n,1,-1):
fact = fact* factor
print "The factorialof", n, "is", fact
main()
Ofcoursetherearenumerousotherwaysthisprogramcouldhave beenwritten.I have alreadymentioned
changingtheorderoffactors.Anotherpossibilityis toinitializefacttonandthenusefactorsstartingat
n 1 (aslongasn 0).Youmighttryoutsomeofthesevariationsandseewhichyoulike best.