首页 > 解决方案 > 为什么这不能正确提取价格?每个价格都为0?它还说在定义之前就引用了“付款”?

问题描述

# Sample line of text from file (Ford,F150,55000;)    
filename = 'carPrice.txt'

def main():

    all_prices= {}

    try:
        with open(filename) as fh:
            for line in fh:
                make, model, price = line.strip().split(',')
                all_prices[(make,model)]=price.strip()

        income = float(input("Enter your monthly income amount:"))
        print("Your monthly income amount is",income,)
        make = input("Enter Make of the car:")
        print("You selected a",make,)
        model = input("Enter Model of the car:")
        print("You selected a",model,)
        price_value=0
        for x in price:
            if x == (make,model):
                price_value=price[x]
        print("The price of that car is",price_value,)
        payment = (price_value* 0.80)/60
        print("The monthly payment is",payment,)

        if (payment < 0.11*income):
            print("The monthly payment of",payment,"= Acceptable Risk")
            return "Acceptable"
        else:
            print("The monthly payment of",payment,"= Unacceptable Risk")
            return "Unacceptable"

    # Exception added to enable troubleshooting of errors on lines
    except OSError as e:
        print(e.errno)

if __name__ == '__main__':
    main()

标签: python

解决方案


相对而言,代码似乎有点到处都是,特别是在价格方面。如果这是您的代码的精确副本,我认为您可能已经忘记了“价格”实际上是什么。

例如这里:

for x in price:
    if x == (make,model):
        price_value=price[x]

但是,price这是string您从文件中提取的值,例如 100 英镑。然后,您将对其进行迭代£, 1, 0, 0并根据品牌和型号对其进行检查。

最后你制作price_value这个字符串的索引,例如

price[x]  # could be price["£"]

这将导致异常。

我会再次检查您的代码并确保您正在引用priceprice_value以及all_prices您真正想要它们的位置


推荐阅读