Python test Medium calculator returen error 'list' object does not have attribute 'len'

Hey, this is a demo to show some of my classmates an introduction to python and coding. In the code below, a list should be given, for example [0,1] , and if the start using the average function returns 0.5. When launched using the list, the function below returns the error 'list' object has no attribute 'len' . How do I get this function to work without deleting the len() function

 def average(lst): total = 0 for item in lst: total += item averageGrade= total / lst.len() return averageGrade 

How could I make it return a float, not an integer

+7
python
source share
1 answer

Change the line. Refer to python docs for inline len . The built-in len calculates the number of elements in a sequence. Since a list is a sequence, an inline can work on it.

 averageGrade= total / lst.len() 

to

 averageGrade= total / len(lst) 

The reason it fails with the error 'list' object has no attribute 'len' is because the list data type has no method named len . Refer to python docs for list

Another important aspect is that you do integer division. In Python 2.7 (which I assume from your comments), unlike Python 3, returns an integer if both operands are integers.

Change the line

 total = 0.0 

to convert one of your operands from divisor to float.

+13
source share

All Articles