python - 为什么这不能正确提取价格?每个价格都为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()
解决方案
相对而言,代码似乎有点到处都是,特别是在价格方面。如果这是您的代码的精确副本,我认为您可能已经忘记了“价格”实际上是什么。
例如这里:
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["£"]
这将导致异常。
我会再次检查您的代码并确保您正在引用price
,price_value
以及all_prices
您真正想要它们的位置
推荐阅读
- javascript - 正则表达式匹配点和数字跟随点
- ios - 将作为参数传递给另一个函数的函数设为可选?
- docker - 如何通过变量扩展将默认 CMD 传递给 ENTRYPOINT?
- python - 在我的打印语句中添加代码块的时间
- azure - Azure 数据仓库到 CosmosDB 与数据工厂管道同步
- javascript - 没有 setTimeout 的 VueJS 转换不起作用
- python - Python 的 dict 元组列表
- javascript - 对象数组的键值对交集
- excel - VBA Excel 2013 列范围与下拉列表创建 VBA 代码以全选和取消全选复选标记
- javascript - DavieJones 在表单验证器中的 client_side_validations 无法正确解析 Rails