Python Program to Solve Quadratic Equation

In this post, we will learn how to solve a quadratic equation using Python Programming language.

This program asks the user to enter the values of a, b and c, then it computes the roots of the quadratic equation using cmath.

So, without further ado, let’s begin this tutorial.

Python Program to Solve Quadratic Equation

# Python Program to Solve Quadratic Equation
import cmath

# Asking for input
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))

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

# finding roots
root1 = (-b-cmath.sqrt(d)) / (2 * a)
root2 = (-b+cmath.sqrt(d)) / (2 * a)
print("The Roots are {0} and {1}" .format(root1, root2))

Output

Enter the value of a: 2
Enter the value of b: 1
Enter the value of c: -6
The Roots are (-2+0j) and (1.5+0j)

How Does This Program Work ?

import cmath

We import the cmath module in our program in order to perform complex square root.

# Asking for input
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = int(input("Enter the value of c: "))

The user is asked to enter the values of a, b and c.

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

Then, we calculate the discriminant using the formula b2 – 4ac.

# finding roots
root1 = (-b-cmath.sqrt(d)) / (2 * a)
root2 = (-b+cmath.sqrt(d)) / (2 * a)

Now, we calculated the square roots using the formula [(-b + (4ac)½ ) / 2a] and  [(-b – (4ac)½) / 2a].

print("The Roots are {0} and {1}" .format(root1, root2))

Finally, the result is displayed on the screen using print() function.

Conclusion

I hope after going through this post, you understand how to solve a quadratic equation using Python Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published.