Write a Python program to find the roots of a quadratic function


This program is written in Python and it solves a quadratic equation of the form ax^2 + bx + c = 0 where a, b, and c are the coefficients of the equation.

The program prompts the user to input the values of a, b, and c using the input() function and stores them as floating-point numbers using the float() function. It then calculates the discriminant r using the formula b^2 - 4ac.

The program then checks the value of r using an if-elif-else statement.

  • If r > 0, it means that the quadratic equation has two distinct real roots. The program calculates the roots using the quadratic formula and assigns them to x1 and x2 variables. The roots are then printed on the console using the print() function.
  • If r == 0, it means that the quadratic equation has one real root. The program calculates the root using the quadratic formula and assigns it to the x variable. The root is then printed on the console using the print() function.
  • If r < 0, it means that the quadratic equation has no real roots. The program prints "No roots" using the print() function and exits the program using the exit() function.

Note that the sqrt() function from the math module is used to calculate the square root of r. It needs to be imported at the beginning of the program using the from math import sqrt statement.

Overall, this program provides a simple implementation of the quadratic formula to solve quadratic equations and can be used to quickly calculate the roots of a quadratic equation.

Source Code

from math import sqrt
 
print("Quadratic function : (a * x^2) + b*x + c")
a = float(input("Enter the a Number :"))
b = float(input("Enter the b Number :"))
c = float(input("Enter the c Number :"))
 
r = b**2 - 4*a*c
 
if( r > 0):
    num_roots = 2
    x1 = (((-b) + sqrt(r))/(2*a))     
    x2 = (((-b) - sqrt(r))/(2*a))
    print("There are Two Roots: ",x1, "and",x2)
elif(r == 0):
    num_roots = 1
    x = (-b) / 2*a
    print("There is one Root: ", x)
else:
    num_roots = 0
    print("No roots")
    exit()

Output

Quadratic function : (a * x^2) + b*x + c
Enter the a Number :2
Enter the b Number :5
Enter the c Number :3
There are Two Roots:  -1.0 and -1.5

Example Programs