python 她如何使用全局变量而不将其传入函数参数

h4cxqtbf  于 2022-12-02  发布在  Python
关注(0)|答案(2)|浏览(162)

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

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"])

我试着看她的解决方案,发现她的一个函数使用的字典资源没有在函数内部声明,也没有作为参数传递。我的英语不是很好,这就是为什么我很难在互联网上搜索我特别想了解的内容。有人能用这个主题启发我吗?
注意:不建议使用全局
我的代码:
(my如果未将变量设置为全局变量或未将其作为参数传递,则永远不能在函数外部使用变量)

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!")
7kqas0il

7kqas0il1#

考虑一个更简单的示例

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
}

def test(item, val):
    resources[item] -= val

test("water", 5)

这个程序可以运行。即使resources不是参数,test也会更新resources。Python需要知道函数中使用的哪些变量是局部变量,哪些不是。规则很简单:在函数中赋值的变量是函数的局部变量。关键字global打破了这一规则,允许您在全局范围内赋值变量。
在本例中

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

var1在函数中被赋值,因此python将其设为局部变量。var2在函数中被引用,但未被赋值,因此python在全局作用域中查找其值。var3被赋值,但也声明了global,因此局部变量规则被打破,赋值将转到全局作用域。

jhiyze9q

jhiyze9q2#

我想在此处添加John在udemy QnA部分发布的答案:
列表和字典是可变的。这意味着你可以在列表/字典中添加和删除元素,而它仍然是相同的列表/字典对象。在这种情况下,没有必要创建一个新的列表/字典。
几乎所有其他Python对象都是不可变的。这意味着一旦创建,它们就不能以任何方式改变。例如,如果a是一个整数,那么当你执行a += 1***时,就会创建一个全新的整数对象。***
全局变量可以在文件中的任何位置读取,包括函数内部。
规则是,***在没有使用global关键字授予特定权限的情况下,***不允许函数创建新的全局对象。
为了说明这一点,让我们看看对象的内存位置是什么:

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)

See Mutable vs Immutable Objects in Python

相关问题