This forum is now read-only. Please use our new forums at discuss.codecademy.com.

# Having trouble with this lesson? Think your average() function is correct? Check out this post!

Many people on this lesson are having a similar problem, so I am writing a short post here to better guide people to pass this lesson.

The lesson asks you to write a function `average` which will take a list of numbers as input and return the average value in that list. Many people seem to think that they are supposed to find each student's average in this function. Thus, many people have a variation of the following code:

``````def average(student):
total = 0
for subject in student:
``````

Alternatively, some people get the average of each subject and try to return that like so:

``````def average(student):
total = 0
for subject in student:
total += sum(student[subject])/len(student[subject])
``````

Now obviously these are just two examples of many different solutions people try. But they are representative of the logic of many people. I will now try to explain where this logic is flawed.

Let us start with the `def` statement. I have noticed many people write, as I have above `def average(student)`. This tells me that people are incorrectly assuming that `average` will be passed a dictionary/student and/or that this function should return a student's average. Neither of these are the case. The correct `def` statement looks something like `def average(list_of_numbers)`. `average` will be passed a `list` of numbers, not a `dict` or student.

Other errors stem from similarly faulty logic, and by misunderstanding what the lesson is asking you to do. This lesson is asking you to make a general function that will function anywhere and in any context in which we need to find an average value in a list of numbers. In a later lesson, you will use this function to find the grade average of each student. But for now we are making a generalized function for any situation.

Here are some valid inputs and outputs for `average()`

``````average([1]) #1.0
average([0,2]) #1.0
average([1,2]) #1.5
``````

If your code works for all three of those inputs, you should be fine.

Cheers and hope this helps!

Its not so much a problem with the logic of students as a miscommunication error on the part of the lesson writer. Misunderstanding the problem is not the same as having faulty logic. But thank you for clearing up what the lesson is asking us to do.

stgeorge about 6 years ago

I agree on this. Just take a look at Adam W.Cooper's other lessons and you will see the pattern being repeated.
The fact that so many of us have problems with his lessons, means something is definitively wrong with the way those lessons are taught.

Michael Rochlin about 6 years ago

can you provide more specific examples so we can maybe work on them?

stgeorge about 6 years ago

Can you tell me how to quote the code in this comment box?
When I add a new answer I simply use the "{}" but in what should I do in here?

stgeorge about 6 years ago

From: Just average 04/05:

"Write a function called getclassaverage that takes your student list as input to compute the average of your entire class."

What student list? We have dictionaries with student names, not lists.

Michael Rochlin about 6 years ago

Sadly, you cannot format code in the Q&A comments (yet...) And good example. Thanks.

stgeorge about 6 years ago

No, thank you. For all the effort an explanation you gave us.

Brad almost 6 years ago

We did make a student list, though. It just got deleted as we completed exercises. Remember, it was students = [lloyd, alice, tyler]. I believe for this exercise we need to add the list back in so we can use it as an input for the getclassaverage function.

e4Nf3Bb5 almost 6 years ago

I would ditto stgeorge's initial comment. I was moving along just fine through the lessons until hitting the Cooper series. I think there are two problems with some of the lessons - ambiguous wording and a need for iterative practice with syntax. I found myself continually having to go back and reference the list and dictionary syntax examples because too much of the code is directly given to you, and then you are asked to repeat it wholesale. As to ambiguity, another sample to add to this one:
A Day at the Supermarket, section three "Shopping Trip" uses ambiguous wording ("Write a function compute_bill that takes a parameter food as input and computes your bill by looping through your food list and summing the costs of each item in the list." - what list? The groceries list? Some other 'food' list that's getting added in? What's the point of the grocery list otherwise? In implementation it ends up making very little difference,yes, but it's that kind of wording that pops up in other places as well where the teachers intentions are a bit vague or the phrases don't match directly.

word4word constantine almost 6 years ago

I agree with all the critic on Cooper's lessons. following the lessons of weinstein or others was perfekt but when doing cooper's
its alsways results in totaly unneccessary murder of time.
e4Nf3Bb5 and stgeorge found the best words - i encountered the same problems. beeing able to look up examples of right solutions instead of searching in this forum would be great.

andy gray almost 6 years ago

I agree with the comments above

elizan almost 6 years ago

I agree that some of the directions are vague and miscommunicate what the lesson actually wants. I never even finished the "Shopping Trip" because it would not work no matter what I did, even using the code others said worked for them. I asked friends who know python and they saw nothing wrong with my code, so I just moved on.
Clarifying the directions might be a good idea.

MC almost 6 years ago

I also agree

Diego J.B. over 5 years ago

I dont think it is a miscommunication error. It says to define a function that returns sum(x) / len(x) BUT Python needs to know that the result is a float, so the hint tells us how to make it: return float(sum(x)) / len(x)

William Lee over 5 years ago

I receive an error that the average function doesn't return a float, but it does. I ran my code in IDLE and it is returning a float. Any suggestions?

William Lee over 5 years ago

Of course, I'm also getting the correct answer for test cases and a few others that I've made up.

Chris Rocco over 5 years ago

What worked for me is where you initially set the total variable to 0, set it to 0.0 instead

Jared Stensland over 5 years ago

Thanks Chris! I had this same problem and your comment fixed it

CryptoCoinSolutions over 5 years ago

I see in the instructions: "write a function average that takes a list of numbers as the parameter lst (for list)"

If I follow the instructions:

def average(1st)

I'm going to totally ignore this. Again, the architect of a program is the first point of failure.

michael about 5 years ago

since i don't see a way to upvote comments, i would like to echo the sentiments regarding the lessons by Adam Cooper. i find the instructions to be worded in an unnecessarily confusing manner, and the inconsistencies in the code i've written being replaced / modified only adds to the confusion, as it breaks any continuity of thought as i (try to) progress.

agrabloj almost 5 years ago

my thoughts exactly

Dan McFarland almost 5 years ago

I also agree.

Joseph Denton almost 5 years ago

I often find myself coming here and having to find the answer because of how confusing the lesson can be. It's counter productive and I barely learn anything by doing so. I get the basics, come to completely baffling point in the lesson with no idea how to proceed and then have to come to the Q&A forum for help. The "hints" are also something to be desired, they provide no insight into what common problems might be.

harry93rose almost 5 years ago

I completely agree, this is a difficult enough process without the questions being delivered in riddles.

pancakerz over 4 years ago

Speak for yourselves. The average function was easy enough to figure out if you just read the instructions rather than try to write it with preconceived assumptions.

Matheen Ali over 4 years ago

def average(listofnumbers):
return sum(listofnumbers)/len(listofnumbers)

followed by function calls would suffice , since we are passing a list to the function

jufranzoi over 4 years ago

def avarage(numbers):
total=sum(numbers)
total=float(total)

this is what the text tells you to do but i still get an error ...

CptJHarkness over 4 years ago

I agree. The instructions are a list of 5 things to do to while the actual task only takes 3 steps. Many of us are seeing it the way it says just like jufranzoi pointed out. For it to be logical it would need to be instructed more like 1.Define a function called average with an argument of numbers.

1. steps 2, 3, and 4 can be placed here with some minor editing
2. Return the result. That would make much more sense logically. When you tell me to store something in a var called total then to alter it then to alter it again I'm going to end up with total in the script more than one time. No offense the the instructors because I really appreciate the fact that I can learn all this for free and from home but it seems like we skipped alot of basics, and since this is a basics course.....yeah.

Dat Mee over 4 years ago

Definitely concur, there are more than a few issues like this I've seen in the instructions thus far.

Jeffrey George over 4 years ago

The instructions in "Student Becomes the Teacher 8/9: Part of the Whole" are deeply confusing, and almost caused me to give up on the entire Python course at Codecademy. To begin: the sentence "You can expect STUDENTS to be a list containing your three students" does not mean the same thing to a beginner as "Create a list called STUDENTS, containing lloyd, alice, and tyler," but that is what the author intends for us to do. Next, he refers to a CLASS list, which seems to mean the STUDENTS list he never quite told you to create, under a different name, but "class" is a reserved term in Python, for declaring classes, so naming your list of students "class" won't work. And he never suggests putting in PRINT commands to actually see what your code does - though that's the only source of mission-accomplished satisfaction we're going to get out of these simple programs. And as other commenters have mentioned, there is way too little practice with list and dictionary syntax before you are expected to have it memorized, and to double back and refer to examples prior lessons in Codecademy requires difficult navigation and lots of "Open link in new tab" so you don't lose your place in the current lesson.
I've done a lot of Codecademy lessons and courses, but this is the first I've encountered that frustrated me nearly to the point of quitting. If I hadn't found the advice in the Q&A forum, I would have abandoned Codecademy's Python course with this lesson.

Lucy Carrick over 4 years ago

I just looked at this and it had 193 votes on it. Read through and it was amazing, so i voted too. :)

Diego Villena over 4 years ago

There needs to be a serious review of Adam Cooper's work. I've gone through the HTML/CSS track, JS track, and most of Python with few problems. I get here and it is nothing but cognitive dissonance, poorly worded instructions, shoddy hints if there were any, and endless frustration trying to use material I haven't had enough practice with. Thank DOG for google and these forums, otherwise I would have quit.

90 over 4 years ago

I did think there was something wrong with how some of the lessons were worded. For everyone's sakes, I would hope that all these errors are corrected to prevent so much confusion.

TheNikodilay_54f391499113cb18ff00551 about 4 years ago

Well Connor, I think you forget that you wouldn't even have this free source of information about coding, if it wasn't for Adam Cooper

Lucy Carrick about 4 years ago

Connor, you need to lighten up a bit. You have been able to code this far and now you decide to call Adam Cooper names. What's the point? To be honest, the only reason why you dislike Adam is because you can't figure it out. This is not Adam's fault. Other people have been able to pass this, so you can as well. Stop being such a negative dishearten person.

positiveprogrammer about 4 years ago

I got through the lesson just fine. The only problem is that he failed to give clear concise instructions. Other students got through it because they copied someones source..

90 about 4 years ago

I'd actually consider myself guilty of that...

455nefer about 4 years ago

First off, just to be cynical, he's the teacher, not us. He should be teaching us, not ignoring us as we try to teach him.
Idea: why not email a survey form about each lesson for feedback once you complete it?

astarrh about 4 years ago

Some people have no respect

Shane Stout almost 4 years ago

has nothing to do with respect, the lesson writer admittedly throws us under the bus and asks us to do things that we're still(obviously) not comfortable with by telling us outright that they've been holding our hands and are no longer going to do so. to be honest, i started struggling with my comprehension of the lessons shortly after the grocery shopping....i've been going back over the lessons several times to try and understand what the teacher is asking for, i didn't get it until today.

Sam almost 4 years ago

@Shane Stout exactly ^^^

GangstaCoder almost 4 years ago

ditto

Bex almost 4 years ago

It was not clear from the instructions and it became marginally clearer with this elaboration. Only when I studied other people's code below it made real sense to me.

Fredrik over 3 years ago

I agree with all of the above. Some of the instructions need to be rewritten. If a few students don't understand the instructions, then it's a problem with the students. If a lot, or even most, of the students don't understand, then it's a problem with the instructions.

Brian Stillwell over 3 years ago

I couldn't agree less... I am appreciative that the lesson wasn't spelled out, such that all I had to do was cut and paste. With the current lesson, I believe I now have a much better understanding. Seeing how to do something incorrectly allows the student to see the problem from many different angles, which adds to their base knowledge.

BobGears over 3 years ago

If the instructions were perfect, we wouldn't even be having this conversation. "Food" can't come out of nowhere.

### hi, there. here is my code, you can try, it works

``````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]
}

def average(numbers):
total = float(sum(numbers))

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])

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

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

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

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

Antonio HP about 5 years ago

Hi, thanks, it works, I finally did, but I really I don't understand how it works because this code is similar to mine

Tae Keun Lee about 5 years ago

Thank you very much :)

Geoffrey Ayap almost 5 years ago

thanks so much

Mutembei almost 5 years ago

Thanks a lot. I had done everything I could but got stuck on the very last line. Yours shed a large photon of light on that, thanks again.

arsalanj123 almost 5 years ago

Thanks

pmporter almost 5 years ago

Thanks! I got the correct answer, but used the wrong approach. I explicitly named the students in function:

print getclassaverage([alice, lloyd, tyler])
print getlettergrade(getclassaverage([lloyd, alice, tyler]))

...rather than creating a list: students = [lloyd, alice, tyler]

I was going to try that approach next (honest)..your solution made that moot...

Thanks again.

doctor_boy almost 5 years ago

Thanks!

Akin Okon almost 5 years ago

I was stuck at this point for up to a day, but after seeing the way you defined your getclassaverage function, realized it was all in the instructions, just not clear enough.
Thanks for helping with this. Now I can proceed. :-)

Sweta Shaw almost 5 years ago

thanks a lot..i was stuck here for a day...finally i can understand now.. :

yebuoy almost 5 years ago

it worked! thanks

aj unknow almost 5 years ago

can someone PLEASE EXPLAIN, what python is doing from the SECOND DEF,
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])

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

can someone please explain why he/she uses student as the parameter, I mean I don't see a list or a variable called student.

Andrew L almost 5 years ago

The variable student is first created in the def function line. The variable is created to be used only inside the function. The variable can be anything you want. The student variable is used in the three average calculations for homework, quizzes, and tests. When you call the function with the parameter lloyd with get_average(lloyd), it assigns lloyd to the variable student inside the function. Everywhere that the variable student is found within the function is replaced with lloyd. Please let me know if this makes sense.

aj unknow almost 5 years ago

cheers andrew m8 that is a much clear

frank1701a almost 5 years ago

