9.2.RANDOMNUMBERS 139
thefunctiontoproducea newnumber. Witha carefullychosenfunction,theresultingsequenceofvalues
looksessentiallyrandom.Ofcourse,if youstarttheprocessover againwiththesameseedvalue,youendup
withexactlythesamesequenceofnumbers.Itβs alldeterminedbythegeneratingfunctionandthevalueof
theseed.
Pythonprovidesa librarymodulethatcontainsa numberofusefulfunctionsforgeneratingpseudorandom
numbers.Thefunctionsinthismodulederive aninitialseedvaluefromthedateandtimewhenthemodule
is loaded,soyougeta differentseedvalueeachtimetheprogramis run.Thismeansthatyouwillalsogeta
uniquesequenceofpseudorandomvalues.Thetwo functionsofgreatestinteresttousarerandrangeand
random.
Therandrangefunctionisusedtoselecta pseudorandomintfroma givenrange. It canbeused
withone,two orthreeparameterstospecifya rangeexactlyaswiththerangefunction. Forexample,
randrange(1,6)returnssomenumberfromtherange[1,2,3,4,5], andrandrange(5,105,5)
returnsa multipleof5 between5 and100,inclusive.(Remember, rangesgoupto,butnotincluding,the
stoppingvalue.)
Eachcalltorandrangegeneratesa newpseudorandomint.Hereis aninteractive sessionthatshows
randrangeinaction.
from random importrandrange
randrange(1,6)
3
randrange(1,6)
3
randrange(1,6)
5
randrange(1,6)
5
randrange(1,6)
5
randrange(1,6)
1
randrange(1,6)
5
randrange(1,6)
4
randrange(1,6)
2
Noticeit tooktencallstorandrangetoeventuallygenerateeverynumberintherange1β5.Thevalue 5
cameupalmosthalfofthetime.Thisshowstheprobabilisticnatureofrandomnumbers.Overthelonghaul,
thisfunctionproducesa uniformdistribution,whichmeansthatallvalueswillappearan(approximately)
equalnumberoftimes.
Therandomfunctioncanbeusedtogeneratepseudorandomfloatingpointvalues.It requiresnoparam-
etersandreturnsvaluesuniformlydistributedbetween0 and1 (including0, butexcluding1).Herearesome
interactive examples.
from random importrandom
random()
0.545146406725
random()
0.221621655814
random()
0.928877335157
random()
0.258660828538
random()
0.859346793436