為學校撰寫食品訂購程式,并在嘗試獲取用戶輸入以選擇選單項時遇到 TypeError 問題,然后使用該輸入將數量值參考到該字典。
`
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
key = int(input("Please select your item:\n"))
if int(key) < 1 or int(key) > 6:
print("Invalid selection. Please try again. \n")
isOrdering = True
continue
quan = int(input("Enter quantity: \n")), menu.update[key]({"quantity": quan})
我目前遇到的錯誤是“發生例外:TypeError 'builtin_function_or_method' object is not subscriptable” :
quan = int(input("輸入數量:\n")), menu.update[key]({"quantity": quan})
我根據之前嘗試詢問朋友為我發帖的嘗試嘗試了上面的代碼。拋出了與我最初嘗試解決時相同的錯誤。
預期/預期的輸出/更新(無論你想怎么稱呼它)是:
選單選擇:1
數量:3
字典更新:1:{“item”:“Green Beret Omelette”,“price”:“$12.99”,“quantity”:3}
uj5u.com熱心網友回復:
嘗試:
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
from pprint import pprint
print(" CHOOSE AN ITEM FROM THE MENU:")
pprint(menu)
print()
key = 0
while int(key) < 1 or int(key) > 6:
key = int(input("Please select your item (1 or 2 up to 6):\n"))
if int(key) < 1 or int(key) > 6:
print("Invalid selection. Please try again. \n")
quan = int(input("Enter quantity: \n"))
menu[key]["quantity"] = quan
pprint(menu)
print()
print(f'You ordered {key}: {menu[key]["item"]}, quantity: {quan}, total price=${quan*float(menu[key]["price"][1:])}')
uj5u.com熱心網友回復:
我認為您嘗試做的是在它甚至不知道“quan”是什么之前連接到您的選單字典。
嘗試獲取然后重置它。
menu = {
1: {"item": "Green Beret Omelette", "price": "$12.99"},
2: {"item": "Get to the Chopped Salad", "price": "$14.99"},
3: {"item": "Pump You Up Protein Shake", "price": "$9.99"},
4: {"item": "I'll Be Baby Back Ribs", "price": "$22.99"},
5: {"item": "Let Off Some Steamed Vegetables", "price": "$4.99"},
6: {"item": "The Ice Cream Cometh", "price": "$15.99"}
}
key = int(input("Please select your item:\n"))
if (int(key) < 1 or int(key) > 6):
print("Invalid selection. Please try again. \n")
isOrdering = True
m1 = menu[key]
quan = int(input("Enter quantity: \n"))
q = {"quantity":quan}
m1.update(q)
menu.update({key: m1})
print("dictionary updated:",list(menu.keys())[0],":",menu[key])
==============================
請選擇您的專案:
1
輸入數量:
3
字典更新:1 : {'item': 'Green Beret Omelette', 'price': '$12.99', 'quantity': 3}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528994.html
