Python Program to solve a quadratic equation

How to solve a quadratic equation in python?

In this python program example, we solve a quadratic equation of 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 not be a quadratic equation; it will be a linear equation.

To solve the quadratic equation, we use the formula x= (-b + sqrt(b2 - 4ac))/2a or x= (-b - sqrt(b2 - 4ac))/2a. here b2 - 4ac is called the discriminant. and the 'a', 'b', 'c' Are called the coefficients.

In this python program for beginners, we have to import complex math.cmath is a built-in module  in the python programming language 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 simple python program, we accept the values for a, b, c and convert that to float using float data type in python. 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.

so We will break this python code step by step.


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 convert 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.

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