Python Programming: An Introduction to Computer Science

(Nora) #1
20 CHAPTER2. WRITINGSIMPLEPROGRAMS

Becausetheassignmentis simultaneous,it avoidswipingoutoneoftheoriginalvalues.
Simultaneousassignmentcanalsobeusedtogetmultiplevaluesfromtheuserina singleinput. Con-
siderthisprogramforaveragingexamscores:


avg2.py


A simple programto average two exam scores


Illustrates use of multipleinput


def main():
print "This programcomputes the average of two exam scores."


score1, score2= input("Enter two scores separated by a comma:")
average = (score1+ score2) / 2.0

print "The averageof the scores is:", average

main()


Theprogrampromptsfortwo scoresseparatedbya comma.Supposetheusertypes86, 92. Theeffectof
theinputstatementis thenthesameasif wehaddonethisassignment:


score1, score2 = 86, 92


We have gottena valueforeachofthevariablesinonefellswoop.Thisexampleusedjusttwo values,butit
couldbegeneralizedtoany numberofinputs.
Ofcourse,wecouldhave justgottentheinputfromtheuserusingseparateinputstatements.


score1 = input("Enterthe first score: ")
score2 = input("Enterthe second score: ")


Insomewaysthismaybebetter, astheseparatepromptsaremoreinformative fortheuser. Inthisexample
thedecisionastowhichapproachtotake is largelya matteroftaste.Sometimesgettingmultiplevaluesina
singleinputprovidesa moreintuitive userinterface,soit is nicetechniquetohave inyourtoolkit.


2.6 DefiniteLoops


Youalreadyknow thatprogrammersuseloopsto executea sequenceofstatementsseveraltimesin succession.
Thesimplestkindofloopis calledadefiniteloop. Thisis a loopthatwillexecutea definitenumberoftimes.
Thatis,atthepointintheprogramwhentheloopbegins,Pythonknowshowmany timestogoaround
(oriterate) thebodyoftheloop.Forexample,theChaosprogramfromChapter1 useda loopthatalways
executedexactlytentimes.


for i in range(10):
x = 3.9 * x * (1 - x)
print x

Thisparticularlooppatternis calledacountedloop, andit is builtusinga Pythonforstatement.Before
consideringthisexampleindetail,let’s take a lookat whatforloopsareallabout.
A Pythonforloophasthisgeneralform.


for <var> in <sequence>:
<body>

Thebodyoftheloopcanbeany sequenceofPythonstatements.Thestartandendofthebodyis indicated
byitsindentationundertheloopheading(thefor in :part).
Themeaningoftheforstatementis a bitawkwardtoexplaininwords,butis veryeasytounderstand,
onceyougetthehangofit. Thevariableafterthekeywordforiscalledtheloopindex. It takeson

Free download pdf