error handling in user input: is this natural or just laborious

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Oct 7 14:06:25 CEST 2006


On Fri, 06 Oct 2006 17:19:01 -0700, sam wrote:

> gosh, a lot of work to get some input. i must be missing something,
> though this is a lot better than what i had before...

Welcome to the real world of programming. Writing your algorithms is,
generally, the easy part. Handling data input and output and the user
interface is often much more work.

I would suggest you factor out logically separate parts of your code
something like this:

done = False
good_input = False
while not done:
    while not good_input:
        a, b, c, d = get_user_input() # or whatever values you need
        good_input = validate_user_input(a, b, c, d)
    done = do_something_with_input(a, b, c, d)


See how easy it is to understand the high level logic of the code,
without getting bogged down in gory details? Now all you have to do is
write functions get_user_input() etc.

E.g. I might write something like this:

class RangeError(ValueError):
    pass

def validate_user_input(a, b, c, d):
    # assumes all of a, b, c, d are percentages
    data = {'a': a, 'b':b, 'c': c, 'd': d}
    for name, value in data:
        try:
            float(value)
            if not (0.0 <= value <= 100.0):
                raise RangeError
        except RangeError:  # this must come first
             print name, "is out of range."
             return False
        except ValueError:
             print name, "is not a percentage."
             return False
    return True

-- 
Steve.




More information about the Python-list mailing list