I am reading from an e-book, here is my code:
import math
class QuadError( Exception ):
pass
def quad(a,b,c):
if a == 0:
ex = QuadError( "Not Quadratic" )
ex.coef = ( a, b, c )
raise ex
if b*b-4*a*c < 0:
ex = QuadError( "No Real Roots" )
ex.coef = ( a, b, c )
raise ex
x1= (-b+math.sqrt(b*b-4*a*c))/(2*a)
x2= (-b-math.sqrt(b*b-4*a*c))/(2*a)
return (x1,x2)
Although I understood the try... except thing inside a function, I can't understand this... I understand what it does, e.g I have used quad(4, 2, 4) that gives me an "No Real Roots" error, or the quad(0, b, c) However I can't understand how the program itself works... So,
if a == 0:
a varibale with the name: "ex", gets the value: QuadError( "Not Quadratic" ) so the programs searches for the Class QuadError that has a pass command in it???! Then why does it print the message??? I would expect something like...
class QuadError( Exception ):
print Exception
Next thing I don't unserstand is the line:
ex.coef = ( a, b, c )
What's that??? is coef a command? Does it do something?
Thanks guys! :)
QuadError(Exception)inherits from Exception, which means that it gets all the fancy goodies that come with the Exception class. Including the ability to act like any standard exception. thepasskeyword is just a control flow statement of sorts that says, no more after me. and ex.coef is being assigned a tuple of a,b,c.ex.coef = ( a, b, c ), you need to go back to basics.