Parameter or argument in function

46 views Asked by At

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

There are 1 answers

0
void On

It seems that you are a bit confused about how arguments/parameters are passed.

Take a look at this example.

def my_func(copy_var):
    #copy_var=1
    print(copy_var)
    print(hex(id(copy_var)))
var=1000
print(var)
print(hex(id(var)))
print("----------------------")
my_func(var)

output:

1000
0x7efd723d9b70
----------------------
1000
0x7efd723d9b70

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.

def my_func(copy_var):
    print(copy_var)
var=1000
print(var)
print("------------------------")
my_func(var)
print(copy_var)

output:

1000
------------------------
1000
Traceback (most recent call last):
  File "/home/mr/argfunc.py", line 7, in <module>
    print(copy_var)
NameError: name 'copy_var' is not defined

Now as simple as i can put,

def my_func(copy_var):
    print(copy_var)
    print(var)
var=1000
print(var)
my_func(var)

Both copy_var and var have 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

add_to_inventory(stuff, dragon_loot)

dragon_loot is given to function as added_items so both point to same address having same values. But only difference is their scopes are different.

dragon_loot --> added_items