Joe*_*GeC 1 python keyword-argument python-3.x
我对 Python 比较陌生,最近遇到了 kwargs。我想我了解它们以及它们是如何工作的。但是,当我尝试使用 for 循环打印键和值时,会出现 ValueError: Too many values to unpack。
def shop(**kwargs):
sh = 1
print ("Welcome to the shop!")
for i, v in kwargs:
print (" ", i, ": ", v)
while sh == 1:
b = input ("What would you like to buy?").lower()
if b == i:
Player.gold -= v
Player.inv_plus(i)
elif b == "exit":
sh = 0
shop(Stone=5, Potion=10)
Run Code Online (Sandbox Code Playgroud)
Player.gold 就是玩家拥有多少金币,而 Player.inv_plus(i) 会为玩家库存中的物品加 1。不过,这对我遇到的问题并不重要。
如果我在没有 for 循环的情况下打印 kwargs,它工作正常。但这不是我打印时想要的格式。
如果有人能解释我做错了什么,我将不胜感激,因为我很困惑为什么它不起作用。
kwargs 是一个字典,默认情况下迭代它们只返回键。你需要kwargs.items().
for i, v in kwargs.items():
print (" ", i, ": ", v)
Run Code Online (Sandbox Code Playgroud)