I am trying to solve a programming task, and i have ran into some trouble. The task reads:
Consider the usual formula for computing solutions to the quadratic equation: ax2 + bx + c = 0 given by x = sqrt(b± b^2−4ac/2a) Write a program reads values for a,b and c from the command line. Use exceptions to handle missing arguments, and handle invalid input where b^2-4ac < 0
My program is as follows:
from math import sqrt
import sys
try:
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
bac = b**2 - 4*a*c
if bac < 0:
raise ValueError
except IndexError:
while True:
input("No arguments read from command line!")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
bac = b**2 - 4*a*c
if bac > 0:
break
if bac < 0:
while True:
print("Please choose values of a,b,c so\
that b^2 - 4ac > 0")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
bac = b**2 - 4*a*c
if bac > 0:
break
except ValueError:
while True:
input("Please choose values of a,b,c so that b^2 - 4ac > 0")
a = float(input("a = ? "))
b = float(input("b = ? "))
c = float(input("c = ? "))
if bac > 0:
break
for i in range(-1,2,2): # i=-1, next loop > i=1
x = (b + i*sqrt(bac)) / (2*a)
print("x = %.2f"%(x))
It seems to be working fine, but in the case below it doesnt:
terminal >
python quadratic_roots_error2.py
No arguments read from command line!
a = ? 1
b = ? 1
c = ? 1
Please choose values of a,b,c so that b^2 - 4ac > 0
a = ? 5
b = ? 2
c = ? -3
No arguments read from command line!
a = ? 5
b = ? 2
c = ? -3
x = -0.60
x = 1.00
Why does the program spit out the message "No arguments read from command line!"? I want the program to print every solution where b^2-4ac > 0, and whenever b^2-4ac < 0 i want the message "Please chose values of a,b,c so that b^2 - 4ac > 0" to be printed, like it does.