【发布时间】:2019-11-24 05:36:07
【问题描述】:
main()、invoice.close() 和它上面的 print 函数都抛出“无效语法”异常。
我对字典或函数一无所知(目前),所以这是我能想到的最好的。
这是我想要的结果:
这里是invoice.txt的内容:
#### CONTENTS OF invoice.txt ###
# hammer#9.95
# saw#20.15
# shovel#35.40
编辑*** 这是添加括号的例外 enter image description here
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()
【问题讨论】:
-
欢迎来到 SO!请参阅this。您的文本文件是否真的以
#开头每一行并且第一行字面意思是#### CONTENTS OF invoice.txt ###?如果没有,请编辑这些。谢谢。 -
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
-
您似乎在以下行的末尾缺少一个右括号:total = total + (int(float(hammer[1])) + int(float(saw[1])) + int(float(shovel[1])). 应该是 total = total + (int(float(hammer[1])) + int(float(saw[1])) + int(float(shovel[1] )))