我是這里的新手。英語不是我的母語,所以請原諒任何語法錯誤。我正在嘗試為具有特殊條件的自動售貨機撰寫代碼。我對 inv_coins 有疑問。
Inv_coins = 找零的紙幣數量。
我的代碼出現以下錯誤:
while inv_coins < price:
inv_coins = inv_coins float(input('insert ' str(price - inv_coins) ':
TypeError:'dict'和'int'的實體之間不支持'<'
我應該如何編輯此代碼以使用我的自動售貨機?
def vend():
'''
inv_data = {'Chips':{'stock':50, 'price':11},
'Water':{'stock':50, 'price':7},
'Candies':{'stock':50, 'price':8},
'Sandwich':{'stock':50, 'price':27}}
inv_coins = {100:0, 50:0, 10:20, 5:20, 2:20, 1:20}
'''
a = {'item': 'Chips', 'price': 11, 'stock': 50}
b = {'item': 'Water', 'price': 7, 'stock': 50}
c = {'item': 'Candies', 'price': 8, 'stock': 50}
d = {'item': 'Sandwich', 'price': 27, 'stock': 50}
items = [a, b, c, d]
cim = {100:0, 50:0, 10:20, 5:20, 2:20, 1:20}
print('Hi there! This is the vending machine of Felix Seletskiy \n@@@@@@@@@@@@@@@')
# 1. Here we offer a menu by showing items and prices
def show(items):
print('\nitems available \n***************')
for item in items:
if item.get('stock') == 0:
items.remove(item)
for item in items:
print(item.get('item'), item.get('price'))
print('***************\n')
# 2. Here we take an order to suggest to place another order
continueToBuy = True
# have user choose item
while continueToBuy == True:
show(items)
selected = input('select item: ')
for item in items:
if selected == item.get('item'):
selected = item
price = selected.get('price')
while inv_coins < price:
inv_coins = inv_coins float(input('insert ' str(price - inv_coins) ': '))
print('you got ' selected.get('item'))
# 4. Here we update the stock after processing the current order
selected['stock'] -= 1
inv_coins-= price
print('cash remaining: ' str(inv_coins))
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
# 3. Here we calculate the price and update the price based on coins input
# 4. Here we calculate the change based on coins stock
if cim != 0:
print(str(cim) ' refunded')
cim = 0
print('thank you, have a nice day!\n')
break
else:
print('thank you, have a nice day!\n')
break
else:
continue
uj5u.com熱心網友回復:
在您的行 while inv_coins < price:中,您正在比較字典 inv_coins 和整數硬幣。這種比較是行不通的。您不應將字典本身與數字進行比較,而應獲取相應的數字。我想 inv_coin 表示硬幣的庫存,因此您可以遍歷該字典以獲取每種面額的硬幣數量,然后將其乘以該面額的值(例如,如果您有 20 個季度,則為 20 * $0.25 = $5 ),將它們相加,就可以得到一個整數,您可以將其與另一個整數進行比較。
uj5u.com熱心網友回復:
問題是您不能只使用 inv_coins (這是一個字典)并將其與整數進行比較。
每當您想要訪問 inv_coins 時,您必須指定您想要訪問的確切值并在方括號中提供其鍵。
例如:
# dictionary with key:value pairs
inv_coins = {100:0, 50:0, 10:20, 5:20, 2:20, 1:20}
# find out how many coins with key 10 there are in the inv_coins dict:
print(inv_coins[10])
> 20
# add a coin with key 100 to the inv_coins dict:
inv_coins[100] = 1
print(inv_coins[100])
> 1
print(inv_coins)
> {100:1, 50:0, 10:20, 5:20, 2:20, 1:20}
你到底想用 while-loop 歸檔while inv_coins < price:什么?您是否要一直處于此回圈中,直到將足夠的硬幣添加到硬幣庫存中以覆寫價格?
這通常可能是有問題的,因為您缺少對客戶開始插入硬幣之前庫存的參考。因此,最好使用一個額外的變數來了解到目前為止支付了多少,并且一旦涵蓋了您繼續進行的價格。
uj5u.com熱心網友回復:
該錯誤告訴您確切的問題是什么,您正在嘗試比較字典和整數,而python不喜歡那樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429210.html
標籤:Python python-3.x
