Python Program to Solve the Quadratic Equation

In this post, we will discuss how to write a python program to solve the quadratic equation.

What is Quadratic Equation?

In algebra, a quadratic equation is an equation having the form

ax2 + bx + c

where x represents an unknown variable, and ab, and c represent known numbers such that a is not equal to 0.

The numbers ab, and, are the quadratic coefficients of the equation.

What do you mean by solving the Quadratic Equation?

Solving the Quadratic Equation means that we have to find the roots of the equation.

How to find the roots of the Quadratic Equation?

We use the Quadratic Formula to find the roots of the equation.

Firstly, we find the discriminant.

d = (b2) - (4*a*c)

And then we find the two roots using the discriminant.

r1 = (-b + sqrt(d)) / (2*a)
r2 = (-b - sqrt(d)) / (2*a)

The nature of roots is decided by the value of discriminant.

If d > 0, the roots will be real;
If d < 0, the roots will be complex;
And if d = 0, the roots will be real and equal.

Let's see the code for this program.


# import complex math module
import cmath
# general quadratic equation is ax**2 + bx + c

a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("And Enter the value of c: "))

# printing the full equation
print('The Quadratic Equation is ',a,'x**2 + ',b,'x + ',c,sep='')

# calculating discriminant
d = (b**2) - (4*a*c)

# evaluating first root
r1 = (-b + cmath.sqrt(d)) / (2*a)
r2 = (-b - cmath.sqrt(d)) / (2*a)

# prinring the roots
print("First root:",r1)
print("Second root:",r2)


Enter the value of a: 8
Enter the value of b: 4
And Enter the value of c: 5
The Quadratic Equation is 8.0x**2 + 4.0x + 5.0
First root: (-0.25+0.75j)
Second root: (-0.25-0.75j)

I have used the sqrt() function from the cmath module to find the square root of the discriminant.

I have also used the sep parameter of the print() function so that I can format the quadratic equation properly. If you don't know what is sep parameter, you can check the Print Hello World program.

That was all about this python program.

Thanks for visiting our website. If you have any doubt, you can comment below.

You can learn about many other Python Programs Here.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...