-2

I am new in python and I wanna calculate averages of grades for a student class with this:

from statistics import mean
import csv
def calculate_averages(input_file_name, output_file_name):
    with open('D:\\p3\\grades.csv', 'r') as f:
        f = csv.reader(f)
        namelist=[]
        averagelist=[]
        for row in f:
            name = row[0]
            scores = row[1:]
            scores = list(map(int, scores))
            average = mean(scores)
            namelist = name
            averagelist=average
            print(namelist, averagelist)
    yield namelist, averagelist
print(calculate_averages('namelist', 'averagelist'))

I put print n the code to see if where the problem is: when I use return it gives me :

mahtaab 15.5
Reza 14
Mahyar 15.5
Shamim 17.166666666666668
Milad 13.5
('Milad', 13.5)

when I use yield it returns:

<generator object calculate_averages at 0x0000019FB6474BA0>

what is the problem?

  • 1
    (-1) because it is unclear what your question is. Do you want to calculate an average (have a look at `numpy.mean()` ) or do you want to know the difference between `yield` and `return`? (the first creates a generator object, which calculates the results on the fly; the latter turns your code into a normal function) – max Jan 27 '20 at 07:59

2 Answers2

0

You can perform print(list(calculate_averages('namelist', 'averagelist'))) or print([i for i in calculate_averages('namelist', 'averagelist')])

0

You are printing the generator object. In order to get the list ("content" of the generator) you'll have to iterate over it, for instance by casting it to a list:

>>> def bla():
...     for i in range(10):
...         yield i
... 
>>> print(bla())
<generator object bla at 0x7f1cd1a770f8>
>>> print(list(bla()))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Have a look at this answer to understand generators: https://stackoverflow.com/a/1756156/11164958

Or at https://docs.python.org/3/glossary.html#term-generator:

A function which returns a generator iterator. It looks like a normal function except that it contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved one at a time with the next() function.

ezdazuzena
  • 6,120
  • 6
  • 41
  • 71