我有一個程式,一個功能是出售用戶擁有的物品。它會提示用戶輸入名稱(id)和數量,然后進行銷售。但是用戶可以擁有很多專案,因此有很多 if else elif 陳述句。我如何縮短這個?(PS我用的是Replit,Replit目前有Python 3.8)這里是sell函式,供參考。
def sell_command():
global cash
cash = 0
#I created a dictionary, inventory, which has how much the user has of a particular item.
#itemSell variable contains what the user wants to sell
#itemSellCount variable contains how much the user wants to sell
#itemSoldCash variable calculates how much one item is worth, and multiplies for how much the user is selling
#cash variable is hlobal since another function prints cash
itemSell = input('What would you like to sell? ')
itemSell = itemSell.lower()
if itemSell == "cobblestone" or "cobble stone":
itemSellCount = int(input("How many would you like to sell? "))
if itemSellCount <= inventory["cobblestone"]:
itemSoldCash = itemSellCount*10
print("You sold " str(itemSellCount) " cobblestone/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["cobblestone"] -= itemSellCount
elif itemSellCount > inventory["cobblestone"]:
print("You tried to sell more than what you have!")
elif itemSell == "coal":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["coal"]:
itemSoldCash = itemSellCount*5
print("You sold " str(itemSellCount) " coal for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["coal"] -= itemSellCount
elif itemSellCount > inventory["coal"]:
print("You tried to sell more than what you have!")
elif itemSell == "iron ore" or "ironore":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["ironOre"]:
itemSoldCash = itemSellCount*20
print("You sold " str(itemSellCount) " iron ore/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["cobblestone"] -= itemSellCount
elif itemSellCount > inventory["ironOre"]:
print("You tried to sell more than what you have!")
elif itemSell == "iron ingot" or "ironingot":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["ironIngot"]:
itemSoldCash = itemSellCount*25
print("You sold " str(itemSellCount) " iron ingot/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["ironIngot"] -= itemSellCount
elif itemSellCount > inventory["ironIngot"]:
print("You tried to sell more than what you have!")
elif itemSell == "emerald" or "emeralds":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["emerald"]:
itemSoldCash = itemSellCount*100
print("You sold " str(itemSellCount) "emerald/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["emerald"] -= itemSellCount
elif itemSellCount > inventory["emerald"]:
print("You tried to sell more than what you have!")
elif itemSell == "diamond" or "diamonds":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["diamond"]:
itemSoldCash = itemSellCount*300
print("You sold " str(itemSellCount) " diamond/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["diamond"] -= itemSellCount
elif itemSellCount > inventory["diamond"]:
print("You tried to sell more than what you have!")
elif itemSell == "oak":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["oak"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " oak/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["oak"] -= itemSellCount
elif itemSellCount > inventory["oak"]:
print("You tried to sell more than what you have!")
elif itemSell == "birch":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["birch"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " birch for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["birch"] -= itemSellCount
elif itemSellCount > inventory["birch"]:
print("You tried to sell more than what you have!")
elif itemSell == "redwood" or "red wood":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["redwood"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) "redwood for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["redwood"] -= itemSellCount
elif itemSellCount > inventory["redwood"]:
print("You tried to sell more than what you have!")
elif itemSell == "spruce":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["spruce"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " spruce for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["spruce"] -= itemSellCount
elif itemSellCount > inventory["spruce"]:
print("You tried to sell more than what you have!")
elif itemSell == "acacia":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["acacia"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " acacia for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["acacia"] -= itemSellCount
elif itemSellCount > inventory["acacia"]:
print("You tried to sell more than what you have!")
elif itemSell == "jungle":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["jungle"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " jungle for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["jungle"] -= itemSellCount
elif itemSellCount > inventory["jungle"]:
print("You tried to sell more than what you have!")
elif itemSell == "maple":
itemSellCount = int(input("How many would you like to sell?"))
if itemSellCount <= inventory["maple"]:
itemSoldCash = itemSellCount*15
print("You sold " str(itemSellCount) " maple for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory["maple"] -= itemSellCount
elif itemSellCount > inventory["maple"]:
print("You tried to sell more than what you have!")
uj5u.com熱心網友回復:
這是很多重復的代碼,本質上是相同的東西(我已經稍微清理了你的語法):
itemSellCount = int(input("How many would you like to sell? "))
if itemSellCount <= inventory[itemSell]:
itemSoldCash = itemSellCount*10
print(f"You sold {itemSellCount} {itemSell}/s for ${itemSoldCash}")
cash = itemSoldCash
inventory[itemSell] -= itemSellCount
else:
print("You tried to sell more than what you have!")
但是,有以下三點需要考慮:
1. 每件商品的售價是多少?
這可以通過多種方式解決,具體取決于編程風格以及您需要跟蹤每個專案的內容。OOP 方法是創建一個專案類,每個專案都有一些定義其值的屬性。一個簡單的程式性方法是擁有一個定義此內容的字典:
itemValue = {
"cobblestone": 10,
"coal": 5,
...
}
現在,使用字典查找來確定itemSoldCash:
itemSoldCash = itemSellCount*itemValue[itemSell]
2. 替代物品名稱
您接受替代專案名稱,例如“圓石”被視為“圓石”。這也可以通過字典來解決,例如:
itemAltNames = {
"cobble stone": "cobblestone",
"iron ingot": "iron ingot",
...
}
然后,您可以執行以下操作:
if itemSell in itemAltNames:
itemSell = itemAltNames[itemSell];
或者,如果您的替代方案僅涉及剝離空格,則只需這樣做:
itemSell = itemSell.replace(" ","")
3. 檢查專案是否存在
就目前而言,如果用戶輸入無效專案,您的控制流將不會執行。這很好,但過于復雜!另外,如果用戶輸入無效專案,您是否給出錯誤訊息(或允許重復輸入)?檢查您的庫存字典以確保用戶擁有該專案:
if itemSell in inventory:
把它放在一起
這就是現在一切可能的樣子:
def sell_command():
global cash
cash = 0
itemSell = input("What would you like to sell? ")
while (itemSell := itemSell.lower().strip().replace(" ","")) not in inventory:
itemSell = input(f"You do not have {itemSell} in your inventory. What would you like to sell? ")
itemSellCount = int(input("How many would you like to sell? "))
if itemSellCount <= inventory[itemSell]:
itemSoldCash = itemSellCount * itemValue[itemSell]
print(f"You sold {itemSellCount} {itemSell}/s for ${itemSoldCash}")
cash = itemSoldCash
inventory[itemSell] -= itemSellCount
else:
print("You tried to sell more than what you have!")
uj5u.com熱心網友回復:
您可以使用字典和物件為您正在做的事情減少很多分支。這就是 OOP 的力量。這是一個如何重構代碼的示例。
cash = 0
class CommodityShelf:
"""
A shelf to hold commodities
"""
def __init__(self, item_name, available_quantity, price):
self.item_name = item_name
self.available_qty = available_quantity
self.price = price or 10
def key(self):
# "make it easy to search for this shelf"
return self.item_name.lower().replace(" ", "")
def sell(self):
# handle the selling logic at one place, for any item
global cash
sell_units = int(input(f"How many {self.item_name} would you like to sell? "))
if sell_units > self.available_qty:
print(f"You tried to sell more {self.item_name} than what you have!")
else:
cash = (sell_units * self.price)
self.available_qty -= sell_units
print(f"You sold {self.item_name} for ${sell_units * self.price}")
def start_selling(pos_registry):
"""
Start selling commodities
:param pos_registry:
:return:
"""
item_to_sell = input('What would you like to sell? ').lower().replace(" ", "")
if item_to_sell in pos_registry:
pos_registry[item_to_sell].sell()
else:
print(f"You tried to sell {item_to_sell} but it's not in your inventory!")
if __name__ == '__main__':
# create a shelf for each commodity
inventory = [
CommodityShelf("Cobble Stone", 10, 0),
CommodityShelf("Coal", 10, 0),
CommodityShelf("Iron Ore", 10, 0),
CommodityShelf("Iron Ingot", 10, 0),
CommodityShelf("Emarald", 10, 0),
CommodityShelf("Diamond", 10, 0),
]
# create a registry of all the shelves
pos_registry = {pos.key(): pos for pos in inventory}
# start selling
start_selling(pos_registry)
# loop it if the user wants to
我希望在評論中給出合乎邏輯的解釋。
uj5u.com熱心網友回復:
看起來你的很多 if-else 都是多余的。每個 if 條件中唯一唯一的就是itemSoldCash。您可以使用輔助函式將它們映射到相關的itemSells,否則使用單個 if-else 條件:
def sell_command():
global cash
cash = 0
def get_Cash(itemSell, itemSellCount):
if itemSell == "cobblestone":
return itemSellCount*10
elif itemSell == "coal":
return itemSellCount*5
elif itemSell == "ironore":
return itemSellCount*20
elif itemSell == "ironingot":
return itemSellCount*25
elif itemSell == "emerald":
return itemSellCount*100
elif itemSell == "diamond":
return itemSellCount*300
elif itemSell in ["oak","birch","redwood","spruce","acacia","jungle","maple"]:
return itemSellCount*15
itemSell = ''.join(input('What would you like to sell? ').lower())
itemSellCount = int(input("How many would you like to sell? "))
if itemSellCount <= inventory[itemSell]:
itemSoldCash = get_Cash(itemSell, itemSellCount)
print("You sold {} {} for ${}".format(itemSellCount, itemSell, itemSoldCash))
cash = itemSoldCash
inventory[itemSell] -= itemSellCount
else:
print("You tried to sell more than what you have!")
uj5u.com熱心網友回復:
此代碼可能是最簡單的修復方法。不過,您可能需要更改庫存字典,以便每個鍵都是小寫的。
此外,itemSell == "cobblestone" or "cobble stone"始終回傳 true。
def sell_command():
global cash
cash = 0
cashMultiplierDict = {"cobblestone": 10, "coal": 5} #etc
#The following line just removes all white spaces (e.g. cobble stone becomes cobblestone)
itemSell = input('What would you like to sell? ').lower().replace(" ", "")
itemSellCount = int(input("How many would you like to sell? "))
if itemSellCount <= inventory[itemSell]:
itemSoldCash = itemSellCount * cashMultiplierDict[itemSell] #Uses the dict created before
print("You sold " str(itemSellCount) " " itemSell "/s for $" str(itemSoldCash))
cash = cash itemSoldCash
inventory[itemSell] -= itemSellCount
elif itemSellCount > inventory[itemSell]:
print("You tried to sell more than what you have!")
uj5u.com熱心網友回復:
您可以更好地組織代碼:
這
itemSellCount = int(input("How many would you like to sell?")
為每個專案完成,這可以完成一次,然后
itemSoldCash = itemSellCount*15
是成本的數量。成本可以以更好的資料結構組織到一個目錄中,可能是這樣的:
# you can add if needed other attributes for all material, like color, weight, damage, duration, and so on
catalogue = {
"cobblestone": {"cost": 15, 'color':'red'},
"maple": {"cost": 15},
"jungle": {"cost": 15},
"acacia": {"cost": 15},
"diamond": {"cost": 300},
...
}
# aliases
catalogue["cobble stone"] = catalogue["cobblestone"]
def sell(item, qty, inventory):
if qty <= inventory[item]:
sold = qty * catalogue[item]["cost"]
print("You sold {} maple for ${}".format(qty, sold))
cash = sold
inventory[item] -= qty
else:
print("You tried to sell more {} than what you have!".format(item))
最后你用所有需要的資訊呼叫這個函式:
itemSell = input('What would you like to sell? ')
itemSell = itemSell.lower()
itemSellCount = int(input("How many would you like to sell? "))
sell(itemSell,itemSellCount, inventory)
示例中未定義庫存。
PS 如果許多物件成本相同,并且它們被認為是默認成本,您可以簡化目錄定義,只放入特殊成本,默認值可以作為缺失值應用:
sold = qty * (catalogue[item]["cost"] if item in catalogue else 15)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/399454.html
標籤:Python if 语句 python-3.8
上一篇:使用if陳述句向后回圈
