main()
, invoice.close()
, 和它上面的 print 函数都抛出“无效语法”异常。
我对字典或函数一无所知(此时),所以这是我能想到的最好的。
这是我想要的结果:
以下是 的内容invoice.txt
:
#### CONTENTS OF invoice.txt ###
# hammer#9.95
# saw#20.15
# shovel#35.40
编辑 *** 这是添加括号的例外 在 此处输入图像描述
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )
def main():
invoice = open("invoice.txt", "r")
count = 0
total = 0
hammer = invoice.readline()
while invoice != "":
saw = invoice.readline()
shovel = invoice.readline()
hammer = hammer.rstrip("\n")
saw = saw.rstrip("\n")
shovel = shovel.rstrip("\n")
hammer = hammer.split("#")
saw = saw.split("#")
shovel = shovel.split("#")
print('{0: <10}'.format(hammer[0]), '{0: >17}'.format('$' + hammer[1]), sep = '' )
print('{0: <10}'.format(saw[0]), '{0: >17}'.format('$' + saw[1]), sep = '' )
print('{0: <10}'.format(shovel[0]), '{0: >17}'.format('$' + shovel[1]), sep = '' )
# total = total + float(hammer[1]) + float(saw[1]) + float(shovel[1]) # DOESN"T WORK
total = total + (int(float(hammer[1])) + int(float(saw[1])) + int(float(shovel[1]))
# total = total + (int(hammer[1])) + (int(saw[1])) + (int(shovel[1])) # DOESN"T WORK
print("{0: <10}".format("Total cost") + "{0: >17}".format("{0:.2f}".format(float(total))))
invoice.close()
main()