Python – Confusion regarding def function within Python

coding-stylefunctionslanguage-featurespythonsyntax

I'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 buildConnectionString with the argument (params) know to get its data from the variable myParams? Or params.items(), too within the return line? Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly? How can you set the variable of your data to myParams, but have the argument of your function be params and have it read? How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams? 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.

Best Answer

It's not about Python.

But nevertheless, to answer you straightly. Lets say you have a function:

def doSomethingWithParmas(params):
    params.doSomething()

Now you can call it later on with:

print doSomethingWithParams(myParams)

or/and

print doSomethingWithParams(yourParams)

It's how functions work, you can call it with whatever params you like, all that function cares, is that they are some kind of params that it can handle.

EDIT: A remark: I have never coded a line of Python in my life.

Related Topic