简体   繁体   中英

My code tells me I need to float but when I use float it tells me “Can't convert 'float' object to str implicitly ”

I don't know what I'm doing wrong, please help:(
the output expects:

Expected:

  1. Item name:
  2. Quantity purchased:
  3. Price per item:
  4. Would you like to enter another item? Type 'c' for continue or 'q' to quit:
  5. 1 milk @ $2.99 ea $2.99
  6. Grand total: $2.99

Here is my code:

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))

'''

The problem is these four lines:

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

The last line ends up undoing the previous three lines, and assigns grocery_item['price'] as a string value, not a float . This causes the eventual error of trying to print that value as a float with %.2f .

Why is that fourth line even there? Just remove it.

easy fix, just wrap grocery_history with str

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

Also, that error will be thrown when you try to add a float/int to a string, because python wants you to explicitly convert the float/int to a string first, by using the str function.

Update

Much cleaner just to use f-strings for printing:

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

Now you don't even need to use str on your floats. This only works for python >= 3.6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM