Python Programming: An Introduction to Computer Science

(Nora) #1
106 CHAPTER7. CONTROLSTRUCTURES,PART 1

def main():
print "This programfinds the real solutions to a quadratic\n"


a, b, c = input("Please enter the coefficients (a, b, c): ")

dicrim = b * b - 4 * a * c
if discrim >= 0:
discRoot = math.sqrt(discrim)
root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)
print "\nThesolutions are:", root1, root2

Thisversionfirstcomputesthevalueofthediscriminant(b^2  4 ac) andthencheckstomake sureit is not
negative. Onlythendoestheprogramproceedtotake thesquarerootandcalculatethesolutions. This
programwillneverattempttocallmath.sqrtwhendiscrimis negative.
Incidently, youmightalsonoticethatI have replacedthebareprintstatementsfromtheoriginalversion
oftheprogramwithembeddednewlinestoputwhitespaceintheoutput;youhadn’t yetlearnedabout


nthe
firsttimeweencounteredthisprogram.
Unfortunately, thisupdatedversionis notreallya completesolution.Studytheprogramfora moment.
Whathappenswhentheequationhasnorealroots?Accordingtothesemanticsfora simpleif, whenb*b



  • 4acis lessthanzero,theprogramwillsimplyskipthecalculationsandgotothenext statement.Since
    thereis nonextstatement,theprogramjustquits.Here’s whathappensinaninteractive session.





quadratic2.main()
This program findsthe real solutions to a quadratic





Please enter the coefficients(a, b, c): 1,2,3








Thisis almostworsethanthepreviousversion,becauseit doesnotgive theuserany indicationofwhat
wentwrong;it justleavesthemhanging.Abetterprogramwouldprinta messagetellingtheuserthattheir
particularequationhasnorealsolutions.We couldaccomplishthisbyaddinganothersimpledecisionat the
endoftheprogram.


if discrim < 0:
print "The equationhas no real roots!"


Thiswillcertainlysolve ourproblem,butthissolutionjustdoesn’t feelright.We have programmeda
sequenceoftwo decisions,butthetwo outcomesaremutuallyexclusive.Ifdiscrim >= 0is truethen
discrim < 0mustbefalseandviceversa.We have two conditionsin theprogram,but thereis reallyonly
onedecisiontomake.BasedonthevalueofdiscrimTheprogramshouldeitherprintthatthereareno
realrootsorit shouldcalculateanddisplaytheroots.Thisis anexampleofa two-waydecision.Figure7.3
illustratesthesituation.
InPython,a two-waydecisioncanbeimplementedbyattachinganelseclauseontoanif. Theresult
is calledanif-elsestatement.


if :



else:

WhenthePythoninterpreterencountersthisstructure,it willfirstevaluatethecondition.If theconditionis
true,thestatementsundertheifareexecuted.If theconditionis false,thestatementsundertheelseare
executed.Ineithercase,controlthenpassestothestatementfollowingtheif-else.
Usinga two-waydecisioninthequadraticsolveryieldsa moreelegantsolution.

Free download pdf