1

I wanted to make a program that takes the inventory as a dictionary data and prints it with the total at the bottom.

# inventory.py 
stuff = {"coal":42,"dagger":1,"iron":           
20,"torch":2}
total_items = 0 

def display_inventory(inventory): 
       for k,v in inventory.items(): 
              print(k,v) 
              global total_items 
              total_items = total_items + v

print("\n")
print("Total: " + str(total_items))

I want to add colon to output like: coal: 42 dagger: 2 How do i do this?

Edit: We call the function using the variable "stuff"

ardasevinc
  • 13
  • 4

2 Answers2

2

You can use string format, code looks elegant more details is here https://www.programiz.com/python-programming/methods/string/format

# inventory.py 
stuff = {"coal":42,"dagger":1,"iron":           
20,"torch":2}
total_items = 0 

def display_inventory(inventory): 
       for k,v in inventory.items(): 
              print("{}:{}".format(k,v)) 
              global total_items 
              total_items = total_items + v

print("\n")
print("Total: " + str(total_items))
nerding_it
  • 704
  • 7
  • 17
0
# inventory.py 
stuff = {"coal":42,"dagger":1,"iron":           
20,"torch":2}
total_items = 0 

def display_inventory(inventory): 
    for k,v in stuff.items(): 
        print(k+':',v,end=' ') # (k+': '+v,end =' ')
        global total_items 
        total_items = total_items  + v 

    print("\n")
    print("Total: " + str(total_items))

display_inventory(stuff)
'''
output
coal: 42 dagger: 1 iron: 20 torch: 2 

Total: 65
'''
Tanmay jain
  • 814
  • 6
  • 11
  • Thanks i didn't know i could use print() like k+':' and then the second parameter. Anyway thanks, will accept this answer. – ardasevinc Aug 17 '18 at 07:46
  • @ardasevinc yes that is called string concatenation :) [link](https://stackoverflow.com/questions/12169839/which-is-the-preferred-way-to-concatenate-a-string-in-python) – Tanmay jain Aug 17 '18 at 07:48
  • other answer seemed more elegant. – ardasevinc Aug 17 '18 at 07:54
  • @ardasevinc no issues, glad you found what you were looking for :) but remember about string concatenation you can use that at many other place – Tanmay jain Aug 17 '18 at 07:56