Some people might see this as a noob question, which I'm sure it is. I'veI've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.
Lets just take the default code that Dive Into Python uses as an example:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim",
"database":"master",
"uid":"sa",
"pwd":"secret"
}
print buildConnectionString(myParams)
How does the function buildConnectionStringbuildConnectionString
with the argument (params)(params)
know to get it'sits data from the variable myParamsmyParams
? Or params.items()params.items()
, too within the returnreturn
line? Wouldn't the argument in buildConnectionStringbuildConnectionString
need to be set as buildConnectionString(myParams)buildConnectionString(myParams)
in order for it to read properly? How can you set the variable of your data to myParamsmyParams
, but have the argument of your function be paramsparams
and have it read? How does it know to read myParamsmyParams
as paramsparams
?
And is there a reason behind not naming your variable paramsparams
, or vice versa naming your argument in your function myParamsmyParams
? It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.