Python Programming: An Introduction to Computer Science

(Nora) #1
7.3.MULTI-WAY DECISIONS 107

no yes

Calculate roots Print "no roots"

discrim < 0?

Figure7.3:Quadraticsolverasa two-waydecision.

quadratic3.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!"
else:
discRoot = math.sqrt(b* b - 4 * a * c)
root1 = (-b + discRoot)/ (2 * a)
root2 = (-b - discRoot)/ (2 * a)
print
print "\nThesolutions are:", root1, root2

Thisprogramfitsthebillnicely. Hereis a samplesessionthatrunsthenew programtwice.





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





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


The equation has no realroots!





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





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


The solutions are:-0.292893218813 -1.70710678119


7.3 Multi-WayDecisions


Thenewestversionofthequadraticsolveris certainlya bigimprovement,butit stillhassomequirks.Here
is anotherexamplerun.

Free download pdf