Easy Tutorial
❮ Python Os Read Python File Next ❯

Python Quadratic Equation

Python3 Examples

The following example calculates the quadratic equation by taking user input for the coefficients:

Example (Python 3.0+)

# Filename : test.py
# author by : www.tutorialpro.org

# Quadratic equation ax**2 + bx + c = 0
# a, b, c are provided by the user, real numbers, a ≠ 0

# Import cmath (complex math) module
import cmath

a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# Calculate
d = (b**2) - (4*a*c)

# Two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solutions are {0} and {1}'.format(sol1, sol2))

Executing the above code outputs:

$ python test.py
Enter a: 1
Enter b: 5
Enter c: 6
The solutions are (-3+0j) and (-2+0j)

In this example, we used the sqrt() method from the cmath (complex math) module to compute the square root.

Python3 Examples

❮ Python Os Read Python File Next ❯