Why inventory[dragon_loot[n]] == inventory[added_items[n]], in following codes?
def display_inventory(inventory):
print('Inventory:')
items = 0
for k, v in inventory.items():
print(str(v) + ' ' + str(k))
items += v
print('Total number of items: ' + str(items))
def add_to_inventory(inventory, added_items):
for n in range(len(added_items)):
inventory.setdefault(added_items[n], 0)
inventory[dragon_loot[n]] += 1 ----> # or 'inventory[added_items[n]] += 1' the same effect
return display_inventory(inventory)
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragon_loot = ['rope', 'gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
add_to_inventory(stuff, dragon_loot)
It seems that you are a bit confused about how arguments/parameters are passed.
Take a look at this example.
output:
Note : hex(id(variable)) just returns the address of the memory of the value stored in a variable
Notice how the addresses are same. Means both the local variable (which is local only to the function) and global variable point to same address.
However the scope of copy_var is only within that function. When you try to access it outside. Error is thrown.
Take a look at this one.
output:
Now as simple as i can put,
Both
copy_varandvarhave the same value pointing to same address. But one's cope is within the function while other is global.Notice how they both (copy_var and var) print the same value
1000. That's exactly what's happening in your confusing code.So coming back to your, since in this line
dragon_lootis given to function asadded_itemsso both point to same address having same values. But only difference is their scopes are different.dragon_loot-->added_items