Function Calling Slicing

#1

``````Traceback (most recent call last):
File "python", line 66, in <module>
TypeError: 'float' object has no attribute '__getitem__'``````

I was trying to make it slice the float so that its not so long when printed. But it gave me that error and I'm not sure how to make it slice it to be 83.86 for the class average instead of 83.8666666667.

``````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'])

return average(student['homework']) * .1 + \
average(student['quizzes']) * .3 + \
average(student['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 get_class_average(students):
results = []
for s in students:
x = get_average(s)
results.append(x)
return average(results)

lloyd_average = get_average(lloyd)
alice_average = get_average(alice)
tyler_average = get_average(tyler)

print """Lloyd\'s grade in the class is %s percent.

Alice\'s grade in the class is %s percent.

Tyler\'s grade in the class is %s percent.
""" % (lloyd_average, alice_average, tyler_average)

class_average = get_class_average(students)[0:4]
print """The class average is %s percent.""" % (get_class_average(students))``````

#2

You can't really slice the numbers. But you can convert number to a string (`str` function):

``class_average = str(get_class_average(students))[0:5]``

But it would be much better to simply round up this value to two decimal places:

``class_average = round(get_class_average(students), 2)``

#3

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