108 CHAPTER7. CONTROLSTRUCTURES,PART 1
quadratic3.main()
This program findsthe real solutions to a quadratic
Please enter the coefficients(a, b, c): 1, 2, 1
The solutions are:-1.0 -1.0
Thisis technicallycorrect;thegivencoefficientsproduceanequationthathasa doublerootat -1.However,
theoutputmightbeconfusingtosomeusers. It lookslike theprogramhasmistakenlyprintedthesame
numbertwice.Perhapstheprogramshouldbea bitmoreinformative toavoidconfusion.
Thedouble-rootsituationoccurswhendiscrimis exactly0. Inthiscase,discRootis also0,and
bothrootshave thevalue 2 ab. If wewanttocatchthisspecialcase,it lookslike ourprogramactuallyneedsa
three-waydecision.Here’s a quicksketchofthedesign.
...
Check the value of discrim
when < 0: handlethe case of no roots
when = 0: handlethe case of a double root
when > 0: handlethe case of two distinct roots.
Onewaytocodethisalgorithmis tousetwoif-elsestatements.Thebodyofaniforelseclause
cancontainany legalPythonstatements,includingotheriforif-elsestatements.Puttingonecompound
statementinsideofanotheriscallednesting. Here’s a fragmentofcodethatusesnestingtoachieve a
three-waydecision:
if discrim < 0:
print "Equationhas no real roots"
else:
if discrim == 0:
root = -b / (2 * a)
print "Thereis a double root at", root
else:
Do stuff fortwo roots
Ifyoutracethroughthiscodecarefully, youwillseethatthereareexactlythreepossiblepaths. The
sequencingis determinedbythevalueofdiscrim. A flowchartofthissolutionis showninFigure7.4.You
canseethatthetop-levelstructureis justanif-else. (Treatthedashedboxasonebigstatement.)The
dashedboxcontainsthesecondif-elsenestedcomfortablyinsidetheelsepartofthetop-level decision.
Onceagain,wehave a workingsolution,but theimplementationdoesn’t feelquiteright.We have finessed
a three-waydecisionbyusingtwo two-waydecisions.Theresultingcodedoesnotreflectthetruethree-fold
decisionoftheoriginalproblem.Imagineif weneededto make a five-waydecisionusingthistechnique.The
if-elsestructureswouldnestfourlevelsdeep,andthePythoncodewouldmarchoff theright-handedge
ofthepage.
Thereis anotherwaytowritemulti-waydecisionsinPythonthatpreservesthesemanticsofthenested
structuresbutgivesit a moreappealinglook.Theideais tocombineanelsefollowedimmediatelybyan
ifintoa singleclausecalledanelif.
if
elif
elif
...
else: