Home » Program to Find Roots of Quadratic Equation using Function in Python

# Program to Find Roots of Quadratic Equation using Function in Python

Learn about the Program to Find Roots of Quadratic Equation using Function in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.

Contents

#### Program to Find Roots of Quadratic Equation using Function in Python

The quadratic equation has the conventional form ax²+ bx + c = 0, where a, b, and c are real and a!=0, and x is an unknown variable.

The discriminant is calculated in the below program using the below formula :

discriminant(d) = b² – 4*a*c

Program:

``````# Python program to solve quadratic equation

#importing math module
import math

def edu_roots(a, b, c):
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))

# 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: '))

# function call
edu_roots(a, b, c)``````

Output:

```Enter the value of a: 1
Enter the value of b: 5
Enter the value of c: 4
Two distinct real roots are -3.50 and -6.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 : Python Program to Solve Quadratic Equation