Here’s an example Python code to solve a quadratic equation:
# Import the math module
import math
# Take input from the user
a = float(input("Enter the coefficient a: "))
b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))
# Calculate the discriminant
discriminant = b**2 - 4*a*c
# Check if the discriminant is positive, negative, or zero
if discriminant > 0:
# Two real and distinct roots
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print("The roots are", root1, "and", root2)
elif discriminant == 0:
# One real and repeated root
root = -b / (2*a)
print("The root is", root)
else:
# Two complex roots
real_part = -b / (2*a)
imaginary_part = math.sqrt(-discriminant) / (2*a)
print("The roots are", real_part, "+", imaginary_part, "i and", real_part, "-", imaginary_part, "i")
In this code, we first import the math module, which provides several mathematical functions, including the sqrt() function for finding the square root of a number.
We then use the input() function to prompt the user to enter the coefficients a, b, and c of the quadratic equation. We convert the user input to a float using the float() function and assign them to the variables a, b, and c.
Next, we calculate the discriminant of the quadratic equation using the formula b**2 - 4*a*c and assign the result to the variable discriminant.
We then use an if statement to check if the discriminant is positive, negative, or zero, and compute the roots accordingly. If the discriminant is positive, the quadratic equation has two real and distinct roots, which we calculate using the quadratic formula and assign to the variables root1 and root2. If the discriminant is zero, the quadratic equation has one real and repeated root, which we calculate using the quadratic formula and assign to the variable root. If the discriminant is negative, the quadratic equation has two complex roots, which we calculate using the quadratic formula and assign to the variables real_part and imaginary_part.
Finally, we use the print() function to output the roots of the quadratic equation.
When you run this code, it should prompt you to enter the coefficients a, b, and c of the quadratic equation. Once you enter those values and press enter, it should output the roots of the quadratic equation. For example:
Enter the coefficient a: 2 Enter the coefficient b: -7 Enter the coefficient c: 3 The roots are 3.0 and 0.5
Note that you can replace 2, -7, and 3 with any other values you want to solve a quadratic equation with different coefficients.