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



In message <1160165545.417968.276460@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>, 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

.



Relevant Pages