TypeError:无法将“浮动”对象隐式转换为str /购物清单

时间:2019-07-28 17:08:03

标签: python-3.x

我在将float变量合并到我的打印字符串中时遇到问题。我对编码非常陌生,需要这个问题的帮助

我尝试过在任何我知道如何转换的地方进行转换,并且在这里停留了一段时间

''' 该任务分为三个部分。 第1部分-用户输入 第2节-遍历购物清单 第3节-向控制台提供输出 '''

#Task:创建空的数据结构

grocery_item = {}

grocery_history = []

#Variable用于检查while循环条件是否满足

stop = True 

while stop == True:

接受购买的杂货商品名称的输入。

item_name =输入(“项目名称:\ n”。

输入购买的杂货数量。

数量=输入(“购买数量:\ n”)

接受杂货项目输入成本(这是每项成本)的输入。

 cost = input('Price per item:\n')

使用更新功能创建词典条目,其中包含用户输入的名称,编号和价格。

 grocery_item = {'name' : item_name, 'number' : int(quantity), 'price' : float(cost)}

使用附加函数将杂货项添加到杂货历史记录列表中

grocery_history.append(grocery_item)

接受用户的输入,询问他们是否完成输入杂货。

choice = input("Would you like to enter another item?\nType 'c' for continue or 'q' for quit:\n")
if choice == 'c':
  stop = True
else:
  stop = False

定义变量以保存总计,称为“ grand_total”

 grand_total = 0

定义一个“ for”循环。

for i in grocery_history:

计算杂货项的总费用。

item_total = grocery_item['number'] * grocery_item['price']

将item_total添加到grand_total

grand_total += item_total

输出食品杂货的信息以与此匹配

2个苹果@ $ 1.49每个$ 2.98

print(str(grocery_item['number']) + grocery_item['name'] + " @ " + str(grocery_item['price']) + " ea "+ item_total)

设置item_total等于0

item_total = 0

打印总计

print(grand_total)

我只是不断地收到这个错误 TypeError:无法将“ float”对象隐式转换为str

1 个答案:

答案 0 :(得分:0)

grocery_item = {}
grocery_history = []
stop = True 

while stop == True:
    item_name = input('Item name:\n')
    quantity = input('Quantity purchased:\n')
    cost = input('Price per item:\n')
    grocery_item = {'name' : item_name, 'number' : int(quantity), 'price' : float(cost)}
    grocery_history.append(grocery_item)
    choice = input("Would you like to enter another item?\nType 'c' for continue or 'q' for quit:\n")
    if choice == 'c':
        stop = True
    else:
        stop = False
    grand_total = 0
    for i in grocery_history:
        item_total = grocery_item['number'] * grocery_item['price']
        grand_total += item_total
        print(str(grocery_item['number']) + grocery_item['name'] + " @ " + str(grocery_item['price']) + " ea "+ str(item_total))
        item_total = 0
        print(grand_total)

,输出为:

Item name:
apple
Quantity purchased:
2
Price per item:
1.49
Would you like to enter another item?
Type 'c' for continue or 'q' for quit:
q
2apple @ 1.49 ea 2.98
2.98
相关问题