Ramy George Ramy George - 15 days ago 5
Python Question

PySchools topic 3 Q8

The question is


For a quadratic equation in the form of ax2 + bx + c, the
discriminant, D is b2-4ac.
Write a function that return the following output depending on the discriminant.


  • D > 0: 2 real roots.

  • D = 0: 1 real root.

  • D < 0: 2 complex roots.



Examples

>>> quadratic(1, 2, 3)
'This equation has 2 complex roots.'
>>> quadratic(1, 3, 2)
'This equation has 2 real roots.'
>>> quadratic(1, 4, 4)
'This equation has 1 real root.'



Python gave a "Private test cases failed" error. Where is my error?

def quadrtic(a,b,c):
d=b**2-4*a*c
if d<0:
return "This equation has 2 complex roots."
elif d==1:
return "This equation has 2 real roots."
elif d==0 or d==1:
return "This equation has 1 real root."

Answer

Your if blocks should be

def quadrtic(a,b,c):
   d = b**2 - 4*a*c
   if d < 0:
       return "This equation has 2 complex roots."
   elif d > 0:
       return "This equation has 2 real roots."
   else:  # d == 0
       return "This equation has 1 real root."

The discriminant is very unlikely to be exactly == 1. For it to have two real roots, it just must be greater than 0, the discriminant can be any real number in this case (e.g. 4.2564)