Python Program to find roots of a Quadratic Equation

Write a Python program to find Roots of a Quadratic Equation with an example. The mathematical representation of a Quadratic Equation is ax²+bx+c = 0. A Quadratic Equation can have two roots, and they depend entirely upon the discriminant. If discriminant > 0, then Two Distinct Real Roots exists for this equation

C Program to find Roots of a Quadratic Equation 3

If discriminant = 0, Two Equal and Real Roots exists.

C Program to find Roots of a Quadratic Equation 4

And if discriminant < 0, Two Distinct Complex Roots exists.

C Program to find Roots of a Quadratic Equation 5

Python Program to find roots of a Quadratic Equation using elif

This python program allows user to enter three values for a, b, and c. By using those values, this Python code find roots of a quadratic equation using Elif Statement.

# Python Program to find roots of a Quadratic Equation
import math

a = int(input("Please Enter a Value of a Quadratic Equation : "))
b = int(input("Please Enter b Value of a Quadratic Equation : "))
c = int(input("Please Enter c Value of a Quadratic Equation : "))

discriminant = (b * b) - (4 * a * c)

if(discriminant > 0):
    root1 = (-b + math.sqrt(discriminant) / (2 * a))
    root2 = (-b - math.sqrt(discriminant) / (2 * a))
    print("Two Distinct Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant == 0):
    root1 = root2 = -b / (2 * a)
    print("Two Equal and Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant < 0):
    root1 = root2 = -b / (2 * a)
    imaginary = math.sqrt(-discriminant) / (2 * a)
    print("Two Distinct Complex Roots Exists: root1 = %.2f+%.2f and root2 = %.2f-%.2f" %(root1, imaginary, root2, imaginary))
Python Program to find roots of a Quadratic Equation 1