Python Programming: An Introduction to Computer Science

(Nora) #1
7.4.EXCEPTIONHANDLING 109

discrim < 0?

Print "no roots"

yes no

yes no

Do Double Root Do Unique Roots

discrim == 0?

Figure7.4:Three-waydecisionforquadraticsolverusingnestedif-else.

Thisformis usedtosetoff any numberofmutuallyexclusive codeblocks.Pythonwillevaluateeachcondi-
tioninturnlookingforthefirstonethatis true.If a trueconditionis found,thestatementsindentedunder
thatconditionareexecuted,andcontrolpassestothenextstatementaftertheentireif-elif-else. If
noneoftheconditionsaretrue,thestatementsundertheelseareperformed.Theelseclauseis optional;
if omitted,it is possiblethatnoindentedstatementblockwillbeexecuted.
Usinganif-elif-elseto show thethree-waydecisionin ourquadraticsolver yieldsa nicelyfinished
program.


quadratic4.py


import math


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


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

discrim = b * b - 4 * a * c
if discrim < 0:
print "\nTheequation has no real roots!"
elif discrim == 0:
root = -b / (2 * a)
print "\nThereis a double root at", root
else:
discRoot = math.sqrt(b* b - 4 * a * c)
root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)
print "\nThesolutions are:", root1, root2

7.4 ExceptionHandling.


Ourquadraticprogramusesdecisionstructurestoavoidtakingthesquarerootofa negative numberand
generatinga run-timeerror. Thisis a commonpatterninmany programs:usingdecisionstoprotectagainst

Free download pdf