Python Forum
Definitions in User-Created Functions and For Loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Definitions in User-Created Functions and For Loops
#1
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.
Reply
#2
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.
BashBedlam likes this post
Reply
#3
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.
BashBedlam likes this post
Reply
#4
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!
Reply
#5
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.
Reply
#6
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
ndc85430 likes this post
Reply
#7
Yeah, it's a shame Python lets you do that.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable definitions inside loop / could be better? gugarciap 2 450 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  Passing parameters with arrays and array definitions michael_lwt 1 952 Jul-07-2022, 09:45 PM
Last Post: Larz60+
  Running scripts and location of saved interpreted user-defined classes and functions leodavinci1990 3 2,544 Aug-25-2020, 03:43 AM
Last Post: micseydel
  User functions don't work: Baldev10 7 3,188 Aug-18-2020, 08:34 PM
Last Post: deanhystad
  User defined functions inside other user defined functions WildP 1 1,955 Jan-29-2020, 04:57 PM
Last Post: Clunk_Head
  Parenthesis in User-Defined Functions giorgitsu 2 1,985 Aug-07-2019, 12:56 PM
Last Post: ThomasL
  how to work with variables changed in definitions Prof_Jar_Jar 2 2,626 Dec-16-2018, 12:04 AM
Last Post: Prof_Jar_Jar
  Why won't this user created function work? Evyeniarocks 5 3,142 Mar-29-2018, 05:20 PM
Last Post: wavic
  Accept Multiple Lines of Input into a User Created File Bragger 0 2,629 Oct-29-2017, 04:15 PM
Last Post: Bragger

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020