【问题标题】:My code tells me I need to float but when I use float it tells me "Can't convert 'float' object to str implicitly "我的代码告诉我我需要浮动但是当我使用浮动时它告诉我“无法将'float'对象隐式转换为str”
【发布时间】:2019-09-29 02:22:14
【问题描述】:

我不知道我做错了什么,请帮助:(
输出预期:

预期:

  1. 项目名称:
  2. 购买数量:
  3. 单件价格:
  4. 您要输入其他项目吗?输入“c”表示继续,输入“q”表示退出:
  5. 1 牛奶 @ 2.99 美元 2.99 美元
  6. 总计: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


【解决方案1】:

问题出在这四行:

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

最后一行结束了前三行,并将grocery_item['price'] 分配为 string 值,而不是 float。这会导致尝试将该值打印为带有%.2f 的浮点数的最终错误。

为什么第四行还在那里?只需将其删除。

【讨论】:

    【解决方案2】:

    轻松解决,只需将grocery_historystr 包装起来

    print(str(grocery_history[items]['number']) + ' ' + str(grocery_history[items]['name']) + ' @ $' + str('%.2f' % grocery_history[items]['price']) + ' ea $' + str('%.2f' % item_total)) 
    

    此外,当您尝试将 float/int 添加到字符串时,会引发该错误,因为 python 希望您首先显式使用 @ 将 float/int 转换为字符串987654324@函数。

    更新

    使用 f-strings 打印更简洁:

    print(f"{grocery_history[items]['number']} {grocery_history[items]['name']}  @ $ {grocery_history[items]['price']}  ea ${item_total}") 
    

    现在你甚至不需要在你的花车上使用str。这仅适用于 python >= 3.6

    【讨论】:

    • 当我应用该修复程序时,它说需要一个浮点数“回溯(最近一次调用最后一次):文件“grocery_list.py”,第 48 行,在 print(str(grocery_history[items] ['number']) + ' ' + str(grocery_history[items]['name']) + '@$' + str('%.2f' %grocery_history[items]['price']) + 'ea $ ' + str('%.2f' % item_total)) TypeError: a float is required"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多