exceptions and assertions what the programmer should have written would look something like while trueval raw_input('enter an integer'tryval int(valprint 'the square of the number you entered is'val** break #to exit the while loop except valueerrorprint val'is not an integerafter entering the loopthe program will ask the user to enter an integer once the user has entered somethingthe program executes the try--except block if neither of the first two statements in the try block causes valueerror exception to be raisedthe break statement is executed and the while loop is exited howeverif executing the code in the try block raises valueerror exceptioncontrol is immediately transferred to the code in the except block thereforeif the user enters string that does not represent an integerthe program will ask the user to try again no matter what text the user entersit will not cause an unhandled exception the downside of this change is that the program text has grown from two lines to eight if there are many places where the user is asked to enter an integerthis can be problematical of coursethis problem can be solved by introducing functiondef readint()while trueval raw_input('enter an integer'tryval int(valreturn val except valueerrorprint val'is not an integerbetter yetthis function can be generalized to ask for any type of inputdef readval(valtyperequestmsgerrormsg)while trueval raw_input(requestmsg 'tryval valtype(valreturn val except valueerrorprint valerrormsg the function readval is polymorphici it works for arguments of many different types such functions are easy to write in pythonsince types are firstclass values we can now ask for an integer using the code val readval(int'enter an integer:''is not an integer'exceptions may seem unfriendly (after allif not handledan exception will cause the program to crash)but consider the alternative what should the type conversion int dofor examplewhen asked to convert the string 'abcto an object of type intit could return an integer corresponding to the bits used to encode the stringbut this is unlikely to have any relation to the intent of the programmer alternativelyit could return the special value none if it did that