如何使用全局变量而不将其传递到函数参数中



目前是Angela 100天python的第15天。我从所有的练习和项目中理解的是,函数外部的变量不能在函数内部使用,除非它作为参数传递或者你输入"全局"。在函数内部。

MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
profit = 0
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}

def is_resource_sufficient(order_ingredients):
"""Returns True when order can be made, False if ingredients are insufficient."""
for item in order_ingredients:
if order_ingredients[item] > resources[item]:
print(f"​Sorry there is not enough {item}.")
return False
return True

def process_coins():
"""Returns the total calculated from coins inserted."""
print("Please insert coins.")
total = int(input("how many quarters?: ")) * 0.25
total += int(input("how many dimes?: ")) * 0.1
total += int(input("how many nickles?: ")) * 0.05
total += int(input("how many pennies?: ")) * 0.01
return total

def is_transaction_successful(money_received, drink_cost):
"""Return True when the payment is accepted, or False if money is insufficient."""
if money_received >= drink_cost:
change = round(money_received - drink_cost, 2)
print(f"Here is ${change} in change.")
global profit
profit += drink_cost
return True
else:
print("Sorry that's not enough money. Money refunded.")
return False

def make_coffee(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources."""
for item in order_ingredients:
resources[item] -= order_ingredients[item]
print(f"Here is your {drink_name} ☕️. Enjoy!")

is_on = True
while is_on:
choice = input("​What would you like? (espresso/latte/cappuccino): ")
if choice == "off":
is_on = False
elif choice == "report":
print(f"Water: {resources['water']}ml")
print(f"Milk: {resources['milk']}ml")
print(f"Coffee: {resources['coffee']}g")
print(f"Money: ${profit}")
else:
drink = MENU[choice]
if is_resource_sufficient(drink["ingredients"]):
payment = process_coins()
if is_transaction_successful(payment, drink["cost"]):
make_coffee(choice, drink["ingredients"])

我试着看看她的解决方案,看到她的一个函数正在使用没有在函数内部声明也没有作为参数传递的字典资源。我的英语不是很好,这就是为什么我很难在网上搜索我想要理解的东西。有人能给我讲讲这个话题吗?

注意:不建议使用全局

我代码:

(我的理解是,如果没有设置为全局变量或作为参数传递,则永远不能在函数外使用变量)

def use_resources(user_order, machine_menu, machine_resources):
"""Deduct the resources needed for the user's order and returns the current resources of the machine after the
user's order. """
for menu_ingredients_key in machine_menu[user_order]["ingredients"]:
# print(menu_ingredients_key)  # REPRESENT KEY water, coffee
# print(menu[order]["ingredients"][menu_ingredients_key])  # REPRESENT VALUES [50,18]
for resources_key in machine_resources:
if resources_key == menu_ingredients_key:
machine_resources[menu_ingredients_key] -= menu[user_order]["ingredients"][menu_ingredients_key]
print(f"Here is your {user_order} ☕. Enjoy! Come again :)")

函数如何使用在函数外部声明而不是作为参数传递的资源?

def make_coffee(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources."""
for item in order_ingredients:
resources[item] -= order_ingredients[item]
print(f"Here is your {drink_name} ☕️. Enjoy!")

我想添加John在udemy QnA部分发布的答案:

列表和字典是可变的。这意味着您可以从列表/字典中添加和删除元素,而它仍然保持相同的列表/字典对象。在这种情况下,没有必要创建一个新的列表/字典。

几乎所有Python对象都是不可变的。这意味着一旦被创造出来,它们就不能以任何方式被改变。例如,如果a是整数,那么当执行a += 1时,将创建一个全新的整数对象。

全局变量可以在文件的任何地方读取,包括函数内部。

规则是函数不允许创建新的全局对象不需要您使用全局关键字给予特定的权限。

为了说明这一点,让我们看看对象的内存位置:

my_list = [1, 2, 3]
print(id(my_list), my_list)
my_list += [4]  # my_list is the same list object
print(id(my_list), my_list)

print()

my_int = 123
print(id(my_int), my_int)
my_int += 1  # my_int is a new integer object
print(id(my_int), my_int)

参见Python中的可变对象与不可变对象

考虑一个更简单的例子

resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def test(item, val):
resources[item] -= val
test("water", 5)

这个程序可以工作。test更新resources,即使resources不是参数。Python需要知道函数中使用的哪些变量是局部的,哪些不是。规则很简单:在函数中赋值的变量是该函数的局部变量。global关键字打破了这一规则,允许您在全局作用域中分配变量。

在这个例子中

def test2():
var1 = "foo"
print(var2)
global var3
var3 = "baz"

var1在函数中被赋值,所以python将其设置为本地。var2在函数中被引用,但没有被赋值,所以python在全局作用域中查找它的值。var3被赋值了,但它也声明了global,所以局部变量规则被打破了,赋值将进入全局作用域。

最新更新