问题
ValueError: invalid literal for int() with base 10: ''
Why it showing the error of int(), in fact the values coming from the cgi is as string which i am converting it to integer, bcoz my comparable part variable actual_ans_dict contains an integer
res12 = form.getvalue('opt_12', '')
res27 = form.getvalue('opt_27', '')
res20 = form.getvalue('opt_20', '')
res16 = form.getvalue('opt_16', '')
res13 = form.getvalue('opt_13', '')
res19 = form.getvalue('opt_19', '')
res25 = form.getvalue('opt_25', '')
actual_ans_dict = {}
count = 0
b = []
for data in prsnobj.result:
actual_ans_dict[data[0]] = data[1]
#print actual_ans_dict[12], actual_ans_dict[27], actual_ans_dict[20], actual_ans_dict[16], actual_ans_dict[13], actual_ans_dict[19], actual_ans_dict[25]
if int(res12) == actual_ans_dict[12]:
count += 1
if int(res27) == actual_ans_dict[27]:
count += 1
if int(res20) == actual_ans_dict[20]:
count += 1
if int(res16) == actual_ans_dict[16]:
count += 1
if int(res13) == actual_ans_dict[13]:
count += 1
if int(res19) == actual_ans_dict[19]:
count += 1
if int(res25) == actual_ans_dict[25]:
count += 1
if count:
b.append(count)
if len(b)==0:
print "Fail"
else:
print "Marks: ", b
回答1:
The problem is because int
tries to convert ''
to a base 10 number, which is not possible. Thats why it is failing. You are getting the default ''
if the value is not there like this
form.getvalue('opt_12', '')
instead of that use a sentinel value like this
form.getvalue('opt_12', '0')
Even better, you can convert them to numbers as and when you get them from the form like this
res12 = int(form.getvalue('opt_12', '0'))
...
...
...
来源:https://stackoverflow.com/questions/20375706/valueerror-invalid-literal-for-int-with-base-10-python