124 CHAPTER8. CONTROLSTRUCTURES,PART 2
Thissentinelloopsolutionisquitegood,butthereisstilla limitation. Theprogramcan’t beusedto
averagea setofnumberscontainingnegative aswellaspositive values.Let’s seeif wecan’t generalizethe
programa bit.Whatweneedis a sentinelvaluethatis distinctfromany possiblevalidnumber, positive or
negative.Ofcourse,thisis impossibleaslongaswerestrictourselvestoworkingwithnumbers.Nomatter
whatnumberorrangeofnumberswepickasa sentinel,it is alwayspossiblethatsomedatasetmaycontain
sucha number.
Inordertohave a trulyuniquesentinel,weneedtobroadenthepossibleinputs.Supposethatwegetthe
inputfromtheuserasa string.We canhave a distinctive, non-numericstringthatindicatestheendofthe
input;allotherswouldbeconvertedintonumbersandtreatedasdata.Onesimplesolutionis tohave the
sentinelvaluebeanemptystring. Remember, anemptystringis representedinPythonas""(quoteswith
nospacebetween).If theusertypesa blanklineinresponsetoarawinput(justhits Enter ), Python
returnsanemptystring.We canusethisasa simplewaytoterminateinput.Thedesignlookslike this:
Initialize sum to 0.0
Initialize count to 0
Input data item as a string,xStr
while xStr is not empty
Convert xStr to a number,x
Add x to sum
Add 1 to count
Input next dataitem as a string, xStr
Output sum / count
Comparingthistothepreviousalgorithm,youcanseethatconvertingthestringtoa numberhasbeenadded
totheprocessingsectionofthesentinelloop.
TranslatingintoPythonyieldsthisprogram:
average4.py
def main():
sum = 0.0
count = 0
xStr = raw_input("Entera number (
while xStr != "":
x = eval(xStr)
sum = sum + x
count = count+ 1
xStr = raw_input("Entera number (
print "\nThe averageof the numbers is", sum / count
Thiscodemakesuseofeval(fromChapter4)toconverttheinputstringintoa number.
Hereis anexamplerun,showingthatit is now possibletoaveragearbitrarysetsofnumbers:
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
Enter a number (
The average of the numbersis 3.38333333333
We finallyhave anexcellentsolutiontoouroriginalproblem.Youshouldstudythissolutionsothatyoucan
incorporatethesetechniquesintoyourownprograms.