Python Program to Find the Roots of a Quadratic Equation

This is a Python Program to find the roots of an equation.

Problem Description

The program takes the coefficients of an equation and finds the roots of the equation.

Problem Solution

1. Take in the coefficients of the equation and store it in three separate variables.
2. Find the value of the discriminant, d.
3. Use an if statement to check if the value of the discriminant is greater than 0 or lesser than 0.
4. If the value of the discriminant is greater than 0, use the quadratic formula and find the roots rounded upto 2 decimal places.
5. Print the roots of the equation.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the roots of an equation. The program output is also shown below.

print("Equation: ax^2 + bx + c ")
a=int(input("Enter a: "))
b=int(input("Enter b: "))
c=int(input("Enter c: "))
d=b**2-4*a*c
d1=d**0.5
if(d<0):
    print("The roots are imaginary. ")
else:
    r1=(-b+d1)/2*a
    r2=(-b-d1)/2*a
    print("The first root: ",round(r1,2))
    print("The second root: ",round(r2,2))
Program Explanation

1. User must enter the coefficients of the equations and store it in three separate variables.
2. The value value of the discriminant, d, is found out which determines the nature of roots of the equation.
3. If the value of the discriminant is lesser than 0, the roots are imaginary.
4. If the value of the discriminant is greater than 0, the roots aren’t imaginary.
5. The value of the roots is found out using the quadratic formula.
6. The roots of the equation are printed.

advertisement
Runtime Test Cases
 
Case 1:
Equation: ax^2 + bx + c 
Enter a: 1
Enter b: -5
Enter c: 6
The first root:  3.0
The second root:  2.0
 
Case 2:
Equation: ax^2 + bx + c 
Enter a: 1
Enter b: 5
Enter c: 10
The roots are imaginary.

Sanfoundry Global Education & Learning Series – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

Free 30-Day Python Certification Bootcamp is Live. Join Now!

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.