Write a Python program that reads option-value pairs from the command-line. The
ID: 3685160 • Letter: W
Question
Write a Python program that reads option-value pairs from the command-line. The program should find the squareroots of a quadratic function using the quadratic formula: X = -b plusminus Squareroot b^2 - 4ac/2a From the command-line, the user should have the ability to enter values for a, b, and c. The default values for a, b, and c are a = b = c = 1. LASTNAME_FIRSTNAME_HW_5_PROB_3.py [filename].py -a 1 -b -2 -c -1 squareroots of the equation x**2 + 2x + 1 = 0 are: -1 and -1 [filename].py squareroots of the equation x**2 + x + 1 = 0 are: -0.5 + 0.866 i and -0.5 - 0.866 iExplanation / Answer
#!/usr/bin/python
import sys
import math
#Python script that returns the roots of a quadratic equation
#of the form a*x^2 + b*x + c = 0
#Enter values for a, b, and c in the command line
#e.g. run: >python quadratic.py 1 2 -15
def main():
try:
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
except ValueError:
print 'Give Numerical Inputs'
exit()
x1, x2 = find_roots(a, b, c)
print "This is x1: %f" %x1
print "This is x2: %f" %x2
def find_roots(a,b,c):
mid = b**2 - 4*a*c
try:
sqrt_mid = math.sqrt(mid)
except ValueError:
print "Imaginary Roots"
exit()
try:
x1 = (-b + sqrt_mid)/(2*a)
x2 = (-b - sqrt_mid)/(2*a)
except ZeroDivisionError:
print 'Do not give an a value of zero, this program expects a quadratic function'
exit()
return x1, x2
if __name__=="__main__":
main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.