So I have to write a code that solves a quadratic equation. The user has to input in a,b,c for the quadratic equation. The rules for inputting are:
-The user must input three floating point numbers (do not worry if the user inputs
non floats and your program crashes). The user must not enter zero for A.
Prompt the user until the user provides valid input.
I'm having SO MUCH TROUBLE ON THIS PART!
Here is my code:
import math
def quad():
temp = [] #initialize variables
while (len(temp)!= 3):
values = input("Input A B C>") #input string from line
temp = values.split() #split string into list
## if len(temp)==0:
## values = input("Input A B C>")
##
## if len(temp)==1:
## values = input("Input A B C>")
##
## if len(temp)==2:
## values = input("Input A B C>")
##
## if len(temp)==3:
##
new_list=[]
for item in temp:
new_list.append(float(item))
d = new_list[1]**2 - 4 * new_list[0] * new_list[2]
## d = b**2 - 4*a*c
if d < 0:
x1 =(-new_list[1] + (d*-1)) / (2*new_list[0])
x2 =(-new_list[1] + (d*-1)) / (2*new_list[0])
if new_list[0] == 1:
print("Solution for", "x^2", "+", new_list[1], "x", "+",new_list[2],"is:", str(x1)+"+i" , str(x2)+"-i")
else:
print ("Solution for", new_list[0],"x^2", "+", new_list[1], "x", "+",new_list[2],"is:", str(x1)+"+i" , str(x2)+"-i")
elif d == 0:
x = (-new_list[1]+math.sqrt(d))/(2*new_list[0])
if new_list[0] == 1:
print("Solution for", "x^2", "+", new_list[1], "x", "+",new_list[2],"is:", x)
else:
print ("Solution for", new_list[0],"x^2", "+", new_list[1], "x", "+",new_list[2],"is:", x)
else:
x1 = (-new_list[1]+math.sqrt(d))/(2*new_list[0])
x2 = (-new_list[1]-math.sqrt(d))/(2*new_list[0])
if new_list[0] == 1:
print("Solution for", "x^2", "+", new_list[1], "x", "+",new_list[2],"is:", x1, "and", x2)
else:
print ("Solution for", new_list[0],"x^2", "+", new_list[1], "x", "+",new_list[2],"is:", x1, "and", x2)
quad()
THE WHILE LOOP IS WHERE I AM STRUGGLING! Ok so I want the program to know when the user is inputting only 0,1,or 2 numbers for a,b,c (since they have to input 3). I don't know how to do this! I'm struggling to write a while loop for this!

New Topic/Question
Reply


MultiQuote



|