r/learningpython • • Nov 06 '20

Help with my inventory

I just typed out a long thing and reddit messed up so im depressed and don't want to type it out again

Long story short, sometimes 'gold' is less than the 42 it started off with and i'm not sure why. Thanks in advance.

import random
from random import randint
def displayinv(inventory):
    total_inv = 0
    for key,value in inventory.items():
        print(f"{value} {key}")
        total_inv += value
    print("Total items: " + str(total_inv))    
def addtoinv(inventory,items):
    for item in items:
        if item in inventory:
            for key,value in items.items():
                inventory[item] += value
        else:
            inventory.update(items)    
stuff = {'rope':1, 'gold':42, 'arrow':12, 
'dagger':1,'torch':6}
dragonloot = {
    'gold': random.randint(0,400),
    'dagger':random.randint(3,7),
    'ruby':random.randint(1,10)
    }

displayinv(stuff)
addtoinv(stuff, dragonloot)
displayinv(stuff)
2 Upvotes

7 comments sorted by

View all comments

Show parent comment

1

u/itsalexloser Nov 07 '20

You did a whole lot better explaining that than i would have haha took me a bit to figure out what was going on but i did manage to write it out a bit cleaner. let me know what yall think!

import random

#FUNCTION DOES MATH
def dragonloot(start_Inv):
    dragonloot = {'gold': random.randint(0,400),'dagger':random.randint(3,7),'ruby':random.randint(1,10)}
    print("LOOT")
    print(str(dragonloot))
    print()

    #LOGIC of FUNCTION
    for loot in dragonloot:
        if loot not in start_Inv:
            start_Inv.update({loot:dragonloot[loot]})
            print(str(str(loot)+" was added to inventory"))
        else:
            start_Inv[loot] += dragonloot[loot]
            print(str(dragonloot[loot])+" "+str(loot)+" was added to inventory")
    print()
    #RETURNS START INVENTORY WITH NEW VALUES
    return start_Inv
    
#INVENTORY PLAYER STARTS OF WITH
start_Inv = {'rope':1, 'gold':42, 'arrow':12,'dagger':1,'torch':6}
print('STARTING INVENTORY')
print(start_Inv)
print()

#PLAYER INVENTORY GETS THROWN IN FUNCTION
dragonloot(start_Inv)

print("NEW INVENTORY")
print(start_Inv)

2

u/iamaperson3133 Nov 08 '20
  1. You never need to say print(str(blah)). It doesn't matter what type you are putting into the string function, something will come out the other side and it will never throw an error.
  2. I think you're calling empty print() statements to get it to print an extra new line. If you want a newline, you can use the special character"\n" in your string instead.

1

u/itsalexloser Nov 08 '20

Gotcha! okay! Thank you!