pressing ctrl+D doesn't give complete output

Viewed 51

I have the following code in python:

#!/usr/bin/python

import sys

def reducer():

    oldKey = None
    totalSales = 0

    for line in sys.stdin:
            data= line.strip().split("\t")
            if(len(data)!=2):
                    continue

            thisKey,thisSale = data

            if (oldKey and oldKey != thisKey):
                    print ("{}\t{}".format(oldKey,totalSales))
                    oldKey=thisKey
                    totalSales = 0


            oldKey = thisKey
            totalSales += float(thisSale)

    if(oldKey!=None):
            print("{}\t{}".format(oldKey,totalSales))

reducer()

When I give the input:

a       1
a       2
a       3
b       4
b       5
b       6
c       1
c       2

and press Ctrl+D here

I get output:

a       6.0
b       15.0

I expected the output to be:

a       6.0
b       15.0
c       3.0

I am getting the full output only after I press Ctrl+D once more. Why is it so? How can I fix it?

1 Answers
Related