Robust user input (exception handling) example in Python
Archive - Originally posted on "The Horse's Mouth" - 2009-09-17 20:02:52 - Graham EllisOne of the questions in the "exceptions" section of the Python Course asks my delegates to "Graham Proof" a piece of code:
first = int(input("First number: "))
second = int(input("Second number: "))
print "Sum is "+str(first+second)
The idea is that I come round the room and put really awkward inputs into customer's programs, as would a hacker or a non-thinking user. Not only is there a need to trap exceptions, but input should be changed to raw_input, and the input / error handling delegated to a function so that an error on the second input doesn't push the user back to remaking the first input, nor does it result in code duplication. Here is what I came up with:
def getval(pr):
while 1:
try:
result = raw_input(pr+" ")
val = float(result)
return val
except EOFError:
print "Ran out of Data"
exit()
except:
print "nah"
first = getval("first number")
second = getval("second number")
print "Sum is "+str(first+second)
A further comment on the EOFError. On some systems, you can continue to read even if you've received an EOF - RedHat Fedora Linux being one of them. On others, such as my Mac with OS X, reading past the end of file results in the code returning a further EOF without checking / waiting so see if there's any more data. My code above deals with the case on both types of operating system ...