0

I'm not sure what I'm doing wrong here, but for some reason, every time I correct the code or try to get it to iterate through the CSV file, it gives me a float object not iterable. If someone could give me some pointers on how to iterate through the array of floats, I would be grateful.

    import pickle
    from weatherreading import WeatherReading
    
    
    def valid_temperature(temperature : float):
        return -40 < temperature < 85
    
    def valid_pressure(pressure : float):
        return 300 < pressure < 1200
    
    
    def valid_humidity(humidity : float):
        return 20 < humidity < 80 
    
    
    def valid_reading(temperature : float, pressure : float, humidity : float):
        return valid_temperature(temperature) and valid_pressure(pressure) and valid_humidity(humidity)
    
    
    def get_readings_from_file(filename : str, skip_first_line : bool) -> list[WeatherReading]:

   
    with open(filename, "r") as file: 
        # Note that we're stating that the list is a List of WeatherReading instances
        all_readings : list[WeatherReading] = [] 
        first_line = True

        for line in file: 
            if skip_first_line and first_line:
                first_line = False
                continue 

            split = line.split(",") #split the data at every comma
            temperature = float(split[0]) #First column
            pressure = float(split[1]) #second column
            humidity = float(split[2]) #third column

            def max_temperature():
                maxTemp = []
                for i in temperature:
                    maxTemp.append(i)
                return max(maxTemp)

            def min_pressure():
                minPress = []
                for i in pressure:
                    minPress.append(float[i])
                return min(minPress)

            def max_humidity():
                maxHum = []
                for i in humidity:
                    maxHum.append(float[i])
                return max(maxHum)

            if valid_reading(max_temperature(), min_pressure(), max_humidity()):
                reading = WeatherReading(max_temperature(), min_pressure(), max_humidity())
                all_readings.append(reading)
    
        return all_readings


if __name__ == "__main__":

    filename = input("Enter CSV file name: ")

    all_readings = get_readings_from_file(filename, True)

    # Echo the input to output.
    print("Your readings:")
    for reading in all_readings:
        print(f"\tTemp: {reading.temperature}", end="")
        print(f"\tPressure: {reading.pressure}", end="")
        print(f"\tHumidity: {reading.humidity}")

    pickle_demo = open('pickle_demo.bin', 'wb')
    pickle.dump(all_readings, pickle_demo)
    pickle_demo.close()
7
  • in the max_temperature and min_pressure functions you are trying to loop over floats which are not iterable. for i in temperature <-- temperature is a float. You can't do a for loop over a float Commented Aug 29, 2022 at 4:29
  • Yes I know, my question is how do I iterate through them even though they are floats. Commented Aug 29, 2022 at 4:30
  • No, I’m trying to find the min/max values in the CSV file, for temp I’m finding the max, pressure min and humidity max Commented Aug 29, 2022 at 4:34
  • Ok... so what you want to do is to put all the values of each column into a list and then take the max, right? Commented Aug 29, 2022 at 4:35
  • To do it that way, you should create those list in advance (before looping through the rows) and append each value. Not to iterate through each value (which is a single element). But there're modules specialized in that work, like csv or pandas Commented Aug 29, 2022 at 4:39

1 Answer 1

1

What you can do is collect the values after you split them from the csv file line, into their own lists, and then perform your calculations after they have all been collected.

For example:

import pickle
from weatherreading import WeatherReading

def valid_temperature(temperature : float):
    return -40 < temperature < 85

def valid_pressure(pressure : float):
    return 300 < pressure < 1200

def valid_humidity(humidity : float):
    return 20 < humidity < 80

def valid_reading(temperature : float, pressure : float, humidity : float):
    return valid_temperature(temperature) and valid_pressure(pressure) and valid_humidity(humidity)

def get_readings_from_file(filename : str, skip_first_line : bool) -> list:
    with open(filename, "r") as file:
        all_readings = []
        temps, pressures, humidities = [], [], []
        first_line = True
        for line in file:
            if skip_first_line and first_line:
                first_line = False
                continue
            # split the line and convert to floats
            temp, press, humid = map(float, line.split(","))
            temps.append(temp)        # append each value to its own
            pressures.append(press)   # list collection
            humidities.append(humid)
        maxTemp = max(temps)          # max and min values 
        minPress = min(pressures)     
        maxHums = max(humidities)
        if valid_reading(maxTemp, minPress,  maxHums):
            reading = WeatherReading(maxTemp, minPress, maxHums)
            all_readings.append(reading)
        return all_readings

 
if __name__ == "__main__":
    filename = input("Enter CSV file name: ")
    all_readings = get_readings_from_file(filename, True)
    print("Your readings:")
    for reading in all_readings:
        print(f"\tTemp: {reading.temperature}", end="")
        print(f"\tPressure: {reading.pressure}", end="")
        print(f"\tHumidity: {reading.humidity}")
    pickle_demo = open('pickle_demo.bin', 'wb')
    pickle.dump(all_readings, pickle_demo)
    pickle_demo.close()

Making those few changes to the get_readings_from_file function and your script should work fine

Sign up to request clarification or add additional context in comments.

4 Comments

hey bro, the way you had it before you edited it was perfect.
@StephenMartinez it is the same exact thing... I just removed the parts that I didn't edit to make it more obvious which parts I did edit....
it didn't work, output was blank
@StephenMartinez I changed it back

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.