exceptions and assertions def getgrades(fname)trygradesfile open(fname' '#open file for reading except ioerrorraise valueerror('getgrades could not open fnamegrades [for line in gradesfiletrygrades append(float(line)exceptraise valueerror('unable to convert line to float'return grades trygrades getgrades('quiz grades txt'grades sort(median grades[len(grades)// print 'median grade is'median except valueerrorerrormsgprint 'whoops 'errormsg figure get grades the function getgrades either returns value or raises an exception with which it has associated value it raises valueerror exception if the call to open raises an ioerror it could have ignored the ioerror and let the part of the program calling getgrades deal with itbut that would have provided less information to the calling code about what went wrong the code that uses getgrades either uses the returned value to compute another value or handles the exception and prints useful error message assertions the python assert statement provides programmers with simple way to confirm that the state of the computation is as expected an assert statement can take one of two formsassert boolean expression or assert boolean expressionargument when an assert statement is encounteredthe boolean expression is evaluated if it evaluates to trueexecution proceeds on its merry way if it evaluates to falsean assertionerror exception is raised assertions are useful defensive programming tool they can be used to confirm that the arguments to function are of appropriate types they are also useful debugging tool the can be usedfor exampleto confirm that intermediate values have the expected values or that function returns an acceptable value