7.2.TWO-WAY DECISIONS 105
if name == ’main’:
main()
Thisguaranteesthatmainwillautomaticallyrunwhentheprogramis invokeddirectly, butit willnotrun
if themoduleis imported.Youwillseea lineofcodesimilartothisat thebottomofvirtuallyeveryPython
program.
7.2 Two-WayDecisions.
Nowthatwehave a waytoselectivelyexecutecertainstatementsina programusingdecisions,it’s timeto
gobackandspruceupthequadraticequationsolverfromChapter3.Hereis theprogramasweleftit:
quadratic.py
A program thatcomputes the real roots of a quadratic equation.
Illustrates use of the mathlibrary.
Note: this programcrashes if the equation has no real roots.
import math # Makesthe math library available.
def main():
print "This programfinds the real solutions to a quadratic"
print
a, b, c = input("Please enter the coefficients (a, b, c): ")
discRoot = math.sqrt(b* b - 4 * a * c)
root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)
print
print "The solutionsare:", root1, root2
main()
Asnotedinthecomments,thisprogramcrasheswhenit is givencoefficientsofa quadraticequationthat
hasnorealroots.Theproblemwiththiscodeis thatwhenb^2 4 acis lessthan0,theprogramattemptsto
take thesquarerootofa negative number. Sincenegative numbersdonothave realroots,themathlibrary
reportsanerror. Here’s anexample.
import quadratic
This program findsthe real solutions to a quadratic
Please enter the coefficients(a, b, c): 1,2,3
Traceback (innermostlast):
File "
File "quadratic.py",line 21, in?
main()
File "quadratic.py",line 14, in main
discRoot = math.sqrt(b b - 4 a * c)
OverflowError: mathrange error
We canusea decisiontocheckforthissituationandmake surethattheprogramcan’t crash.Here’s a
firstattempt:
quadratic2.py
import math