Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python 3 NOTE: This is an example of a function that DOES something (it puts the

ID: 3778524 • Letter: P

Question

Python 3 NOTE: This is an example of a function that DOES something (it puts the value(s) of the root(s) in a list), and it RETURNS something (the number of roots)

Sample exercise 4.1

When the discriminant == 0 r1 and r2 are the same
so we only report one. You've unnecessarily done the
calculation twice.
"""
#Algebra: Solve Quadratic Equations

a, b ,c = eval(input("Enter the values for a, b, c:"))

disc= (b*b) - (4 * a * c)

if disc>0:
r1= (-b + (b*b - 4 * a * c)**0.5) / (2*a)
r2= (-b - (b*b - 4 * a * c)**0.5) / (2*a)
print ("Display two roots",r1, r2)
elif disc==0:
r1= (-b + (b*b - 4 * a * c)**0.5) / (2*a)
r2= (-b - (b*b - 4 * a * c)**0.5) / (2*a)
print ("Display one root", r1)
else:
print ("The equation has no real roots")

o.23 Algebra: solve quadratic equations) write a function for solving a quadratic equation using the following header: def solve Quadratic(eqn roots) The coefficients of a quadratic equation ar2 br 0 are passed to the list eqn and the noncomplex roots are stored in roots. The function returns the number of roots. See Programming Exercise 4.1 on how to solve a quadratic equation. Write a program that prompts the user to enter values for a, b, and c and displays the number of roots and all noncomplex roots.

Explanation / Answer

def solveQuadratic(eqn, roots):
   a = float(eqn[0])
   b = float(eqn[1])
   c = float(eqn[2])
   disc = (b ** 2)- (4 * a * c)
  
   if disc > 0:
       roots.append(-b + (disc ** 0.5) / (2 * a))
       roots.append(-b -(disc ** 0.5) / (2 * a))
       return 2
   elif disc == 0:
       roots.append(-b / (2 * a))
       return 1
   else:
       return 0
      

def main():
   #taking equation as ax^2 + bx + c
   a,b,c = eval(input("Please give a, b, c of the quadratic equation: "))
   eqn = []
   eqn.append(a)
   eqn.append(b)
   eqn.append(c)
   roots = []
   no_of_roots = solveQuadratic(eqn, roots)
   print("Number of roots = "+ str(no_of_roots))
   for i in range (0,no_of_roots):
       print("root" + str(i+1) + " : " + str(roots[i]))
      
      
main()