Search code examples
pythonfunctionpylint

Python more functions


I would like to separate this into several smaller functions in order to make it look tidier and easier to read, but whenever I try this I cannot seem to get it to work. Any help would be appreciated.

At the moment my code looks like this

def print_monthly_totals (input_csv_filename):
    data = open(input_csv_filename).readlines()
    print('Rainfall totals for each month')
    for line in data:
        columns = line.split(',')
        month = int(columns[0])
        num_days = int(columns[1])
        total_rainfall = 0
        for col in columns[2 : 2 + num_days]:
            total_rainfall += float(col)

        print('Month {:2}: {:.1f}'.format(month, total_rainfall))

I would like it to look more like the example below

def print_monthly_totals (input_csv_filename):
    data = open(input_csv_filename).readlines()
    print('Rainfall totals for each month')
def SOMETHING(SOMETHING):    #The SOMETHING is just a filler
    for line in data:
        columns = line.split(',')
        month = int(columns[0])
        num_days = int(columns[1])
        total_rainfall = 0
def SOMETHING(SOMETHING):    #The SOMETHING is just a filler
        for col in columns[2 : 2 + num_days]:
            total_rainfall += float(col)

        print('Month {:2}: {:.1f}'.format(month, total_rainfall))

Solution

  • You could shorten up your function like this:

    def print_monthly_totals (input_csv_filename):
        data = open(input_csv_filename).readlines()
        print('Rainfall totals for each month')
        for line in data:
            columns = line.split(',')
            month, num_days = int(columns[0]), int(columns[1])
            daily_rainfalls = [float(x) for x in columns[2:2+num_days]]
            total_rainfall = sum(daily_rainfalls)
    
            print('Month {:2}: {:.1f}'.format(month, total_rainfall))
    

    Or split it up into two functions like this:

    def line_to_rainfall(line):
        cols = line.split(",")
        month, num_days = int(cols[0]), int(cols[1])
        daily_rainfalls = [float(x) for x in cols[2:2+num_days]]
        return month, daily_rainfalls
    
    
    def print_monthly_totals (input_csv_filename):
        data = open(input_csv_filename).readlines()
        print('Rainfall totals for each month')
        for line in data:
            month, daily_rainfalls = line_to_rainfall(line)
            total_rainfall = sum(daily_rainfalls)
            print('Month {:2}: {:.1f}'.format(month, total_rainfall))