I like decorators to separate the checking from the rest of the input handling.
#!/usr/bin/env python def repeatOnError(*exceptions): def checking(function): def checked(*args, **kwargs): while True: try: result = function(*args, **kwargs) except Exceptionexceptions as problem: print "There was a problem with the input:" print problem.__class__.__name__ print problem print "Please repeat!" else: return result return checked return checking @repeatOnError(ValueError) def getNumberOfIterations(): return int(raw_input("Please enter the number of iterations: ")) iterationCounter = getNumberOfIterations() print "You have chosen", iterationCounter, "iterations." EDIT:
A decorator is more or less a wrapper for an existing function (or method). It takes the existing function (denoted below its @decorator directive) and returns a "replacement" for it. This replacement in our case calls the original function in a loop and catches any exception happening while doing so. If no exception happens, it just returns the result of the original function.