我在将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 = 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 "+ item_total)
item_total = 0
print(grand_total)
我只是不断地收到这个错误 TypeError:无法将“ float”对象隐式转换为str
答案 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