Python Program to Find Roots of a Quadratic Equation

A quadratic equation has two roots — two values of x which satisfies the given equation. Although sometimes these two values may turn out to be the same.

This python program calculates the two roots of quadratic equation and these two roots are indicated by x1 and x2.

Finding Roots of Quadratic Equation in Python


# Defining Function To Find Roots
def findRoots(a, b, c):
    d = (b*b - 4*a*c)**0.5
    x1 = (-b + d)/(2*a)
    x2 = (-b - d)/(2*a)
    print('\nROOTS OF GIVEN QUADRATIC EQUATIONS ARE:')
    print('x1: {0}'.format(x1))
    print('x2: {0}'.format(x2))

# Input Section
print('Solving ax^2 + bx + c =0')
a = float(input('Enter the value of a: '))
b = float(input('Enter the value of b: '))
c = float(input('Enter the value of c: '))

# Function Call
findRoots(a,b,c)

Output of the above program:

Run 1:
----------
Solving ax^2 + bx + c =0
Enter the value of a: 1
Enter the value of b: 5
Enter the value of c: 6

ROOTS OF GIVEN QUADRATIC EQUATIONS ARE:
x1: -2.0
x2: -3.0

Run 2:
----------
Solving ax^2 + bx + c =0
Enter the value of a: 1
Enter the value of b: 2
Enter the value of c: 5

ROOTS OF GIVEN QUADRATIC EQUATIONS ARE:
x1: (-0.9999999999999999+2j)
x2: (-1.0000000000000002-2j)