Thank You, Thank You! I was stuck on this for some time. I think though there is an error in the compiler here, at one point I reset the code and ran it to submit (with nothing done for 8/9) and I was getting the same error about alice not being a str or int. I had to log out of codeacademy come back in and I submitted an empty 8/9 and then it told me I had to define the function.

Nathaniel Musial almost 5 years ago

I had a similar approach bet was writting "student in students" instead of "item in students". Somehow this had a confliction with a previous variable assignment maybe? One thing: there seems to be a disagreement on where in this code to place the students = ["""] list. After the dictionaries, withing the last definition or at the end outside of the definition?

ceebs almost 5 years ago

Thank you for this. I was pulling my hair out on the last step of this one. I had apparently missed the step asking me to make the list "students" somewhere. When I created this list used a different list name and it kept spitting out errors despite the console output being right. I change the list name and update the final print commands with the new list name and it passes me.

clearwaters over 4 years ago

A big thank you for the help... it was a confusing journey to the next level.

Yalama over 4 years ago

i am sorry people but for me it doent work..... i did the same

Ryan Mohan over 4 years ago

works perfect, the part i was missing in the getclassaverage() function was the:
return AVERAGE(results)
return results
which gave me a list of each student's average instead of just 1 number for the whole class. misunderstood directions on this step of the lesson

Rashid Malik over 4 years ago

Yea, this works

Luis over 4 years ago

This way works:

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

but this also worked for me:

hw = homework * .10
qzs = quizzes * .30
tst = tests * .60
return hw + qzs + tst
its more simplified

patrascual over 4 years ago

Thanks!

femke11 over 4 years ago

thank you so much!!

tradefutures over 4 years ago

you know more than the instructor. Thank you very much for the clarification!

minhwf_545a3e809c4e9d9968003f54_dele over 4 years ago

Oh thanks so much! I get stuck there and cannot explain why

Kit Rothwell over 4 years ago

Thanks, although I was getting the correct result in the interpreter, it didn't like the way I had gotten it!

Need For Speed over 4 years ago

you are literally a legend

Need For Speed over 4 years ago

votes for u. :)

Igor over 4 years ago

I dont get why I need variables (homework etc.) ?!

LegoBatmanMaster over 4 years ago

YOU ARE... DA BEST.

LegoBatmanMaster over 4 years ago

YYYYYYYAAAAAAASSSSSSS!!!!!!!

Adam Rutkowski over 4 years ago

Great, but why define variables in get_average function if you don't use them later?

manndaw11 over 4 years ago

in get_average function:
you said:
return 0.1 * average(student["homework"]) + 0.3 * average(student["quizzes"]) + 0.6 * average(student["tests"])

you already set: average(student["homework"])
to the variable homework

so it is more efficient to return .1*homework

Cindy Conley Taylor over 4 years ago

I have been trying to get this to work for hours. Thank you so much for posting your results!!

meetthecool shah over 4 years ago

thnak you
working..:)

Slava over 4 years ago

Oh, finally, thank you!

nav over 4 years ago

thanks!!!

Siri Sadashiva over 4 years ago

thank you!!

Adam over 4 years ago

thanks

Diego Villena over 4 years ago

Can anyone explain why I need an empty results list? results = []? I was just told to put it in, and don't know why I'd ever use it.

Robb Rayfield over 4 years ago

Thanks..I did not have my average function coded correctly. When I looked at the average function mathatically it made sense.

Ethan Colby-Witanek over 4 years ago

Diego Villena, you append different forms of data to the results list, so when you call the new average() function, it'll work on all of the items in the results list.

Daniel Olsen over 4 years ago

Hallelujah! Several days of blood sweat and tears and now I finally have an answer. I'll have to look at this code to see where I was flawed but I'm glad I can finally continue with the course now.

viresh92 over 4 years ago

thenx dear

ALE ALE ALE ALEJANDRO about 4 years ago

Thank you, I can go to bed now.

thank you...:)

Nikolay Tanev about 4 years ago

o my god! Same as mine and i searched the mistake arround 2 hours! it was the last return positioned 1 tab to the right! DAMN! :D

j_mazolenyyahoo.com about 4 years ago

Thank you

Kane Bazuka about 4 years ago

thank you))
it works

Gareth Knights about 4 years ago

Ha that return in getclassaverage caught me out too. Moved it out of the for loop and it all worked, Thanks

Brian Blanchard about 4 years ago

you did well but this part "return 0.1 * average(student["homework"]) + 0.3 * average(student["quizzes"]) + 0.6 * average(student["tests"])" needs to be revised. Think for a moment.. You set those values equal to variables named homework, quizzes, and tests. Essentially you stored them in a variable for no reason because in your return you typed the contents of the variables you initialized. The code is functional but it does not meet the conceptual parameters. its should just look like this "def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return (homework * .10 + quizzes * .30 + tests * .60)"

Lata Peng about 4 years ago

Thanks.this solved my problem.

Rishabh Sahrawat about 4 years ago

last line was creating error, now it got resloved. Thanks man (y) :)

AriThereYet about 4 years ago

Reducing redundancy, 一只特立独行的猫 in your code you could simply remove the homework, quizzes, tests variable and leave the return statement, it will give the result. And Brian Blanchard, his answer is perfect but you don't need parenthesis around your return statement.

ElenaR Buhus about 4 years ago

Yes indeed, it works! It seems that the get_average() function - was the problem in my case, so my version looked like this:

ef get_average(student):

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

Richard Smith about 4 years ago

thakyou :) saved me ALOT of time

орест муха about 4 years ago

Change:
return 0.1 * average(student["homework"]) + 0.3 * averag \

Abhinandanudupa about 4 years ago

Thank you a lot you helped me through out the chapter!!!!!:)

RowanStewart about 4 years ago

Hi guys, thought this might help:
works for me :)
def average(numbers):
total = sum(numbers)
total = float(total)
total = total/len(numbers)

budf almost 4 years ago

Thank you!!!! Nice work.

smyles21 almost 4 years ago

not sure what they problem is but I get the same result as your code which is 83.8666667 and have tried both your code and mine and I get this error message. " Oops, try again. getclassaverage([alice]) returned 85.6875 instead of 91.15 as expected"

So neither of these amounts correspond to the result 83.66667. Anyone got any suggestions?

Pinzonc almost 4 years ago

why don't you do print average(getclassaverage(students))

Jeremiah Stanley almost 4 years ago

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])

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

You calculate these values twice, once in your declarations, and again when you return.

Aaron Castrejon almost 4 years ago

My problem was forgetting to summate the totals. That was it.

Monika almost 4 years ago

Thanks for this code!! I got confused at the last part, and I don't think I could have progressed past this without being able to see your answer and compare it to mine. On another note, once I'd figured out my code error I had another persistent problem where it was giving me a wrong average. Turns out the last line was indented one too many times, haha. Don't forget to double-check your indents people!

Yumei Leventhal almost 4 years ago

Thanks! So glad to get past this idiotic lesson!

aomcastor almost 4 years ago

Man, I just got confused after many functions defined, lol.

He almost 4 years ago

Thank you for your post! I have one question about below code:
return 0.1 * average(student["homework"]) + 0.3 * average(student["quizzes"]) + 0.6 * average(student["tests"])

As you have stored the value into homework, quizzes and tests, why can't you use them directly in this code?

I hope I am clear with my question, thank you.

Fred444 almost 4 years ago

Yes, He, that is right, you just need 'return 0.1 * homework....'

Vaish almost 4 years ago

I tried using
average = getclassaverage(students)
print average
but it gives an error , why ?

Corey Gumbs over 3 years ago

I used :
def get_average(student):
homework = average(student["homework"]) * 0.1
quizzes = average(student["quizzes"]) * 0.30
tests = average(student["tests"]) * 0.60
return homework + quizzes + tests

and it worked.

just seemed like cleaner code and less lines used.

Ihaveafork over 3 years ago

return 0.1 * homework + 0.3 * quizzes + 0.6 * tests ----this is what i used as i had already saved all the averages in variables i felt no need to write them out all over again

esraaelkady over 3 years ago

thank you soooo much

is it just me or does this guy love to throw in completely new concepts and not explain them at all?

Paul Lukitsch over 5 years ago

well... I don't know about you, but we all have Google.... and I am not trying to be a dick... but if you really want to learn Python, then read the lesson, and then google things you don't get... even if there are some differences between 2.7 and version 3, you are doing yourself a far greater service by a little extracurricular reading/researching.

JB820901 about 5 years ago

^^ this guy, I like this guy ^^

Jeff van Geete almost 5 years ago

^^seconded

lumogas over 4 years ago

Yes, extracurricular activity helps, yes, looking stuff up on google helps too, but having exercises explained clearly makes it possible for us to follow them. "Free and useful" is to me, better than "Free and opaque"

455nefer about 4 years ago

Indeed. This is the third time I have had to look something up HERE. These guys ought to be helping us work through the problems. Step. By. Step.

AriThereYet about 4 years ago

My biggest pet peeve is when the hints say EXACTLY the same thing as the example text, that irks me because clearly I need the hint because I didn't comprehend the above text. Other than that, I just go with the flow and try to see if I can catch on.

I feel like having to look around to fix my code is helping me remember the missing pieces better! I love Codecademy. These lessons have convinced me that I want to go back to school for computer science.

aribilow about 4 years ago

I personally find this and the last set of tutorials to be utterly mystifying. Even when, through hours of trial and error, I manage to pass an exercise, I do so having gained little or no comprehension of the intended concepts and it is only through trial and error that I gain some tertiary new knowledge of how python works.

I'm up to exercise 6/9 I have almost no understanding of defining functions, their limitations and structural specifics (i.e. sometimes I can print values out of them and sometimes I can't and I have no clue why) and even less of an understanding of the interrelationship between them and lists/dictionaries let alone the actual ability to call specific values from them and extract useful information modularly... in other words, following a list of specific yet vague instructions != understanding.

papasmf almost 4 years ago

I will help you Ari! I got stuck on this too! Yer pal -JF

papasmf almost 4 years ago

haha

papasmf almost 4 years ago

crazy that i saw yer comment!

yes it did...!

What confuse me in this exercice is the fact that student dictionaries are at the beginning of the code so we just assume that the average function must be applied to students. It is wrong indeed but maybe change a little bit the instructions to make things more clear or remove the dictionaries from the first exercice are they are not relevant to the requirement ?

Slym about 6 years ago

Yeah, definitely! The instructions should be rewritten!

SheriBoBerry over 5 years ago

This entire section is SO much easier to follow than the last one. For me, the problem is STILL figuring out the right way to work with dictionaries and lists. I was never clear on when and how to use the key and when and how to use the value. If people are trying to use counting in these exercises, it's probably because counting was never clearly explained.

As for me, this is the first section where I was able to "think like a programmer." I understand that, if I want to use averages in my code, unless this is built into Python (like min(), max(), and abs()) I will ALWAYS have to start by writing the function myself. Maybe that's what Michael means when he writes "faulty logic".

Tom Holdstock over 5 years ago

I agree, the previous exercise was awfully difficult to follow. It seemed to make a HUGE leap in presuming our understanding of new concepts and instantly expected us to not only know how to use the new concepts but to combine them too. It has really slowed down my progress.

JB820901 about 5 years ago

I have been stuck on these past two lessons for like two weeks! I am on the verge of giving up but I want to use python possibly to control an arduino. These lessons help me understand preexisting code which allows me to roughly modify for my spare components which I have. For me personally, this is just such a new concept that there is going to be a learning curve. The instructions should be a little clearer and more user friendly but on the same token nothing easy in this world is worth while...

Patricia Fonseca over 3 years ago

I completely agree!! Sometimes it's not clear what we have to do

`````` 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]
}
#
def average(lst):
return float(sum(lst))/len(lst)
#
def get_average(student):
# homework is 10%,quizzes are 30%,tests are 60%
wtAvg=0
wtAvg=average(student["homework"])*0.1\
+average(student["quizzes"])*0.3\
+average(student["tests"])*0.6
return wtAvg
# get weighted avg
print str(lloyd["name"])+" has avg. of: "\
+str(get_average(lloyd))
print str(alice["name"])+" has avg. of: "\
+str(get_average(alice))
print str(tyler["name"])+" has avg. of: "\
+str(get_average(tyler))
``````

yan long about 5 years ago

It doesn't work!

Goran B about 5 years ago

i can assure you it does. suggestion ... get Sublime Text 3, or 2 > create a python project ... add code to project, as is above, build and voila. if running on a mac you may or may not have to put the shabang or #!usr/bin/python ... and if on windows you need to get an interpreter installed. good luck ... else use the browser interpreter :)

Brownbaseball about 4 years ago

THANK YOU!!!!!!!! I tried like 50 different ways and couldn't get it!

Almis Peter Salcius over 3 years ago

Thanks for the lead Goran, your work helped me a great deal. I found the specification odd and difficult to understand.

Almis Peter Salcius over 3 years ago

I was attempting do this with a for or while loop indexing the list of students because I had been taught in ancient times that doing the calculations in the output section of the program was a bad idea for some reason.

## Finally cracked this one:

``````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]
}

classroom = [lloyd, alice, tyler]

#
def average(x):
return float(sum(x))/len(x)

#
def get_average(student):
result = 0
result = average(student['homework']) * 0.1\
+ average(student['quizzes']) * 0.3\
+ average(student['tests']) * 0.6
return result

#
def get_class_average(avgs):
totalAvg = []
for x in avgs:
studentAvg = get_average(x)
totalAvg.append(studentAvg)
return average(totalAvg)

get_class_average(classroom)
``````

Kunal Patel about 5 years ago

thanks it works

arramsri over 4 years ago

thanks....it helped me

Jen Hodges over 4 years ago

Thanks. This helped me. :)

opap over 4 years ago

two days, same error. Tried everything.
Oops, try again. getclassaverage([alice, lloyd]) returned 91.15 instead of 85.85 as expected

virago750cc91 about 4 years ago

opap, I have the answer to you error, you get that error when the " return average(results)" is indented too far, it should be indented one less than the "results.append(whateveryounamed_it)"

Kane Bazuka about 4 years ago

thx you )

Ribhav Thakur about 4 years ago

Says Return out of function on line 49 but there is no line 49

Crono Mante almost 4 years ago

Thanks, I couldn't figure out why it didn't work, then... indentation... doh!

Niraj Hirachan almost 4 years ago

thanks mate..

GangstaCoder almost 4 years ago

That's clean code there

Ryan Ricketts almost 4 years ago

I love you comenters! Crono I'm with you. Stupid indentations!

fikri.firman over 3 years ago

thanks for this, i have been struggling with 8/9 part for several days. i guess the instructions need to be revised.

Almis Peter Salcius over 3 years ago

That is very efficient code indeed! Nice work.

For my part, I wrote like this :-p

``````def average(l):
return sum(l) / len(l)
``````

Nicholas Teeple about 6 years ago

Thanks a lot for this one. My average function got me through that lesson, but then turned out to be broken in the Sending a Letter function.

Hoàng Đd almost 6 years ago

.look easy :))

Anna Kutyrina almost 6 years ago

Nope, did not work :(

Michael Rochlin almost 6 years ago

As it shouldn't. This will return an integer when the correct average should be a float

the Great almost 6 years ago

What is a float? I don't recall learning this...

DocOnCA over 5 years ago

An "integer" is a whole number (i.e. 1), a "float" is a number with a decimal (i.e. 3.14). The subject was introduced back in 1.3 (Python Syntax > Data Types)

Chris Clasby over 5 years ago

That's not a good description of a float, since it could just as easily describe a decimal, which is distinct. A float is an imprecise decimal; it allows it to be rounded after a certain number of decimal places.

Justin Ardoin over 5 years ago

I would also like to point out that I do not recall float() specifically being introduced anywhere. Floats were indeed mentioned in lesson one, but specifically defining a float, even when going back and reviewing, I still don't see it. Had to google it.

Tom Holdstock over 5 years ago

Can anyone help out with the different styles of brackets please? When do we use the different ones? I think I get it for creating variables, lists and dictionaries but recalling them back is a bit more difficult.

I was using [] in this average function as I wanted it to work through the whole dictionary but here I see I should be using ()

Thanks

Cawarnold over 5 years ago

[] is for lists,
{} is for dictionaries.

Chetan over 5 years ago

i write the same... didn't work lol

Silvijus Abrambaltazar almost 5 years ago

Ok the answer above is correct. Although it took me some time to get the idea.
Generally you really need to read the assignment. Which turns uot ti be a problem, this asks you to write a general function. And i was looking for a way to calculate the score of every student:

{def average(numbers):
total=0
total=sum(numbers)+total
total=float(total)
total=total/len(numbers)

def average(lst):
return float(sum(lst))/len(lst)

This works.

Jennifer Basalone over 5 years ago

not for me :(

J David Hester over 5 years ago

It did for me...don't forget the TWO closing brackets before the /

Alexander Surmenidi over 5 years ago

huh, works

Conor O'Brien over 5 years ago

works fine just don't forget to indent the return statement

teddyrose almost 5 years ago

mine keeps on saying "get_average not defined"

``````average([1,2])
``````

won't return 1.5,

``````average([1.0,2.0])
``````

will return correctly on this code:

``````def average(x):
return sum(x)/len(x)
``````

Douglas Kohn almost 6 years ago

I get the same thing here
average([1,2[)
only returns 1.

Michael Rochlin almost 6 years ago

It's because of integer division. The instructions should now better explain that...

SheriBoBerry over 5 years ago

I'm a little confused about this. When writing the function that returns students' weighted averages, can I use .1 or .3, or does it have to be 0.1 or 0.3? I noticed that some people used 0.10 or 0.30. Is this a matter of style, or is there a preferred notation?

Cancelor over 5 years ago

So the correct code is...

def average(x):
return float(sum(x))/len(x)

Enviy over 5 years ago

This helped a lot. I had mistakenly had everything in one set of parenthesis next to the float.

The instructions state:

"First, write a function average that returns the average value of a list filled only with numbers"

Should the function check whether the list which has been passed only contains numbers and If so, using only the knowledge we have gained from previous sections and still using sum, how do we achieve this?

Michael Rochlin almost 6 years ago

You can assume the list is all numbers.

Bruno Saraiva almost 6 years ago

i thought exactly like philuk2000, i wrote a function that was checking if the list was composed only by numbers, just to realize it wasn't needed xD

SheriBoBerry over 5 years ago

Good point, philuk. Now that's sound logic.

Matthew A over 5 years ago

I think the problem is the lesson is leading somewhere but does not give us the overview FIRST. If we knew the end result, we would probably realize the EXACT purpose of the function.

Well, I was confused until now. Thanks all for posting. Very enlightening.

Patty

can they just make a button that show us the answer?

##### 1 Comment

Matthew A over 5 years ago

EXACTLY!!! But then again forum participation would come to a halt. Maybe this is intentional.

this is the shortest code that will work that people often overlook

``````def average(lst):
return float(sum(lst))/len(lst)
``````

Jeremy Emerson over 5 years ago

Yes, you will not end up with syntax errors and get the "way to go!" at the bottom of the screen.

Glynys Thomas over 5 years ago

This was the one that finally worked for me.
def average(lst):
return float(sum(lst)) / len(lst)
I was making it more complex than it called for, trying to average each student's homework, tests, etc. The exercise is looking for a generic list averaging function.

Joe Reitman over 5 years ago

This will get the green light but it doesn't actually work in a script.

codecore about 5 years ago

it worked but am curious about @Joe Reitman comment that it doesn't actually work in a script?can it work?

###this works after i was almost giving up n I hope I wil save someone tym

def average(lst) :
avr = float(sum(lst))/len(lst)
return avr

students = [lloyd, alice, tyler]

for avg in students:
print avg['name']
print average(avg['homework'])
print average(avg['quizzes'])
print average(avg['tests'])

Little_CodeLikeJesus over 5 years ago

how old are you fridah ?

CodeLikeJesus over 5 years ago

Recruiting old sport?

Fridah Nyagu over 5 years ago

does age matter really?

CodeLikeJesus over 5 years ago

Yes, yes it does old sport .

Fridah Nyagu over 5 years ago

am in my early 20's n btw wat all abt old sport??

k, a question regarding this matter: why can't we just import the average.math function?...or something like that. maybe it's a stupid question but i must know.
thanks

##### 1 Comment

455nefer about 4 years ago

It'd math.average, and I'm not entirely certain that is a function.

1 vote

Well, I wrote the code and ended with the right answer straight away. So maybe is after all logic, or the way one see the problem and another see it another way. But I think it`s normal to be like this.

1 vote

def average(float[x]):
return sum(x) / len(x)

This allowed me to pass for some reason, but I got a syntax error. Why is that?

ArronStone_521cb9f0548c35abc900012b_ over 5 years ago

same for me man....
Do you know why????

Michael Rochlin over 5 years ago

When I run that code it doesn't pass...

Dustin Allen Hensley over 5 years ago

Houston, we have a bug.

Dustin Allen Hensley over 5 years ago

def average(x):
return float(sum(x)) / (len(x))

Michael Rochlin over 5 years ago

I'm confused... what are you submitting and what message are you getting?

Dustin Allen Hensley over 5 years ago

My first post, I passed with, but received a syntax error. I know it's not right but I'm so new to all this that I just try something until it works without knowing the rhyme or reason. I just wanted to make sure the function returned a float. So, the second average function worked for me. I really don't know why. I wish there was a little more of an explanation of why this stuff works. I've been looking all over the web and found some stuff pertaining to that, but I think it would be cool if your site contained more of it. I think understanding the mechanics of why and how the code works might demystify it, but I know that's not the site's responsibility. Anyway . . .

bartekrek over 5 years ago

Hi. I'm a noob myself but I'll try to explain. Function float() changes it's parameter value to float thus you can use it only on integer or string type variables and you were trying to use it on the list cause x you're passing to your average() function is a list of numbers.

Your second average function is wrong but works because the list in the exercise you're passing to it comprises of floats so float() function does nothing in this particular case. If it were integers it wouldn't work. int/int = int (wrong value for example 10/4=2), float/int=float (correct) int/float=float (correct)

Dustin Allen Hensley over 5 years ago

I'm confused. Why would it let me pass? What's the correct answer?

Alex Zhang about 5 years ago

I'm not sure

1 vote

sorry for the indentation, forgot to enclose the tag

1 vote

I did it this way and it works
def average(numbers):
total = 0
if len(numbers) > 0:
total = float(sum(numbers)) / len(numbers)
else:
print "No grades to average"

1 vote

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]
}

students = [lloyd, alice, tyler]

def average(numbers):
total = sum(numbers)
total = float(total)
total = float(total) / len(numbers)
print total

def get_average(student):
for student in students:
total = []
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
total = float(homework) * 0.1 + float(quizzes) * 0.3 + float(tests) * 0.6
return float(total)
print total

ERROR
Oops, try again. get_average(alice) returned 80.55 instead of the expected 91.15

Robert Paczyński about 4 years ago

Oops, try again. getaverage(alice) returned <function getaverage at 0x7f56525ea0c8> instead of the expected 91.15

José Enrique Guadiana Chong almost 4 years ago

i have the exact same problems :(

1 vote

these instructions were the most frustrating part of this section - i get trying to challenge us but some of this was almost down-right misleading. Here are my interpretations of the instructions and below is my final (successful - hooray!) code in its entirety. I added some notes here and there, I hope they help. I bolded object names for the sake of clarity. I did change the name of the initial list, the word "student(s)" was getting thrown around too much.

The images don't appear to be working too well (copying the code wasn't cooperating, so I just took screenshots) but the image URLs should take you to the PNGs. The first is just the student dictionaries. The second image is the meat of the code but I wanted to provide everything for comparison

**Edit bajilliion.0 - in 9/9 the program is specifically looking for the "students" list to see if you've done it properly. my code in the screenshots still works fine but change "roster" to "students" in lines 44, 47 and 49. my solution to 9/9 looks like this:

(line 54) print get(underscore)class(underscore)average(students)
(line 55) print get(underscore)letter(underscore)grade(get(underscore)class(underscore)average(students))

clear as mud?**

INSTRUCTIONS

1. create a list, named roster, of your student dictionaries (the ones created at the beginning of your displayed code)
2. define a function called get(underscore)class(underscore)average that accepts roster as the argument (the list you just created).
3. within this function, prepare an empty list named results
4. for each student in your roster, append your results list with the result of calling your get_average function with student as your argument.
5. outside of the "for" loop but still within your function, return the class average by using the standard average function with your results list as the argument

##### 1 Comment

455nefer about 4 years ago

Learn to add alt text. Just use

1 vote

This one is new *You are all uncodeful*

1 vote

*You are all uncodeful*

Jeffry Dale Suter over 3 years ago

LOL!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Jeffry Dale Suter over 3 years ago

you made reall laugh. Thanks ever so much!

1 vote

Super simple, just think about the basic math involved and what you've learned so far. There's nothing here that hasn't been covered. Here's one example working solution:

``````def average(lst):
return float(sum(lst)) / len(lst)

def get_average(student):
grades = ['homework', 'quizzes', 'tests']

weights = { 'homework': .1, 'quizzes': .3, 'tests': .6 }

weighted_average = 0

for key in student:
if key in grades:
weighted_average += float(average(student[key]) * weights[key])

return weighted_average

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def get_class_average(students):
student_averages = [get_average(student) for student in students]
return average(student_averages)
``````

Carlo DiCelico over 3 years ago

Remember, no one said you can't create an additional data set to help you solve the problem!

Jeffry Dale Suter over 3 years ago

wowza. didn't realize one could use a for next loop like you have just shown/shared when programming using the Python programming language. Reminds of of the BASIC that was imbedded in a Commodore64 i learned 28 years ago and over the years have subsequently forgotton alot of due to simply not using that particular version of BASIC. Reminds me of the saying " The more things change, the more they stay the same if you can mentally process the essense of what I am communicating to you via this text entry.
My first thought upon reading the intructors instructions was "How convoluted can you get?. Here i will clarify: his instructions: Define a function called getclassaverage that has one argument..."students+. You can expect students to be a list containing your three students.{all right sir, it's not i CAN expect. It's I SHOULD and WILL expect because the contents of this singular lesson only has a list that only contains a listing of 3 students.
First, make an empty list called results....OK....actually, What he wrote firstly is the instruction to define a function..right? Then the instructor of this course writes. "First, make and empty bla bla. Well partner... that is actually second in your psuedo-list of instructive material.Linear thought processing and then expressing such linear thought via (in this case English) should be..well...linear. You sir,(not you Carlo) are a source of confusion and I will in the future be using some high-level (haha) common sense when reading you "instructive reading material"

So is the following code fine?

``````def average(person):
return sum(person) / len(person)

students = [lloyd, alice, tyler]

for avg in students:
print avg['name']
print average(avg['homework'])
print average(avg['quizzes'])
print average(avg['tests'])
``````

Eduardo Aranguiz Olea almost 6 years ago

i did almost the same, but i think its not right

Satyam Shukla over 5 years ago

PLz try dis

avg = 0
def average(list):
avg = sum(list)/((len(list)) * 1.0)
return avg

kp_569 over 5 years ago

This does not work.

Omar Zaffar Khan over 5 years ago

Thanks, it worked!

Omar Zaffar Khan over 5 years ago

Hi,kp_569 you just have to arrange it in the correct order.

455nefer about 4 years ago

how do you take the average of a name?!

It took me a while but i finally got it ..
Issues i faced:
1) if you do not have return in ur get average function it gives you an error saying
"Oops, try again! Your code looks a bit off--it threw a "a float is required" error. Check the Hint if you need help!"
which is not very clear as to what the real issue is

2) I got another error saying i was trying to concatenate int to string when i tried to use a for loop with the dictionary object in get average function..so i just passed the static values for students list
like student['homework']

``````def average(lst):
num=len(lst)
total=0
for item in lst:
total=total+item
return float(total)/num
``````

def get_average(student):
total=0.0
total=average(student['homework'])0.1+average(student['quizzes'])0.3+average(student['tests'])*0.6

Dustin Allen Hensley over 5 years ago

Thank you much.

Patrícia Rousseau over 5 years ago

thnks :)

Patrícia Rousseau over 5 years ago

your get_average doesn't work :(

I know what the teacher is expecting now. The exercise is looking at the use of

``````def average(*args)
``````

args will allow even one argument or as many arguments that the function call is using.

Try it out. It worked for me.

Why this code does not work?

``````def average(lst):
som = sum(lst)
lon = len(lst)
return float(som) / len(lon)
``````
##### 1 Comment

Paul Lukitsch over 5 years ago

You don't need to use "len" twice. You use it to define lon, then you use "len(lon)" in your return. You already defined "lon" as len(lst).

``````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]
}

def average(lst):
total = sum(lst)
divide = len(lst)
average = float(total)/divide
print float(average)

average([100,92,98,100.0])
``````

Here is my solution after a hard time understanding the instructions :

``````def average(lst) :
avr = float(sum(lst))/len(lst)
return avr
``````

print average([0])
print average([0,2])
print average([0,1])

##### 1 Comment

Missy Lektro over 5 years ago

wow, finally got it to work. thanks. i've been struggling a bit w/ this one

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]
}

def average(lst):
val = 0.0
for a in lst:
val += a
val /= len(lst)
return float(val)

def get_average(dct):
return (average(dct['homework']) * 0.10) + (average(dct['quizzes']) * 0.30) + (average(dct['tests']) * 0.60)

#print 'tyler average: %s' % getaverage(tyler)
#print 'alice average: %s' % get
average(alice)
#print 'lloyd average: %s' % get_average(lloyd)

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]
}

def average(lst):
length = len(lst)
avg = 0
for value in lst:
avg += lst[value]/ length
return float(avg)

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

``````return wavg
``````

""" hii all, i was trying to complete this challenge... but i am having trouble getting through with this ......
Above is the code that i have written.... its giving me an error..Oops, try again. Does your get_average function take exactly one parameter (a student)? Your code threw a "list indices must be integers, not float" error.

I cant figure out the problem..Can you please help me with this...

thanks

harman

Harman Singh Sandhu over 5 years ago

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]
}

