Discussion with Exercise 6/9 - How do function arguments know what to get? [spoilers]


lloyd = {
  "name": "Lloyd",
  "homework": [90.0, 97.0, 75.0, 92.0],
  "quizzes": [88.0, 40.0, 94.0],
  "tests": [75.0, 90.0]
alice = {
  "name": "Alice",
  "homework": [100.0, 92.0, 98.0, 100.0],
  "quizzes": [82.0, 83.0, 91.0],
  "tests": [89.0, 97.0]
tyler = {
  "name": "Tyler",
  "homework": [0.0, 87.0, 75.0, 22.0],
  "quizzes": [0.0, 75.0, 78.0],
  "tests": [100.0, 100.0]

# Add your function below!
def average(numbers):
  total = sum(numbers)
  total = float(total)
  return total / len(numbers)

def get_average(student):
  homework = average(student["homework"])
  quizzes = average(student["quizzes"])
  tests = average(student["tests"])
  total = homework *.1 + quizzes * .3 + tests * .6
  return total

When defining a function argument, how does Python know what to get? Ie. how does def get_average(student): know that you are referring to lloyd, alice, and tyler- it doesn’t seem as though we’ve built anything that would allow the function to ‘know’ we are referring to these dictionaries, but it appears that it does.


We, as programmers define the data flow. If it is a list, then our code should expect a list. If it is a dictionary then our code should expect a dctionary. The operative words here are, ‘our code’, Python does not ‘know’ anything.


Poor word choice on my part. My question is when we define ‘student’ in the above, what causes the code to refer back to the specific dictionaries with the names? Are we defining any previously created dictionary containing the “homework”, “quizzes”, and “tests” strings as (student) arguments? I am curious to know what would happen if we added another dictionary containing one of these three lists, but not the other two.


The following from 9/9 answered my question. I did not realize that these were defined upon calling the function, rather than in the process of creating the functions. I understand now that this is because the same function can be used again.

students = [lloyd, alice, tyler]
class_avg = get_class_average(students)
print class_avg
print get_letter_grade(class_avg)


Which is a core principle behind functions… Re-usability. Functions should be dedicated to a task, not a data object. There may be a specific requirement such as data type, but aside from that it should take inputs and work with those without any regard for what part of the program called it. Well designed functions do not interact with the world outside. They take in data, process it and return a result. Given the same data, the result will always be the same.


Excellent, thank you.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.