Main Content

Trying things in Python

Archive - Originally posted on "The Horse's Mouth" - 2007-06-18 07:14:29 - Graham Ellis

Are you used to writing long sections of code to validate user input? Perhaps you are, or perhaps you have shortened such code over the years using Regular Expressions where you can specify a pattern to be matched. One regular expression can replace 30 lines of other code.

But in Python, Java and some other languages there's an even more elegant alternative in some circumstances - exceptions. The idea is that you try to perform the action you require on your input data rather than 100% validating it first. If the action works, great and if it fails you catch the exception and handle the error condition in that block.

Like an example? Here's a piece of Python code to read an integer from the program's user, and to keep re-prompting if the user enters a value that cannot be treated as a legitimate integer.

while 1:
  val = raw_input("give an integer ... ")
  try:
    ival = int(val)
    break
  except:
    print "an integer is a WHOLE NUMBER! "
print ival