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

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Sun Oct 8 00:03:06 EDT 2006


In message <1160165545.417968.276460 at b28g2000cwb.googlegroups.com>, sam
wrote:

> i'm still in the early stages, and am trying to code something simple
> and interactive to get the percentages of the portfolio in the five
> different investment categories. i thought i'd get in with the error
> handling early so if someone types in something wrong (like a word), or
> the numbers don't add up to 100%, the error would be caught immediately
> and the user sent back to the start of the loop. granting that there
> may be better ways of doing this, if i decide that i do want to do it
> like this (i.e. a single error requires all data to be re-entered, not
> unreasonable for only five items) ...

One obvious thing is to remove repetitiveness from the code by collecting
the different cases in a data table. E.g.

    data = {}
    input_control = \
        [
            {
                "key" : "cash",
                "description" : "cash percentage",
                "type" : int,
                "describe_type" : "number",
            },
            {
                "key" : "bond",
                "description" : "bond portfolio",
                "type" : int,
                "describe_type" : "number",
            },
            {
                "key" : "blue",
                "description" : "blue-chip percentage",
                "type" : int,
                "describe_type" : "number",
            },
            {
                "key" : "tech",
                "description" : "tech stocks percentage",
                "type" : int,
                "describe_type" : "number",
            },
            {
                "key" : "dev",
                "description" : "developing countries percentage",
                "type" : int,
                "describe_type" : "number",
            },
        ]

    while True :
        index = 0
        while index != len(input_control) :
            control = input_control[index]
            try :
                data[control["key"]] = \
                    control["type"](raw_input(
                            "Please enter a %s index for the portfolio: "
                        %
                            control["description"]
                        ))
                index += 1
        except ValueError :
            print "That is not a %s." % control["describe_type"]
        #end try
    #end while
    if sum([data[k] for k in data]) == 100 :
        break
    print "Those numbers do not sum to 100. Please start again."
#end while




More information about the Python-list mailing list