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
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 – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.