我有一个我正在设计的文本文件,该文件为我叫'Bodn's Superstore'的模拟商店。
我设计了一个.txt数据库。
iPhone
28273139
5.50
Book
81413852
1.50
Charger
62863152
3.00
Plug
25537398
4.50
您可以看到它遵循格式
Name
Code
Price
我编写的代码旨在将数据库转换为词典,并且客户可以选择他们购买的产品数量。然后,他们将8位数字代码输入计算机,而闲置工作可以找出产品的名称。
代码在下面显示。它首先验证代码以确保其长8个字符。(Python 3.4.2)
database = open("SODatabase.txt", "r")
list = {}
for line in database:
key = line.strip()
code = next(database).strip()
price = next(database).strip()
# next(database).strip() # if using python 3.x
list[key]=code,price
numberItems=int(input('State the quantity required. >> '))
with open('SODatabase.txt','r') as searchfile:
for line in searchfile:
while True:
userCode=input('What product would you like? Enter the product code >> ')
try:
if len(str(userCode))!=8:
raise ValueError()
userCode=int(userCode)
except ValueError:
print('The code must be 8 characters long.')
else:
for key, value in list.items():
if userCode==value:
print (key)
现在,代码的验证有效。例如,我想购买1个iPhone。这就是主窗口中出现的。
State the quantity required. >> 1
What product would you like? Enter the product code >> 2827313
The code must be 8 characters long.
What product would you like? Enter the product code >> 28273139
What product would you like? Enter the product code >> 28273139
What product would you like? Enter the product code >>
等等。该代码根本无法向后工作以找到字典的键并打印它,即" iPhone"。我想在说明我的数量和产品代码后接收" iPhone"的名称,但是我的python文件无法通过字典来返回以找到与产品代码相对应的键(值)我给了它。
我不明白为什么需要for line in searchfile
;似乎是一个副本错误。
无论如何,userCode
永远不会等于value
,因为value
是元组;但是,它可以等于value[0]
,在其中保存了代码。
那怎么样?
while True:
userCode = input('What product would you like? Enter the product code >> ')
try:
if len(str(userCode))!=8:
raise ValueError()
userCode = int(userCode)
except ValueError:
print('The code must be 8 characters long.')
else:
for key, value in list.items():
if userCode == value[0]:
print (key)
database = open("SODatabase.txt", "r")
list = {}
for line in database:
key = line.strip()
code = int(next(database).strip())
price = next(database).strip()
# next(database).strip() # if using python 3.x
list[key] = code, price
while True:
userCode = input('What product would you like? Enter the product code >> ')
if userCode == "":
break
try:
if len(str(userCode)) != 8:
raise ValueError()
userCode = int(userCode)
except ValueError:
print('The code must be 8 characters long.')
else:
for key, value in list.items():
if userCode == value[0]: # code is stored as 1st element of value
print (key)
要注意的几件事:
- 请避免使用"列表"作为变量名称。
- 无需再次打开数据库文件。
- 在存储细节时,您将它们存储为包含元组(代码,价格)。因此,要比较usercode,您应该将其与元组的第一个元素进行比较。
- 代码一遍又一遍地循环,因为没有退出声明即可退出循环。