我對 python 很陌生,發現自己很困惑。誰能幫助我或者更好地解釋我如何獲得我想要的輸出?我有一本包含我的“庫存”的當前字典和包含我的“dragonLoot”的串列。我正在嘗試創建一個函式,詢問用戶是否想在他們的庫存中添加任何其他內容,然后將它們添加到我的常備字典串列中。我知道我的第一個功能是正確的,但我無法理解在第二個功能中要更改的內容。這是我到目前為止所擁有的:
感謝您提供的任何幫助,我再次對此非常陌生,并且仍在努力解決功能
def displayInventory(myInv):
print("Inventory:")
total = 0
for k,v in myInv.items() :
print(str(v) " " k)
total = total v
print("Total number of items:" str(total))
def addToInventory(inventory,addedItems) :
addedItems = input("What would you like to add to your your Dragon Loot? Enter D when finished ")
if addedItems not in dragonLoot :
inventory.update({addedItems})
if input == "D" :
return dragonLoot
addToInventory(inventory,addedItems)
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}#Create your inventory dictonary
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
displayInventory(inventory)
uj5u.com熱心網友回復:
首先,當您嘗試向字典添加新專案時,您必須使用split()函式。它將允許用戶在同一行輸入兩個值。我做了一些基本的改變,剩下的你自己做。
def displayInventory(myInv):
print("Inventory:")
total = 0
for k,v in myInv.items() :
print(str(v) " " k)
total = int(v)
print("Total number of items:" str(total))
def addToInventory(inventory,dragonLoot) :
new_Item = int(input("How many Items you want to add? "))
counter = 0
while (new_Item != counter):
name_Item, quantity_Item = input("What would you like to add to your your Dragon Loot? Enter D when finished :").split()
if name_Item not in dragonLoot :
inventory[name_Item] = quantity_Item
counter =1
inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}#Create your inventory dictonary
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
addToInventory(inventory,dragonLoot)
displayInventory(inventory)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/515429.html
標籤:Python列表功能字典
下一篇:執行回圈直到滿足條件
