Home > Software design >  If statement invalid when comparing columns in csv file?
If statement invalid when comparing columns in csv file?

Time:08-09

I want to compare the Speedlimit column with the Speed column in a csv file. The idea is that the user can input a percentage and the program returns a list with the speeds that are x % over the speed limit. When I run the program it prints the entire list, not just the rows where the driven speed is x% greater than the speedlimit. Am I missing something that makes the if statement invalid? Is the code getting stuck in a loop? I am super new to python /programming and any tips/advice is appreciated. btw. i am not allowed to use pandas for my course.

Here is my code so far:

import csv

if __name__ == '__main__':
    percentage = float(input(r'% over speed limit to filter by: '))
    factor = (percentage/100) 1
    with open('./cameraData.csv', 'r', encoding = 'UTF-8') as csvfile:
            reader = csv.DictReader(csvfile, delimiter=';')
            for row in reader:
                    if float(row['Speed'])*factor > float(row['Speedlimit']): 
                        print(row) 

The csv file (cameraData)looks something like this:

IDnumber;Speedlimit;Speed;Date;Time
14075010;40;55;2021-09-11;11:15:31
14075010;40;54;2021-09-11;08:09:17
14075010;40;57;2021-09-11;13:02:41
14075010;40;49;2021-09-11;13:02:55

CodePudding user response:

The logic is incorrect. Use if float(row['Speedlimit'])*factor < float(row['Speed']) instead of if float(row['Speed'])*factor > float(row['Speedlimit'])

CodePudding user response:

Python's CSV reader returns strings (more precisely, lists of strings - one list per row in the file, with each list containing the individual comma-separated strings of the row). What you need to do before applying < and > comparators is to cast these strings into int or float, depending on the kinds of numbers you have.

  • Related