Skip to content
Home » Python Program to Solve Quadratic Equation

Python Program to Solve Quadratic Equation

Learn about Python Program to Solve Quadratic Equation in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

Python Program to Solve Quadratic Equation

A quadratic equation is a second-degree equation, which means it contains at least one squared element. The quadratic equation has the conventional form ax2 + bx + c = 0, where a, b, and c are real and a!=0, and x is an unknown variable. The discriminant determines the nature of the roots.

While declaring the variables, we will take three numbers. Using the math module and an if-else statement, a Python program is used to find the roots of a quadratic equation.

Source code:

# Python program to find roots of quadratic equation

#importing math module
import math  

# inputs from user
a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
c = int(input('Enter the value of c: '))

# calculate discriminant
dis = (b**2) - (4*a*c)

# check condition for discriminant
if(dis > 0):
    root1 = (-b + math.sqrt(dis) / (2 * a))
    root2 = (-b - math.sqrt(dis) / (2 * a))
    print("Two distinct real roots are %.2f and %.2f" %(root1, root2))

elif(dis == 0):
    root1 = root2 = -b / (2 * a)
    print("Two equal and real roots are %.2f and %.2f" %(root1, root2))

elif(dis < 0):
    root1 = root2 = -b / (2 * a)
    imaginary = math.sqrt(-dis) / (2 * a)
    print("Two distinct complex roots are %.2f+%.2f and %.2f-%.2f" 
                          %(root1, imaginary, root2, imaginary))

Output:

Enter the value of a: 1
Enter the value of b: 5
Enter the value of c: 6
Two distinct real roots are -4.50 and -5.50

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.

Similar Code : Difference of Two Numbers using abs() Function Python