簡體   English   中英

如何將用戶整數輸入與字典中的值進行比較? (Python)

[英]How do I compare user integer input to values in dictionary? (Python)

我正在開發一個自動售貨機程序,我的代碼直接跳到 else 語句,而不是獲取用戶輸入並將其與列表中的 ID 號進行比較。

這是列表和代碼:`

itemstock = [

    {
        "idnum": 0,
        "name": 'Water',
        "price": 12,
    },
    {
        "idnum": 1,
        "name": 'Soda',
        "price": 14,
    },
    {
        "idnum": 2,
        "name": 'Juice',
        "price": 13,
    },
    ]

choice = int(input("Now, choose an item ID from the Menu and enter the ID: "))
for i in itemstock:
    if choice in ["idnum"]:
        print("You have chosen item", choice)
    else:
        print("This is not a valid ID.")
        break

`

我曾希望如果我輸入數字 2,它會顯示用戶選擇的內容以及一些文本,但它會直接跳到 else 語句。 我試過在線查看,但我可能在這里做錯了什么。

if choice in ["idnum"]

那只是一個包含文本“idnum”的列表。 你想要i["idnum"]代替:

for i in itemstock:
    if i["idnum"] == choice:
        print("You have chosen item", choice)
        break
else:
    print("This is not a valid ID.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM