如果声明打印错误

时间:2016-05-31 13:53:21

标签: python csv

我在CSV中有这些数据

34512340,0
12395675,2
56756777,1

我的代码是检查每种产品的库存水平。产品是csv中的八位数字,逗号后面的数字是可用存量。

如果库存水平高于0,则一切正常。

但是,当库存水平变为0,而不是打印缺货消息时,程序会打印新的订单消息。任何人都可以解决为什么会这样吗?

def checkstocklevel(code):
    with open('stockcontrol.csv',newline='') as f:
        for line in f:
            if code in line:
                data = line.split(",")
                stocklevel = int(data[1])
                if stocklevel <= 5:
                    print("New Order Required - Remaining Stock:",data[1],)
                elif stocklevel <= 10:
                    print("Low Stock - Remaining Stock:",data[1],)
                elif stocklevel < 1:
                    print("Sorry, this product is out of stock")
                    f = open("receipts","a")
                    f.write(code)
                    f.write(" Product Out Of Stock\n")
                    f.close()
                else:
                    print("Normal Stock -",data[1],)
                return stocklevel

由于

1 个答案:

答案 0 :(得分:3)

0的值已与您的第一个条件stocklevel <= 5匹配,因此您的后期条件< 1永远不会到达。

重新排序您的条件。从最严格的条件开始,然后放松它们。

            if stocklevel < 1:
                print("Sorry, this product is out of stock")
                f = open("receipts","a")
                f.write(code)
                f.write(" Product Out Of Stock\n")
                f.close()
            elif stocklevel <= 5:
                print("New Order Required - Remaining Stock:",data[1],)
            elif stocklevel <= 10:
                print("Low Stock - Remaining Stock:",data[1],)
            else:
                print("Normal Stock -",data[1],)