Home>

This is a basic question, but please tell me about functions.
As an example, I'll put the code, which may be a little confusing.

fruits = {"apple": 100, "grape": 150}
def kudamono (fruit):
    print (fruit ["apple"])
kudamono (fruits)
↓↓↓↓↓↓↓↓↓↓↓
100


It puts the prices of apples and grapes in a dictionary called fruits, defines a function called kudamono, and calls it at the end.
If there is a code with such a composition, when it is executed, it will be output normally as "100", but I do not understand the idea of ​​fruit ["apple"] on the third line.
Specifically, I don't know what it is, I think that it will not pull the key of the dictionary unless it is print (fruits ["apple"]), and since the name of the dictionary is fruits, I can not specify it as fruit I feel like.
Even if the argument is set to fruit in def kudamono (fruit): on the second line, it seems that it has nothing to do with the dictionary (or rather, if you put your favorite character (a or b) here instead of fruit) I have confirmed that it can be executed normally).
I would like you to explain why print (fruit ["apple"]) can output normally (please make it as easy as possible (sweat)).
(Maybe it's because I don't understand the arguments of the function well, so I'm sorry there)

  • Answer # 1

    Function definitiondef kudamono (fruit)Iskudamono (something)When called byfruit = somethingAnd substitute.
    Therefore, laterkudamono (fruits)When called asfruit = fruitsIs implicitly called, and you can then manipulate fruits with the variable fruit. This fruit can be executed normally with a and b as well.