gpt4 book ai didi

python - 关于简单python脚本的问题

转载 作者:行者123 更新时间:2023-11-28 19:04:16 25 4
gpt4 key购买 nike

我有一个家庭作业,要写一个简单的购物 list ,脚本应该能够:

  1. 接受用户输入的变量,例如商品的商品名称、数量和成本

  2. 使用从用户那里收集的信息,创建一个字典条目并将其添加到名为 grocery_history 的列表中

  3. 按照以下格式打印出所有输入的项目:变量→数字名称价格item_total

  4. 最后输出所有项目的成本总和

这是我的代码:

grocery_item = {}
grocery_history=[{}]
stop = 'go'
item_name = input("Item name:")
quantity = input("Quantity purchased:")
cost = input("Price per item:")
grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)

cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
while cont != 'q':
item_name = input("Item name:")
quantity = input("Quantity purchased:")
cost = input("Price per item:")
cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")


grocery_history.append(item_name)
grocery_history.append(quantity)
grocery_history.append(cost)



grand_total = []

number = grocery_history[quantity]
price = grocery_history[cost]

for grocery_history in grocery_item:
item_total = int(number)*float(price)
grand_total.append(item_total)
print(grocery_history[number][name] + "@" [price]:.2f + "ea'.format(**grocery_item)")


item_total = 0


print ("Grand total:" + str(grand_total))

在我的 number = grocery_history[quantity] price = grocery_history[cost]statement I get aKey Error 2`,我不确定为什么,这些键应该存在,但也许它们没有正确添加到列表中。任何帮助将不胜感激,如果您需要更多详细信息,请告诉我,我将对其进行编辑。

最佳答案

这是一个工作示例(解释如下):

grocery_history={'item_name':[], 'quantity':[], 'cost':[]}
cont = 'c'
while cont != 'q':
item_name = input("Item name:")
quantity = int(input("Quantity purchased:"))
cost = int(input("Price per item:"))
cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")

grocery_history['item_name'].append(item_name)
grocery_history['quantity'].append(quantity)
grocery_history['cost'].append(cost)


grand_total = 0
for i in range(len(grocery_history['item_name'])):
item_name = grocery_history['item_name'][i]
quantity = grocery_history['quantity'][i]
cost = grocery_history['cost'][i]

priceTimesQuantity = quantity * cost
grand_total = grand_total + priceTimesQuantity
message = 'Bought {} x{} (each: {}$) to a total of: {}'.format(item_name, quantity, cost, priceTimesQuantity)
print( message )

finalmessage = 'Grand Total: {}'.format(grand_total)
print(finalmessage)

  1. 我减少了你第一个循环上面的部分(考虑一下)
  2. grocery_history 现在是一个包含 3 个列表的字典。示例:
    enter image description here
  3. 我们现在用项目向下填充这些列表(append)
  4. 当用户完成后,我们再次遍历以 i 为索引的列表
    (请参阅图像左侧的小灰色数字)然后,对于每个项目,我们从列表中加载详细信息并计算总价格此外,我们将总数添加到 grand_total,这是一个数字(从零开始)与第二个循环相加。
  5. 在第二个循环完成后,我们打印最终值(总和)

在 Texts 中:"some text {}".format(var) - {}var 之后的占位符字符串

关于python - 关于简单python脚本的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com