8. Part of Whole, returned average as 91.15 instead of 85.85 expected


#1

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)
return float(total)/len(numbers)

def get_average(student):
return (0.1 * average(student["homework"]) + 0.3 * average(student["quizzes"]) + 0.6 * average(student["tests"]))

def get_letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
elif score <=59:
return "F"
print get_letter_grade(get_average(lloyd))

def get_class_average(students):
results = []
for student in students:
results.append(get_average(student))
return average(results)

The error I get is "Oops, try again. get_class_average([alice, lloyd]) returned 91.15 instead of 85.85 as expected"


#2

def get_class_average(students):
    results = []
    for student in students:
        results.append(get_average(student))
        return average(results)

Check the indentation of the return statement. It should be in line with the for (as in, not inside the loop body).

Edit. Tested and passes when repaired.


#3

Your a hero, your the stuff dreams are made out of


#4

Why does this only work when return is indented in this way?


#5

Python is very strict at how blocks are defined, and what scope is on them.

def fn(n):
    # function block
    m = 0
    while n > 0:
        # while block
        if n % 2 == 0:
            # if statement block
            m =+ n
    return m

See where the return lines up with the while? They are both in function block level. The variable m is scoped to that block so can be seen inside the while and the if statements.

Were we to define a variable in the while loop, the return statement at the end would not be able to see it because it has local scope and cannot be seen by its parent scope (the function block). It could however be seen inside the if block.

Again, if we define a variable in the if block, it will not be seen by either the while block or the function block. Only inside the if block where it once again has local scope.

So you see, it's very important where the return takes place. The above unrepaired example is sending the return in the first iteration of the for loop, not at the end of loop iteration.

Just for clarification, a block begins with a colon, and is prefixed with four additional spaces on the next line, as we can see above.


#6

(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)


#8

A post was split to a new topic: My code is generating error prompt