好像它没有读取列表并且我的循环不工作

Seems like it is not reading the list and my loop is not working

我必须调用 readPriceList 函数从文本文件中读取价目表并显示它。然后我必须使用循环让客户输入产品代码。当他输入不在列表中的代码时,显示未找到项目。否则,找到的项目和价格。和 9999 退出循环。

def scanPrices():
    price_list = readPriceList()
    price = set(price_list)
    itemCode = 0
    totalPrice = 0.0
    item_price = price_list.values()
    itemCode = int(input("Enter 4-digit item code [or 9999 to stop]: "))
    while itemCode != 9999:
        itemCode = int(input("Enter 4-digit item code [or 9999 to stop]: "))
        if itemCode in price_list:
            itemPrice = price_list.values()
            print("Item found. Price:", item_price)
        else:
            print("Item not found")
    return totalPrice

这是我的输出:

Welcome to Wake-Mart. Please register!
Name: lol
Enter credit card number: 444444
Enter security code: 454
Enter debit card number: 44444444
Enter PIN: 5555
Registration completed!

Price list:
('1423', 7.88)
('1752', 4.99)
('2368', 5.25)
('2159', 0.99)
('2487', 12.52)
('4178', 8.00)
('5206', 4.25)
('6112', 5.77)
('6245', 4.88)
('6625', 2.99)
Enter 4-digit item code [or 9999 to stop]: 6112
Enter 4-digit item code [or 9999 to stop]: 9999
Item not found

非常感谢!

因为字典包含键的字符串,所以您不需要将任何内容转换为整数。我还将输入移到了 while 循环的底部,因此它不会在开头显示两次。

def scanPrices():
    price_list = readPriceList()
    totalPrice = 0.0
    itemCode = input("Enter 4-digit item code [or 9999 to stop]: ")
    while itemCode != '9999':
        if itemCode in price_list:
            itemPrice = price_list[itemCode]
            print("Item found. Price:", itemPrice)
            totalPrice += itemPrice
        else:
            print("Item not found")
        itemCode = input("Enter 4-digit item code [or 9999 to stop]: ")
    return totalPrice

您正在将字符串与整数进行比较,要么将 price_list 字典中的键转换为整数,要么不将 itemcode 变量转换为整数,让它成为字符串