Hey this is a demo to show some of my classmates an intro to python and coding. The code below should be able to take a list like [0,1]
and if run using the average
function would return 0.5. When run using a list the function below returns the error 'list' object has no attribute 'len'
. How would I get this function to work without removing the len()
function
def average(lst):
total = 0
for item in lst:
total += item
averageGrade= total / lst.len()
return averageGrade
How would I also get it to return a float rather than an integer
Change the line
averageGrade= total / lst.len()
to
averageGrade= total / len(lst)
Refer the python docs for the built-in len. The built-in len calculates the number of items in a sequence. As list is a sequence, the built-in can work on it.
The reason it fails with the error 'list' object has no attribute 'len'
, because, list
data type does not have any method named len
. Refer the python docs for list
Another important aspect is you are doing an integer division. In Python 2.7 (which I assume from your comments), unlike Python 3, returns an integer if both operands are integer.
Change the line
total = 0.0
to convert one of your operand of the divisor to float.
or by changing
averageGrade= total / lst.len()
to:
averageGrade= total / lst.__len__()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With