Just Weight and See (Undefined error)


@ionatan @appylpye

The following code outputs

get_average(alice) raised the following error: ‘float’ object is not iterable.<

But why?

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

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


sum() can calculate the sum of an iterable (like a list), if you just have numbers you need to add together, you can use +


Sorry… I could not get you… a brief explanation pls…


do you have an an iterable (a data type which can be looped over, for example a list)?

sum() is a built-in function which can calculate the sum of an iterable, but an iterable only. It can’t add integers/floats together, so should you use sum() here?


@stetim94 what about the following edit?

def average(numbers):
  total = 0
  for number in numbers:
  	total += number
  length = len(numbers)
  return total/length

or which other option do I have to run this code error-free?


yes, because in the previous exercise you used an iterable (list) as parameter. In this exercise, your parameter is not an iterable. sum() only works for an iterable.

you can’t just assume a built-in function works for all data types. That is an assumption you can not make.

If you don’t know how a built-in function works, the python documentation is a good place to find out


why would you change the average function? The average function is fine, there you can use sum() given the parameter of sum (numbers) is a list, the problem is in get_average, where you try to use sum() and the parameter is not an iterable/list


Oh… Thanks a lot… I got it… It’s so silly that I didn’t notice it even once…
Thanks a lot again…
I needed to use comma(,) instead of plus(+) in the sum() function. The fact is I did not look at this statement ever. I was just thinking of the sum() in average() :expressionless:


or just not use sum() at all in get_average, and add the numbers together using +

why bother to convert the numbers to an iterable so you can use sum()? Its additional steps which are not needed


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