Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Nested formatting?
#1
Sorry for another thread, but this is my favorite place to get help.
The problem is below.

Provided is a list of data about a store’s inventory where each item in the list represents the name of an item, how much is in stock, and how much it costs. Print out each item in the list with the same formatting, using the .format method (not string concatenation). For example, the first print statement should read: 'The store has 12 shoes, each for 29.99 USD.'

Not sure where I went wrong. Assigning names to items?
inventory = ["shoes, 12, 29.99", "shirts, 20, 9.99", "sweatpants, 25, 15.00", "scarves, 13, 7.75"]

#my attempt follows
for thing in inventory:
    product = thing[0]
    amount = thing[1]
    cost = thing[2]
    print("The store has {} {}, each for {} USD.".format(amount, product, cost))
Output:
The store has h s, each for o USD. The store has h s, each for i USD. The store has w s, each for e USD. The store has c s, each for a USD.
Reply
#2
Because the print is outside of the loop only the last instance of amount, product, cost is printed.
the last item in inventory is "scarves, 13, 7.75",
inside the loop amount, product, cost are asigned the value of the index 0,1 and 2 of the string so s, c and a.
To correct this you need to split thing to seperate the 3 values.
thing = "shoes, 12, 29.99"
print(thing.split(', '))
Output:
['shoes', '12', '29.99']
also move the print into the end of the loop.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020