首页 > 解决方案 > ("总计:$%.2f" (grand_total)) 在 python3 中

问题描述

我不断收到语法错误:以下打印语句的语法无效:

print("Grand Total: $%.2f" (grand_total))

任何人都可以帮忙吗?

我尝试了不同的变化,但没有运气。

# Set dictionary and lists
grocery_item = {}
grocery_history = []
stop = 'go'
# Shopping list loop
while stop != 'q':
    item_name = input("Item name:\n")
    quantity = input("Quantity purchased:\n")
    cost = input("Price per item:\n")
    grocery_item['name'] = item_name
    grocery_item ['number'] = int(quantity)
    grocery_item['price'] = float(cost)
    grocery_history.append(grocery_item)
    stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")

grand_total = 0
# Total items/ cost
for grocery_item in grocery_history:
    item_total = grocery_item['number'] * grocery_item['price']
    # Compute grand total
    grand_total = item_total + grand_total
    # Print Gracery History List
    print(grocery_item[number] + grocery_item['name'] + " @ $%.2f" + grocery_item['price'] + " ea $%.2f" + (item_total)
    # Print Grang Total
    print("Grand Total: $%.2f" (grand_total))
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
1 milk @ $2.99 ea $2.99
2 eggs @ $3.99 ea $7.98
4 onions @ $0.79 ea $3.16
Grand total: $14.13

标签: pythonpython-3.x

解决方案


%除了在最后一次调用中缺少字符串格式化运算符外print,正如评论中已经指出的那样,您在最后一次调用中还缺少右括号print

print(grocery_item[number], grocery_item['name'] % " @ $%.2f", grocery_item['price'], " ea $%.2f" % (item_total))

推荐阅读