最后一个 readline 函数一直有效,直到最近出现语法错误

Last readline function was working until a recent syntax error

我有一个 readline 函数,在我执行到代码的最后一步之前它一直在工作。

在代码的开头,我使用 "hammer" 定义了从文本文件中读取一行的函数。

Hammer 被多次用作字符串来表示循环中的其他函数。

现在,当我将它放在函数的末尾时,出现 "hammer."

的语法错误

(我已经包含了 "hammer" 从说明正下方抓取的 invoice.txt 文件内容)

# * Statement: Echos the contents of the file invoice.txt and sums prices and 
# * count of items
# * Specifications:
# * Input  - string describing a tool in the file invoice.txt
# *        - price of the tool in the file invoice.txt
# * Output - Message indicating the item and the cost
# *        - The sum of all costs and the number of items in the file invoice.txt
# ************************************************************************/

########################
# invoice.txt contents #
#--------------------- #
########################
hammer#9.95         
saw#20.15           
shovel#35.40

# output descriptive messages
print('This program will read each line in the file invoice.txt and print a\n'
       + 'a table indicating the item and it\'s cost.  When the file is exhausted,\n'
       + 'it will print the cumulative sum of all of the costs and the total \n'
       + 'number of items.\n')

# display header line for items list
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )

def main():

    invoice = open("Invoice.txt","r")

    count = 0
    total = 0

    hammer = invoice.readline()

    #Once hammer is read keep going
    while hammer != '':
        saw = invoice.readline()
        shovel = invoice.readline()

        #strip of extra lines
        hammer = hammer.rstrip('\n')
        saw = saw.rstrip('\n')
        shovel = shovel.rstrip('\n')

        #strip hashtags
        hammer = hammer.split('#')
        saw = saw.split('#')
        shovel = shovel.split('#')


        #print tools
        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 = '' )

        #convert prices to integer values
        total = total + (int(hammer[1])) + (int(saw[1])) + (int(shovel[1]))

        #print total line
        print('{0: <10}'.format('Total cost')) + ('{0: >17}'.format('{0:.2f}'.format(float(total))

        hammer = invoice.readline()

    invoice.close()

main()

program solution pdf

导致语法错误的行上方的括号错误。将您的 #print total 行更改为:

print('{0: <10}'.format('Total cost') + '{0: >17}'.format('{0:.2f}'.format(float(total))))