python - python中的全局和局部范围
问题描述
profit = 0
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def enough_resources(ingredients) -> bool:
flag = True
for i in ingredients:
if resources[i]-ingredients[i] < 0:
flag = False
return flag
def get_change(cost):
print(f"Your coffee is ${cost:.2f}")
print("Please insert coins")
quarterMoney = int(input("How many quarters?: ")) * .25
dimeMoney = int(input("How many dimes?: ")) *.1
nickelMoney = int(input("How many nickels?: ")) * .05
pennyMoney = int(input("How many pennies?: ")) * .01
price = quarterMoney + dimeMoney + nickelMoney + pennyMoney
if price < cost:
print("not enough money")
return
else:
global profit
profit += cost
print(f"Your total change is {price-cost}.")
return
def use_resources(ingredients):
for i in ingredients:
resources[i] -= ingredients[i]
return resources
如您所见,我已经编写了这段代码。我不明白的是,在函数get_change
中,我必须将 声明profit
为全局变量。resources
为什么我在使用字典时不必这样做?请帮忙。是因为我没有修改字典吗?
解决方案
推荐阅读
- python - 问题将 django 项目部署到 Heroku
- javascript - 反向球运动/设置边缘
- c - 由于结构'crypt_data'没有名为'current_salt'的成员,nginx的编译失败
- javascript - 如何根据数组中的下一个/最后一个值更改 div id 的值
- drupal - 无法运行“blt 测试:phpunit”
- azure - Prometheus 无法通过浏览器访问
- angular - 如何从Angular中的api内容分配传递字符串?
- angular - 如何使用 Razor 页面和 Angular 一起创建 .NET 5 应用程序?
- java - 什么是字符串到 ZonedDateTime 转换错误
- javascript - 如何从 .tolocalstring() 函数运行时间?