每当我尝试运行此代码时,我都会收到错误"字符串索引超出范围。"
但是,这是在输出之后:
[820.34]
['Joint']
[820.34, 0]
['Joint', 'Joint']
我不知道为什么它给我一个字符串错误,因为我的函数计算的参数是列表(income [i]和status [i])。很抱歉长代码,但非常感谢一些帮助!
infile=open("data.txt",'r')
a=infile.readline()
Name=[]
status=[]
income=[]
while(len(a)>0):
Fname,Lname,statuses,incomes=a.split()
Name.append(Fname+ ' '+ Lname)
status.append(statuses)
income.append(incomes)
a=infile.readline()
a=range(len(income))
taxes=0
taxes_s=0
taxes_j=0
tax=[]
Status=[]
def calculations(income,status,Status,tax,taxes):
if status=="S" or status=="s":
if float(income)<0:
pass
elif float(income)<1710:
taxes_s=0
elif float(income)<20930:
taxes_s=87 + .03*(float(income)-1710)
elif float(income)<28790:
taxes_s=742.40 + .08*(float(income)-20930)
elif float(income)>=28790:
taxes_s=1449.60 + .11*(float(income)-28790)
taxes_j=0
status="Single"
elif status=="J" or status=="j":
if float(income)<0:
pass
elif float(income)<3420:
taxes_j=0
elif float(income)<47120:
taxes_j=330 + .04*(float(income)-3420)
elif float(income)<57580:
taxes_j=1905.40 + .09*(float(income)-47120)
elif float(income)>=57580:
taxes_j=2899.20 + .11*(float(income)-57580)
taxes_s=0
status="Joint"
else:
pass
global taxes_j
global taxes_s
if taxes_j==0:
net=float(income)-taxes_s
taxes=taxes_s
elif taxes_s==0:
net=float(income)-taxes_j
taxes=taxes_j
Status.append(status)
tax.append(taxes)
return Status,income,net,tax
for i in a:
Status,income,net,tax=calculations(income[i],status[i],Status,tax,taxes)
print(tax)
print(Status)
按要求输入数据:
Joe Smith J 15678.50
Joseph Kardian j 539590.00
Bill Jones X 8976.0
Nancy Brown j -9087.0
Marty Klauss S 3390.58
Ali Hakimi s 675890.0
George Karlton J 67534.50
答案 0 :(得分:2)
问题出在这里
for i in a:
Status,income,net,tax=calculations(income[i],status[i],Status,tax,taxes)
print(tax)
print(Status)
Realpce with:
for i in a:
Status,income1,net,tax=calculations(income[i],status[i],Status,tax,taxes)
print(tax)
print(Status)
您正在使用收入来分配数据,这将取代收入列表,导致错误,因为索引超出范围,请提供唯一名称以避免此类错误