Search code examples
python

My code is not printing the correct values


I have a code that runs through data.csv file, and it prints out values. But the values do not fit the test cases.

import csv
filePath="data.csv"
with open(filePath) as csvfile:
    reader=csv.DictReader(csvfile)   
    
    print("========================================================")
    print("Display item stock level above certain amount")
    print("========================================================")
    amount = input("Enter amount : ")
    print("========================================================")
    
    for row in reader:
        if (row['STOCK LEVEL'] >= amount):
            print("PRODUCT ID : {0}\nNAME : {1}\nLEVEL : {2}".format(row['PRODUCT ID'],row['NAME'],row['STOCK LEVEL']))
            print()

My codes asks an int input from the user, and would read through the file and print the details of the item, eg Product ID, name, stock level.

but when i enter 8, it should print the details for stock level above 8 and 12, but it only prints the details for 8. When i ask for 12, it would print the details for every item, (5, 7, 8, 12), which is wrong.


Solution

  • One possible error could be that you are comparing an integer value with a string value in line 8 (inside if condition)

    The output of 'amount' in line 5 will have the type 'string', which cannot be compared with any numerical value.

    I suggest you convert it into 'int'

    amount = int(input("bla bla"))
    

    I'm hoping your output of row["Stock level"] is an integer too. If it's not, put it inside int() function too.

    So, your final code will be:

    int(row["Stock level"]) >= amount
    

    Now try. Hope it helps. If this doesn't work, tell me.