Python Program to solve a quadratic equation

May 1, 2022, Learn eTutorial

What is a quadratic equation?

In Algebra, a Quadratic equation is defined as any equation that can be written as ax2 + bx + c = 0 where a, b and c are user inputs. And the x is the unknown we have to find out where the a is not equal to zero. If the a is equal to zero, then it will be a linear equation.

How to solve a quadratic equation in python?

To solve the quadratic equation, we use the formula x= (-b + sqrt(b2 - 4ac))/2a or x= (-b - sqrt(b2 - 4ac))/2a, where 

  • b2 - 4ac is called the discriminant.
  • 'a', 'b', 'c' Are called the coefficients.

In this python program, we have to import complex math.cmath is a built-in module to do math operations with complex numbers. cmath Also accepts int, float, and complex math numbers. cmath module method returns a complex value. If the return value is a real number, it will have an imaginary part of zero value.

In this python program, we accept the values for a, b, c and convert that to float using float data type. Now we have to find out the discriminant d using the formula (b**2) - (4*a*c) and apply that discriminant to calculate sol1 and sol2. Finally, print the result.


STEP 1: Import cmath module to do calculations with complex numbers.

STEP 2: accepts the values of coefficients of a, b, and c using the input function in python language and converts that string to float using float data type.

STEP 3: Now, we have to calculate the discriminant 'd' using the equation.b**2 - 4*a*c and we have to apply that discriminant in the main quadratic equation.

STEP 4: Now, we find the solution to the quadratic equation (-b-cmath.sqrt(d))/(2*a) and save the result in the variables 'sol1' and sol2.

STEP 5: Print the result using the format method.

Note: The format method is used to format the result and insert that value into the format placeholder. Here in the format method, we use{} brackets as the placeholders. format method returns the string value.

Python Source Code

                                          import cmath  
a = float(input('Enter the value a: '))  
b = float(input('Enter the value b: '))  
c = float(input('Enter the value c: '))  

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

sol1 = (-b-cmath.sqrt(d))/(2*a)    # Applying the discriminant in the quadratic formula
sol2 = (-b+cmath.sqrt(d))/(2*a)  
print('The result is {0} and {1}'.format(sol1,sol2))    # print the result using the format method


Enter the value a: 8
Enter the value a: 16
Enter the value a: 8

The result is  -1 + 0j and -1 + 0j