【发布时间】:2019-09-29 02:22:14
【问题描述】:
我不知道我做错了什么,请帮助:(
输出预期:
预期:
- 项目名称:
- 购买数量:
- 单件价格:
- 您要输入其他项目吗?输入“c”表示继续,输入“q”表示退出:
- 1 牛奶 @ 2.99 美元 2.99 美元
- 总计:2.99 美元
这是我的代码:
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
#Task: Create the empty data structure
grocery_item = {}
grocery_history = []
#Variable used to check if the while loop condition is met
stop = 'c'
while stop == 'c':
#Accept input of the name of the grocery item purchased.
item_name = input("Item name:\n")
#Accept input of the quantity of the grocery item purchased.
quantity = input("Quantity purchased:\n")
#Accept input of the cost of the grocery item input (this is a per-item cost).
cost = input("Price per item:\n")
#Using the update function to create a dictionary entry which contains the name, number and price entered by the user.
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = float(cost)
grocery_item = {'name':item_name,'number':quantity,'price':cost}
#Add the grocery_item to the grocery_history list using the append function
grocery_history.append(grocery_item)
#Accept input from the user asking if they have finished entering grocery items.
stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quit:\n")
# Define variable to hold grand total called 'grand_total'
grand_total = 0
#Define a 'for' loop.
for items in range(0, len(grocery_history)):
#Calculate the total cost for the grocery_item.
item_total = int(grocery_history[items].get('number')) * float(grocery_history[items].get('price'))
#Add the item_total to the grand_total
grand_total = grand_total + float(item_total)
#Output the information for the grocery item to match this example:
#2 apple @ $1.49 ea $2.98
print(grocery_history[items]['number'] + ' ' + str(grocery_history[items]['name']) + ' @ $' + str('%.2f' % grocery_history[items]['price']) + ' ea $' + str('%.2f' % item_total))
#Set the item_total equal to 0
item_total = 0
#Print the grand total
print(str('Grand total: $%.2f' % grand_total))
'''
【问题讨论】:
-
您需要创建一个minimal reproducible example,包括带有堆栈跟踪的完整错误消息,以及edit 修复formatting 的问题。
-
stacktrace 以及您的问题到底发生在哪里?
-
@wjandrea 这显然是一个最小且可重复的问题。下次有堆栈跟踪就好了。
-
你用的是python3吗?您在 print 语句中使用的 % 语法已被贬值,如果您使用格式,您将不会收到该错误。我会用一个例子来更新我的问题。
-
我还需要打印语句来打印输入到列表中的每个项目。因此,如果我以 1.49 的价格购买 1 个苹果,以 3.99 的价格购买 1 个牛奶。输出应显示“1 Apple @ 1.49 ea 1.49”“1 milk @ 3.99 ea 3.99”
标签: python