user1399037
user1399037

Reputation: 1

Python, printing things a select number of times

I'm new to coding and am having an issue with my program. I have to get sales information from a file and print it in a certain format. This is the code:

#Looping program to read file per line
for line in lines:
    # Formatting line to read later
    line = line.strip().split(',')
    year = line[0]
    year = int(year)
    month = line[1]
    month = int(month)
    day = line[2]
    day = int(day)
    linePoint = date(year, month, day)

    cost = line[3]
    cost = float(cost)

    #Finding the lines within the start and end date
    if (linePoint >= startDate) and (linePoint <= endDate):
        printcost = (cost / 100)
        printcost = int(printcost)

        print "%s.%s.%s" % (startYear, startMonth, startDay)
        print "0%s:" % printNum,  "*" * printcost

        newcost = newcost + cost
        printNum += 1

When I use the %s.%s.%s it's printing the date above the sales, I want it to print that above the other print statement once per month, and be able to increase it once the month is up. Also in the print "0%s:" % printNum, "*" * printcost statement I would like it to only print the zero for the first nine days.

Essentially my question is how in Python do I run something a certain number of times, but the number of times is dependent on the user and correlate with the date, and in order to do that the computer needs to be able to recognize the date. Sorry for the vagueness.

Upvotes: 0

Views: 178

Answers (2)

Jason Sundram
Jason Sundram

Reputation: 12524

I'm almost sure this is what you want. Note the "%02d" format specifier, which gives you the leading zero, and the check to see if the month has changed via if month != current_month.

current_month, print_num, new_cost = None, 0, 0

for line in lines:
    fields = line.strip().split(',')
    year = int(fields[0])
    month = int(fields[1])
    day = int(fields[2])
    cost = float(fields[3])

    line_date = date(year, month, day)

    #Finding the lines within the start and end date
    if startDate <= line_date <= endDate:
        if month != current_month:
            print "%s.%s.%s" % (year, month, day)
            current_month = month

        print_cost = int(cost / 100)
        print "%02d: %s" % (print_num,  "*" * print_cost)

        new_cost += cost
        print_num += 1

Upvotes: 0

John Gaines Jr.
John Gaines Jr.

Reputation: 11534

If you want the output to be '01', '02', ..., '10', '11', ... then the format you want to use is:

print "%02d" % printNum

As for printing the header out at the start of each new month (that's how I'm reading the first part of your question, you could do something like:

old_month = 0
for line in lines:
    # do stuff
    month = whatever...
    if month != old_month:
        # print header here
        old_month = month
    #rest of loop

Upvotes: 1

Related Questions