Day 15th: same code works in replit but not in Pycharm

Don’t understand why “shut_machine” global variable doesn’t change when it’s supposed to:

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,
    }
}

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

shut_machine = False

def coffee_machine():
    resources["Money"] = 0.0
    #  TODO 1. prompt "report" def report: to tell you the remaining resources in the machine
    order = input("what would you like? (espresso/latte/cappuccino):")

    #  TODO 2. prompt "what would you like? (espresso/latte/cappuccino):" def check: to check if the remaining sources
    #   are sufficient, and return what's missing or allow proceed coffee making
    def check(coffee):
        if order != "report":
            for i in MENU[coffee]["ingredients"].keys():
                resources[i] -= MENU[coffee]["ingredients"][i]
                if resources[i] < 0:
                    print(f"add {i}")
                    global shut_machine
                    shut_machine = True
        if coffee == "report":
            print(resources)
    check(order)

    #  TODO 3. ask for payment, then refund or give changes
    global shut_machine
    if not shut_machine:
        paying = input("please insert coins: quarters, dimes, nickles, pennies\n")
        n_q = int(paying.split(",")[0])
        n_d = int(paying.split(",")[1])
        n_n = int(paying.split(",")[2])
        n_p = int(paying.split(",")[3])

        def coins_total():
            return n_q * 0.25 + n_d * 0.1 + n_n * 0.05 + n_p * 0.01

        # TODO 4. update resources:
        if coins_total() >= MENU[order]["cost"]:
            change = coins_total() - MENU[order]["cost"]
            print(f"{order} is coming right up!, and your change is {round(change, 2)}")
            resources["Money"] += (coins_total() - change)
        else:
            print(f"your money is not enough, and you are refunded")
            return
    while not shut_machine:
        coffee_machine()


coffee_machine()

Is resources declared also or somehow implicit (from an imported file) in the exercise you are doing?
I only see an assignment but no declaration.

Btw it is always better to avoid global variables …

1 Like

Absolutely agree, Global variable is better not to be messed

I struggled with global variables the last time I needed them, so I cheated and made a text file. Now I have my own commands in my own library (pip install CoderElijah) to use text files for global variables if I need to. That, of course, is for worst-case scenarios only.