首页 > 解决方案 > 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为什么我在使用字典时不必这样做?请帮忙。是因为我没有修改字典吗?

标签: pythonmethods

解决方案


推荐阅读