Python Forum

Full Version: Definitions in User-Created Functions and For Loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I'm going through an introductory book on Python and there's a section in which the author presents some code to demonstrate the concept of nested dictionaries. I understand everything that is going on in the code and I've run the code myself in Python 3.8.7 and confirmed that it works. But it's re-raising a few basic questions in my mind regarding the syntax of how user-defined functions and for loops work in Python that I've had when looking at other Python code.

Here is the code that I'm referring to:

allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
             'Bob': {'ham sandwiches': 3, 'apples': 2},
             'Carol': {'cups': 3, 'apple pies': 1}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():
        numBrought = numBrought + v.get(item, 0)
    return numBrought

print('Number of things being brought:')
print(' - Apples         ' + str(totalBrought(allGuests, 'apples')))
print(' - Cups           ' + str(totalBrought(allGuests, 'cups')))
print(' - Cakes          ' + str(totalBrought(allGuests, 'cakes')))
print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
print(' - Apple Pies     ' + str(totalBrought(allGuests, 'apple pies')))
Question 1: On line five, I understand that the totalBrought function is being defined in relation to "guests" and "item." But guests and item have not been defined yet in the code (at least as far as I can tell). So how does Python know what they are referring to?

Question 2: I understand what the for loop is doing here in terms of iterating through the key-value pairs in the dictionary. But as far as I can tell, neither "k," "v," "guests," nor "item" (or "items") have been defined yet in the code. So again, how does Python know what they are referring to?

Thanks so much in advance for any help.
Regarding question one: the syntax is just how you specify what the inputs to the function are (what are called it's arguments or parameters). Remember that lines 5-9 define the function: what it's called, its inputs and what it does (the body). The names for the parameters are just being defined there and then they can be used in the body of the function. When you call the function, you must supply values for those parameters.
And the for loop defines k and v as the key and value in guests.items. So you would not define them ahead of the loop - if you did the values would be overwritten each iteration of the for loop.

Another way of saying what ndc85430 points out is that the arguments in the function definition are just placeholders for the actual values you will pass in to the function. There is a nice youtube from PyCon by Ned Batchelder about Python names and name spaces. Helps a lot when trying to figure out whether Python passes arguments to a function by value or by reference, etc. Worth the 25 minutes.
Thanks ndc85430 and jefsummers. I found the Ned Batchelder video and plan on watching it.

A few other questions: So instead of using k and v in the for loop we could use whatever other letters we wanted (such as a and b, x and y, y and z, etc.) as long as we are internally consistent (for example, by ensuring the second letter is also used in the get code on the next line)? Is the only requirement that whatever we use be letters?

Thanks again!
Avoid using single letters for variable names where possible - choose meaningful names that tell you what the variables are for. Doing so makes the code more readable.
Again agree with ndc85430 but would add - avoid using keywords as well. So instead of k and v might use guest and product. Depending on what you are writing code in, keywords typically will come up colored which should be your clue that you are accidentally using one for your variable name. You want to avoid
print = 'Hello there'
print(print)
Output:
TypeError Traceback (most recent call last) <ipython-input-1-f0fdfc704b1e> in <module>() 1 print = 'Hello there' ----> 2 print(print) TypeError: 'str' object is not callable
Yeah, it's a shame Python lets you do that.