Write a Python Program to Solve Quadratic Equation

In mathematics, a quadratic equation is a polynomial equation of the second degree, which can be expressed in the form ax² + bx + c = 0, where a, b, and c are coefficients and x is the variable.

Quadratic equations have a wide range of applications in physics, engineering, finance, and many other fields.

In this tutorial, we will discuss how to solve a quadratic equation using Python programming language.


To solve a quadratic equation using Python, we need to write a program that takes the values of a, b, and c as input, computes the roots of the equation, and displays the solutions.

There are several ways to solve a quadratic equation, but one of the most common methods is the quadratic formula, which is given by:

x = (-b ± sqrt(b² – 4ac)) / 2a

Using this formula, we can easily find the roots of a quadratic equation.

Here is the Python code to solve a quadratic equation using the quadratic formula:

import math

# input values of a, b, and c
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("Enter the value of c: "))

# calculate the discriminant
d = b**2 - 4*a*c

# find the roots
if d < 0:
    print("No real roots")
elif d == 0:
    x = -b / (2*a)
    print("One real root: ", x)
else:
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print("Two real roots: ", x1, x2)

Let’s break down the above code.

First, we import the math module, which contains the sqrt function that we need to compute the square root of the discriminant.

Then, we take the values of a, b, and c as input from the user using the input() function.

Next, we calculate the discriminant d using the formula d = b**2 - 4*a*c.

Next, we check the value of the discriminant d to determine the number and nature of roots of the equation.

If d is less than zero, the equation has no real roots.

If d is zero, the equation has one real root, which is calculated using the formula x = -b / (2*a).

If d is greater than zero, the equation has two real roots, which are calculated using the formula x1 = (-b + math.sqrt(d)) / (2*a) and x2 = (-b - math.sqrt(d)) / (2*a).

Finally, we print the solutions using the print() function.

If the equation has no real roots, we simply print a message saying so.

If the equation has one real root, we print the value of the root.

If the equation has two real roots, we print both roots.


In conclusion, solving quadratic equations using Python is a simple and straightforward process.

By using the quadratic formula and basic programming constructs, we can easily find the roots of any quadratic equation.