TypeError when trying to call functions in run

Viewed 44

Edit; Thanks everyone! It's working now!

I'm trying to make a program that reads a csv file and calculates using that data. I have my csv_reader function and my average_temperature function working independently but I don't understand how to call them in the run() function.

I understand what the error means but I'm completely lost on how to fix it, but here's the closest I've gotten. It ends up with this error and then below it is the code:

Traceback (most recent call last):
  File "main.py", line 100, in <module>
    run()
  File "main.py", line 82, in run
    avgfile = average_temperature("Temperatures.csv", input)
  File "main.py", line 40, in average_temperature
    if filter in row[date_index]:
TypeError: 'in <string>' requires string as left operand, not builtin_function_or_method

Code:

import csv


date_index = 0
temp_index = 2


def csv_reader(file):
    lst = []
    with open("Temperatures.csv", 'r') as weather_file:
        weather_reader = csv.reader(weather_file)
        first_row = True
        for row in weather_reader:
            if first_row:
                first_row = False
                continue
            lst.append(row)
    return lst

def average_temperature(weather, filter):
    thefile = csv_reader("Temperatures.csv")
    sum = 0
    len = 0
    for row in thefile:
        if filter in row[date_index]:
            sum += float(row[temp_index])
            len += 1
    avg = sum / len
    return avg

def run():
    thefile = csv_reader("Temperatures.csv")
    avgfile = average_temperature("Temperatures.csv", input)

    print("{}".format(avgfile))

    return

if __name__ == '__main__':
    run()
1 Answers

The error is because input is the name of a built-in function. I think what you need to do is call it and get a value to pass as the filter parameter to your average_temperature() function something like this:

def run():
    date_filter = input('What date? ')  # Get value from user.
    thefile = csv_reader("Temperatures.csv")
    avgfile = average_temperature("Temperatures.csv", date_filter)

    print("{}".format(avgfile))

    return

Related