[英]Why does this Python code just print one of the variables over and over again?
[英]Dictionary code just loops over and over again
我有一個文本文件,我正在為名為“ Bodn's Superstore”的模擬商店設計。
我設計了一個.txt數據庫。
iPhone
28273139
5.50
Book
81413852
1.50
Charger
62863152
3.00
Plug
25537398
4.50
您可以看到它遵循以下格式
Name
Code
Price
我編寫的代碼旨在將數據庫轉換成字典,客戶可以選擇購買的產品數量。 然后,他們將8位代碼輸入計算機,然后IDLE會找出產品名稱。
代碼如下所示。 它首先驗證代碼以確保其長度為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
中需要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)
需要注意的幾件事:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.