def average(lst):
length = len(lst)
avg = 0
avg += float(sum(lst))/ length
return avg

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

``````return wavg
``````

""" hi guys... i solved this by editing the average(lst) function....... but i am still confused .....i need to review whole of the concept again..

jackywolfson over 5 years ago

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

jackywolfson over 5 years ago

wavg = 0.0 ,which means the format of float is essential here. The code above had made me pass.

def average(lst):
return float(sum(lst))/len(lst)
def get_average(student):
return (average(student['homework']) * 1/10) + (average(student['quizzes']) * 3/10) + (average(student['tests']) * 6/10)

finally it works.

thanks all. Finally I learned the code. I just put the parentheses and the code worked

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

def average(numbers):
total = sum(numbers)
float(total)
print total /len(numbers)

this worked..

def average(numbers):
total = 0
total = sum(numbers)
total = float(total) / len(numbers)

7/9 - 9/9 Am I doing this right? I'm not sure about the last line.

``````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"
else:
return "F"

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

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

Megan Herrington about 5 years ago

I think the last return line on the getclassaverage function is indented one too many times as it stands...

zerny about 5 years ago

Sorry for the typo, it was supposed to be indented once only. Could you verify the last print line? Much appreciated.

def average(numbers):
sum(numbers)
total=sum(numbers)
total=float(total)
total=total/len(numbers)

this worked for me, it was the 1st try even :D

def average(numbers):
total = sum(numbers)
total = float(total)

This is the code that got me past this headache maker
code
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]
}
students = [lloyd, alice, tyler]

def average(numbers):
total = sum(numbers)
total = float(total)

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

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

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

Just wondering, my code in part 7/9 seems to work (I get the "Way to Go! Next Lesson -->" message) but all I see printed in the output is "None". Has anyone's code been printing out the actual results? I want to be sure that my code actually worked.

##### 1 Comment

Bittu Philip over 4 years ago

Hi Shaita,
Put print before the function
like

# It's an really easy exercise, look what I did:

def average(l):
return float(reduce(lambda x, y: x + y,l)) / len(l)

##### 1 Comment

455nefer about 4 years ago

well, only if you knew to use reduce(lambda x, y: such-and-such)

Hi all

I've been running the code below-

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]
}

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"])
average = (0.1 * homework) + (0.3 * quizzes) + (0.6 * tests)
return (0.1 * homework) + (0.3 * quizzes) + (0.6 * tests)

if score >= 90:
return "A"
elif score >= 80 and score <= 89:
return "B"
elif score >= 70 and score <= 79:
return "C"
elif score >= 60 and score <= 69:
return "D"
elif score < 60:
return "F"

``````    print get_letter_grade(get_average(lloyd))
``````

def getclassaverage(student):
students = [lloyd, alice, tyler]
results = []
for item in students:
studentavg = get_average(item)
results.append(studentavg)
return average(results)

``````    print get_class_average(students)
``````

And I'm getting the following error-

Oops, try again. getclassaverage([alice]) resulted in an error: local variable 'average' referenced before assignment

I keep on going round in circles. Can somebody please help?!

Nathaniel Musial almost 5 years ago

I think it might be in def get_average where you assigned the local variable average = (0.1 * homework) + (0.3 * quizzes) + (0.6 * tests)?

Nathaniel Musial almost 5 years ago

is there a confliction of using a local variable with the same name as a function?

Bittu Philip over 4 years ago

Hi Scott ,

Kindly remove
average = (0.1 * homework) + (0.3 * quizzes) + (0.6 * tests) from your code
and it will work fine . :)

can someone please explain what the second DEF does in the code above, many thanks
def get_average(students):
homework = average(students["homework"])
quizzes = average(students["quizzes"])
tests = average(students["tests"])

``````return 0.1 * average(students["homework"]) + 0.3 * average(students["quizzes"]) + 0.6 * average(students["tests"])
``````

Hi,
could someone please explain to me why students=[lloyd,alice,tyler] and not ["lloyd","alice","tyler"]
Thanks, Femi

##### 1 Comment

FayusMaximus over 4 years ago

Because they aren't strings. They are dictionaries and therefore you don't use quotation marks with them. You're creating a list with three different dictionaries. (= I hope this helps you.

``````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]
}

def average(numbers):
total = sum(numbers)
total = float(total)
result = total / len(numbers)
return result

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

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

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

students = [lloyd, alice, tyler]
print get_class_average(students)
print get_letter_grade(get_average(students)) **#line 56**
``````

It works, but I get these errors:

``````Traceback (most recent call last):
File "python", line 56, in <module>
File "python", line 28, in get_average
TypeError: list indices must be integers, not str
``````
##### 1 Comment

duanyz over 4 years ago

"print getlettergrade(getaverage(students))" shuould be
"print get

The problem is human interpretation versus syntax (x). Its unnatural for humans,or any organism likely to accept difference. I guess, the first thing you need to accept is that you don't before you can understand it.

Thanks for the posts though, it made me aware of a problem i refused to accept.

def average(numbers):
total = 0.0
for x in numbers:
total += x

``````avg = total/len(numbers)
return avg
``````

this worked for me, tried to understand most of it here, but didnt.

If it helps after not understanding anything here, I just re-read the assignment.

think about it, you only want the average returned of any list.

Hi All,

You can try my code this is working fine for me

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]
}

##Functions
def average(numbers):
total= sum(numbers)
#print total
total = float(total)
#print total
total = total/len(numbers)
#print total

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])

``````#Since Homework is 10% so we convert it into 10/100= 0.1
return 0.1*homework+0.3*quizzes+0.6*tests
``````

print get_average(lloyd)

if score>=90:
return "A"
elif score>=80:
return "B"
elif score>=70:
return "C"
elif score>=60:
return "D"
else:
return "F"

my solution:

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

This worked for me:

``````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]
}

def average(numbers):
total = sum(numbers)
total = float(total)

def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
homework = homework * .10
quizzes = quizzes * .30
tests = tests * .60
dingle = homework + quizzes + tests
return dingle

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

students = [lloyd, alice, tyler]

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

print get_class_average(students)
score = get_class_average(students)
``````

So what messed me up on this part of the course is that the concept of variable 'scope' and namespace for functions are not really mentioned in the tutorial up to now and if you are not careful and you use a variable name that is the same as a 'function' name - oh say you use the variable name 'average' and have a function called 'average' then it will mess things up completely. Make sure no variables have the same names as functions. That worked for me.

This worked for me:

def average(student):
return float(sum(student)) / len(student)

# be sure to indent return line

##### 1 Comment

jaxelrod almost 4 years ago

I indent the return line and it gives me an 'unexpected indent' error!!!! Then when I unindent it gives me an 'outside of function' error.

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]
}

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

if score >= 90:
return "A"
elif score >=80:
return "B"
elif score >=70:
return "C"
elif score>=60:
return "D"
else:
return "F"

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

This code worked for me:

def average(numbers):
sum(numbers)
total = sum(numbers)
return float(total) / len(numbers)

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]
}

# return result

def average(lst) :
avr = float(sum(lst))/len(lst)
return avr
def getaverage(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return 0.1 * homework + 0.3 * quizzes + \
0.6 * tests
students = [lloyd, alice, tyler]
def get
if score >= 90 :
return "A"
elif score >= 80 :
return "B"
elif score >= 70 :
return "C"
elif score >= 60 :
return "D"
else :
return "F"
a=get
average(lloyd)
print result
def getclassaverage(students):
results=[]
for student in students:
result=get_average(student)
results.append(result)
return average(results)

``````print get_letter_grade(get_class_average(students))
``````

print getclassaverage(students)

## Why are there so many answers?!

##And none of them work! ##

This is how I wrote it:

``````def average(numbers):
total = 0
for x in numbers:
total += x
total = total/float(len(numbers))
``````

Hope this helps.

You're an ungrateful bunch. This section is hard but not impossible. Just re-read the tasks carefully and it DOES work. If I can manage it, then anyone can

Hello,

Here is my code. It works perfectly fine, you may have a look at it.

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]
}

def average(numbers):
total=sum(numbers)
total=float(total)
total=total/len(numbers)

def get_average(student):
homework=average(student["homework"])
quizzes=average(student["quizzes"])
tests=average(student["tests"])

``````return (0.1*homework)+(0.3*quizzes)+(0.6*tests)
``````

if score>=90:
return "A"
elif score>=80 and score=70 and score=60 and score<70:
return "D"
else:
return "F"

#Just for testing purpose

def getclassaverage(students):
results=[]
for item in students:
studentAvg = get_average(item)
results.append(studentAvg)
return average(results)

students = [lloyd,alice,tyler]
print getclassaverage(students)

I created an empty list oust side of the getclassaverage function and couldn't move on but when I erased that and created the empty list inside the function It worked perfectly. Just in case anyone is pulling their hair out with the same problem.

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]
}

def average(numbers):
total = sum(numbers)
average = float(total)/len(numbers)
return average
def getaverage(student):
homework = student["homework"]
quizzes = student["quizzes"]
tests = student["tests"]
return 0.1average(homework)+0.3average(quizzes)+0.6*average(tests)
def get
if score>=90 :
return "A"
elif 90>score>=80 :
return "B"
elif 80>score>=70 :
return "C"
elif 70>score>=60 :
return "D"
else :
return "F"
x = get
average(lloyd)
print y
def getclassaverage(students):
results = []
for student in students:
result = getaverage(student)
results.append(result)
return average(results)
students = [lloyd,alice,tyler]
print get
classaverage(students)
print get

Hi All,

First time contributing! I noticed a lot of complex answers given here and confusion over what was asked, so I just wanted to post my code and explain the logic in the hope it might help someone else:

#per 01, I define the function average(numbers)
def average(numbers):
#per 02&03, I create var total using sum() and float()
total = float(sum(numbers))
#per 04 I create a new var result for average of total
result = total / len(numbers)
#per 05 I return that result
return result

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]
}

def average(numbers):
total = sum(numbers)
total = float(total)

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

if score >= 90: return "A"
elif score >= 80: return "B"
elif score >= 70: return "C"
elif score >= 60: return "D"
else: return "F"

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

students = [lloyd, alice, tyler]

print getclassaverage(students)

#That should be the correct question
#Plz Notice that the indent may cause some problem

that's mine:

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]
}

def average(numbers):
total = sum(numbers)
total = float(total)
def get_average(student):
homework = average(student["homework"])
quizzes = average(student["quizzes"])
tests = average(student["tests"])
return (homework * 0.1) + (quizzes * 0.3) + (tests * 0.6)

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

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

``````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]
}

def average(numbers):
total = sum(numbers)
total = float(total)
result = total / len(numbers)
return result

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

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

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

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

I will always remember about indentations!
I will always remember about indentations!
I will always remember about indentations!
I will always remember about indentations!
I will always remember about indentations!

for student in students:
print student["name"]
print student["homework"]
print student["quizzes"]
print student["tests"]

def average(numbers):
total = sum(numbers)
total = float(total)

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

if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"