Files
coding-mentor-agent/kb/python-course-kb-practical-python/wiki/exercises/6-6-using-a-generator-to-produce-data.md
T

1.6 KiB

id, source_exercise_id, title, section, source_path, source_repo, source_commit, student_visible_solution, has_private_solution, skip
id source_exercise_id title section source_path source_repo source_commit student_visible_solution has_private_solution skip
practical-python-6.6 6.6 Using a generator to produce data 6.2 Customizing Iteration 06_Generators/02_Customizing_iteration.md https://github.com/dabeaz-course/practical-python 93dca856b41c61a0a0f85ae334116e4c125629ea false false false

Exercise 6.6: Using a generator to produce data

Source: Practical Python Programming, 06_Generators/02_Customizing_iteration.md.

Exercise 6.6: Using a generator to produce data

If you look at the code in Exercise 6.5, the first part of the code is producing lines of data whereas the statements at the end of the while loop are consuming the data. A major feature of generator functions is that you can move all of the data production code into a reusable function.

Modify the code in Exercise 6.5 so that the file-reading is performed by a generator function follow(filename). Make it so the following code works:

>>> for line in follow('Data/stocklog.csv'):
          print(line, end='')

... Should see lines of output produced here ...

Modify the stock ticker code so that it looks like this:

if __name__ == '__main__':
    for line in follow('Data/stocklog.csv'):
        fields = line.split(',')
        name = fields[0].strip('"')
        price = float(fields[1])
        change = float(fields[4])
        if change < 0:
            print(f'{name:>10s} {price:>10.2f} {change:>10.2f}')

关联来源