[Tutor] Help with return results statement.

Steven D'Aprano steve at pearwood.info
Tue Oct 20 08:25:54 EDT 2015


Hi Vusa, and welcome.


On Tue, Oct 20, 2015 at 01:29:59PM +0200, Vusa Moyo wrote:
> Hi there. My script is as follows,

[...]
> def get_class_average(students):
>     results = []
>     for a in students:
>         b = int(get_average(a))
>         results.append([b])
>         return results


I'm not sure why you are getting 0, but the get_class_average function 
is definitely wrong. The problem is in the structure of the function. 
You have the *return* inside the for-loop, which means that only the 
first student will ever be processed. As soon as the function gets to 
the "return results" line, it will exit the for-loop leaving everything 
else unprocessed.

You need to unindent the return so it looks like this:

def get_class_average(students):
    results = []
    for a in students:
        b = int(get_average(a))
        results.append([b])
    return results

Now the for-loop will run all the way to the end, and the function will 
only return at the very end.

I'm also not entirely sure about the [b] argument to append. Are you 
sure it is supposed to be [b]? That will be appending a *list* 
consisting of a single value. I think you want:

        results.append(b)

without the square brackets. Why don't you try both and see the 
difference?

-- 
Steve


More information about the Tutor mailing list