請定義一個函式quadratic(a, b, c),接收3個引數,返回一元二次方程:ax² + bx + c = 0的兩個解。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import math 4 def quadratic(a,b,c): 5 if a == 0: 6 raise TypeError('a不能為0') 7 if not isinstance(a,(int,float)) or not isinstance(b,(int,float)) or not isinstance(c,(int,float)): 8 raise TypeError('Bad operand type') 9 delta = math.pow(b,2) - 4*a*c 10 if delta < 0: 11 return '無實根' 12 x1= (math.sqrt(delta)-b)/(2*a) 13 x2=-(math.sqrt(delta)+b)/(2*a) 14 return x1,x2 15 print(quadratic(2,3,1)) 16 print(quadratic(1,3,-4))