【发布时间】:2021-07-28 06:25:00
【问题描述】:
我正在尝试为以下内容编写代码: 这个想法是有一个存储/库存字典,然后通过某些家庭任务减少键值。例如。清洁、烹饪等。
这将是存储字典:
cupboard= {"cookies":30,
"coffee":3,
"washingpowder": 5,
"cleaningspray": 5,
'Pasta': 0.5,
'Tomato': 4,
'Beef': 2,
'Potato': 2,
'Flour': 0.2,
'Milk': 1,
"Burger buns": 6}
现在这是我编写的代码,用于尝试减少一个键的值(想法是“清洁”动作将“清洁喷雾”键减少一个清洁单位 = 0.5
cleaning_amount = 0.5
def cleaning(room):
while cupboard["cleaningspray"] <0.5:
cleaned = {key: cupboard.get(key) - cleaning_amount for key in cupboard}
return cupboard
livingroom = 1*cleaning_amount
cleaning(livingroom)
print(cupboard)
但它返回的是 this,它与以前的字典相同,没有更新值
{'cookies': 30, 'coffee': 3, 'washingpowder': 5, 'cleaningspray': 5, 'Pasta': 0.5, 'Tomato': 4, 'Beef': 2, 'Potato': 2, 'Flour': 0.2, 'Milk': 1, 'Burger buns': 6}
有人可以帮忙吗?
谢谢!!
附上图片以查看缩进等。
【问题讨论】:
-
while 循环中的 return 语句实际上只是 if 语句中的 return 语句。函数的执行在 return 语句之后停止。
标签: python function dictionary key key-value