我正在尝试为一个简单的商店编写一个代码,它将从文件中加载产品和价格并将其加载到字典然后能够将其用于程序..但我试图不硬编码任何一个代码值,所以如果文件因为不可用而改变它。
我的文件= test.txt包含
banana:3
apple:4
这是我到目前为止所尝试的
d = {}
f = open('test.txt', 'r')
for line in f.readlines():
name,score = line.split(":")
d[name] = int(score)
print('''
Welcome to my store
What would you like to buy today
[1] banana
[2] apple
[3] orange
''')
menumain = int(input('Enter product number to continue: '))
if menumain == 1:
value = int(input('how many banana you will buy'))
new = d[name][0] * value
print('You ordered',value,'banana(s), Which will cost you',new )
else:
print('error! wrong menu')
我需要的是
new = d[name][0] * value
是否修改此行,以便自动选择索引..用户选择的内容以及产品名称。它使用产品的价值
在这种情况下,索引0将尝试获取值banana,该值为3,但它不起作用
我这样做是因为如果我写d ['banana']它会起作用,但如果外部文件中的某些内容被更改,代码就会中断。所以我需要一些东西,所以它的工作原理是软编码的
答案 0 :(得分:0)
使用一个简单的元组列表[(product_name1,price1)]将更加简单并完成工作。
#menu printing:
for counter, product in enumerate(product_list):
print(counter+1, product[0])
#getting the price
product_list[menumain[1]]