为什么我的代码只在任何可用资源都不足以煮咖啡时才给出错误,“NameError:name'r'未定义”?

2024-09-30 10:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,下面的代码应该是模拟咖啡机的。代码运行良好,但当任何可用资源不足以制作一杯新咖啡时,就会产生名称错误。我尝试将函数中的资源[r]存储到一个变量中,然后使用global关键字将该变量包含在条件语句中,但问题仍然存在。目标是在任何资源不足以准备订单时通知用户

    #Coffee ingredients and costs    
        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,
            }
        }
        #Coffee machine resources
        resources = {
            "water": 300,
            "milk": 200,
            "coffee": 100,
            "money": 0
        }
        
        #Loop through MENU to get the quantities of necessary ingredients to make a particular type of coffee
        for items in MENU:
            print(items)
            water = (((MENU[items])['ingredients'])['water'])
            coffee = (((MENU[items])['ingredients'])['coffee'])
            if items != 'espresso':
                milk = (((MENU[items])['ingredients'])['milk'])
        
        #Function that loops through the resources dictionary to provide the current quantities of available resources
        def report():
            for r in resources:
                if r.lower() == "water":
                    print(f'{r}: {resources[r]}'+"ml")
                if r.lower() == "milk":
                    print(f'{r}: {resources[r]}'+"ml")
                if r.lower() == "coffee":
                    print(f'{r}: {resources[r]}'+"g")
                if r.lower() == "money":
                    print(f'{r}: ${resources[r]}')
            return resources[r];
        
        global r
        power = True
        while power:
            print("Welcome to the coffee machine.")
            pennies = int(input("How many pennies did you insert?: "))
            nickles = int(input("How many nickles did you insert?: "))
            dimes = int(input("How many dimes did you insert?: "))
            quarters = int(input("How many quarters did you insert?: "))
            coinValue = (0.01*pennies)+(0.05*nickles)+(0.10*dimes)+(0.25*quarters)
            resources['money'] = resources['money']+coinValue
            coffeeChoice = input("What would you like? Espresso, Latte or Cappuccino?").lower()

            if coffeeChoice == "report":

                report()
            if coffeeChoice == "espresso" and ((resources['water'] < 50) or (resources['coffee'] < 18)):
                if r.lower() == "water" and water > resources[r]:
                    print("Sorry, there is not enough water.")
                if r.lower() == "coffee" and coffee > resources[r]:
                    print("Sorry, there is not enough coffee.")
            elif coffeeChoice == "espresso" and ((resources['water'] >= 50) and (resources['coffee'] >= 18)):
                resources['water'] = resources['water']-(((MENU['espresso'])['ingredients'])['water'])
                resources['coffee'] = resources['coffee'] - (((MENU['espresso'])['ingredients'])['coffee'])
                resources['money'] = resources['money'] - (((MENU['espresso'])['cost']))
                if resources['money'] > 0:
                    resources['money'] = round(resources['money'], 2)
                    print(f"Here is ${resources['money']} in change. ")
                print(f"Here is your {coffeeChoice}. Enjoy!")
                resources['money'] = resources['money']-resources['money']
            
if coffeeChoice == "latte" and ((resources['water'] < 200) or (resources['coffee'] < 24) or (resources['milk'] < 150)):
                if r.lower() == "water" and water > resources[r]:
                    print("Sorry, there is not enough water.")
                if r.lower() == "coffee" and coffee > resources[r]:
                    print("Sorry, there is not enough coffee.")
                if r.lower() == "milk" and milk > resources[r]:
                    print("Sorry, there is not enough milk.")
            elif coffeeChoice == "latte" and ((resources['water'] >= 200) and (resources['coffee'] >= 24) and (resources['milk'] >= 150)):
                resources['water'] = resources['water']-(((MENU['latte'])['ingredients'])['water'])
                resources['coffee'] = resources['coffee'] - (((MENU['latte'])['ingredients'])['coffee'])
                resources['milk'] = resources['milk'] - (((MENU['latte'])['ingredients'])['milk'])
                resources['money'] = resources['money'] - (((MENU['latte'])['cost']))
                if resources['money'] > 0:
                    resources['money'] = round(resources['money'], 2)
                    print(f"Here is ${resources['money']} in change. ")
                print(f"Here is your {coffeeChoice}. Enjoy!")
                resources['money'] = resources['money']-resources['money']
            
if coffeeChoice == "cappuccino" and ((resources['water'] < 250) or (resources['coffee'] < 24) or (resources['milk'] < 100)):
                if r.lower() == "water" and water > resources[r]:
                    print("Sorry, there is not enough water.")
                if r.lower() == "coffee" and coffee > resources[r]:
                    print("Sorry, there is not enough coffee.")
                if r.lower() == "milk" and milk > resources[r]:
                    print("Sorry, there is not enough milk.")
                print("Insufficient resources")
            elif coffeeChoice == "cappuccino" and ((resources['water'] >= 250) and (resources['coffee'] >= 24) and (resources['milk'] >= 100)):
                resources['water'] = resources['water']-(((MENU['cappuccino'])['ingredients'])['water'])
                print(f"{resources['water']}")
                resources['coffee'] = resources['coffee'] - (((MENU['cappuccino'])['ingredients'])['coffee'])
                resources['milk'] = resources['milk'] - (((MENU['cappuccino'])['ingredients'])['milk'])
                resources['money'] = resources['money'] - (((MENU['cappuccino'])['cost']))
                if resources['money'] > 0:
                    resources['money'] = round(resources['money'], 2)
                    print(f"Here is ${resources['money']} in change. ")
                print(f"Here is your {coffeeChoice}. Enjoy!")
                resources['money'] = resources['money']-resources['money']
            report()
            powerOff = input("Do you want to turn off the machine?: Y or N ").lower()
            if powerOff == 'y':
                power = False

Tags: andifislowermenutherecoffeeresources
1条回答
网友
1楼 · 发布于 2024-09-30 10:43:02

从错误中得出的问题是,在给变量赋值之前,尝试使用变量r。我已经在代码中强调了这一点。如果你喜欢,我可以添加一些修复

#Coffee ingredients and costs
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,
    }
}

#Coffee machine resources
resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money": 0
}

##                          -
# Loop through MENU to get the quantities of necessary ingredients to make a particular type of coffee
##                          -
## JonSG: This is not doing what you think it does.
## JonSG: The result of this is that water = 250 as only the last item's ingredients are set.
## JonSG: You probably don't need/want this code block
##                          -
for items in MENU:
    print(items)
    water = (((MENU[items])['ingredients'])['water'])
    coffee = (((MENU[items])['ingredients'])['coffee'])
    if items != 'espresso':
        milk = (((MENU[items])['ingredients'])['milk'])
##                          -

##                          -
# Function that loops through the resources dictionary to provide the current quantities of available resources
##                          -
## JonSG: You might want to think about passing resources into this function
## JonSG: so that is is not reliant on a global.
## JonSG: Additionally "r" is only meaningful inside the for loop so your return is going to error
## JonSG: You never assign a variable based on a call to report so the return can likely just be removed.
##                          -
def report():
    for r in resources:
        if r.lower() == "water":
            print(f'{r}: {resources[r]}'+"ml")
        if r.lower() == "milk":
            print(f'{r}: {resources[r]}'+"ml")
        if r.lower() == "coffee":
            print(f'{r}: {resources[r]}'+"g")
        if r.lower() == "money":
            print(f'{r}: ${resources[r]}')

    ## JonSG: probably don't need/want this
    return resources[r];
##                          -

global r
power = True

while power:
    print("Welcome to the coffee machine.")
    pennies = int(input("How many pennies did you insert?: "))
    nickles = int(input("How many nickles did you insert?: "))
    dimes = int(input("How many dimes did you insert?: "))
    quarters = int(input("How many quarters did you insert?: "))
    coinValue = (0.01*pennies)+(0.05*nickles)+(0.10*dimes)+(0.25*quarters)
    resources['money'] = resources['money']+coinValue
    coffeeChoice = input("What would you like? Espresso, Latte or Cappuccino?").lower()

    if coffeeChoice == "report":
        report()

    if coffeeChoice == "espresso" and ((resources['water'] < 50) or (resources['coffee'] < 18)):
        ##                          -
        ## At this point "r" has not been assigned a value so this is going to error out
        ##                          -
        if r.lower() == "water" and water > resources[r]:
            print("Sorry, there is not enough water.")
        if r.lower() == "coffee" and coffee > resources[r]:
            print("Sorry, there is not enough coffee.")
        ##                          -

    elif coffeeChoice == "espresso" and ((resources['water'] >= 50) and (resources['coffee'] >= 18)):
        resources['water'] = resources['water']-(((MENU['espresso'])['ingredients'])['water'])
        resources['coffee'] = resources['coffee'] - (((MENU['espresso'])['ingredients'])['coffee'])
        resources['money'] = resources['money'] - (((MENU['espresso'])['cost']))
        if resources['money'] > 0:
            resources['money'] = round(resources['money'], 2)
            print(f"Here is ${resources['money']} in change. ")
        print(f"Here is your {coffeeChoice}. Enjoy!")
        resources['money'] = resources['money']-resources['money']

    if coffeeChoice == "latte" and ((resources['water'] < 200) or (resources['coffee'] < 24) or (resources['milk'] < 150)):
        ##                          -
        ## At this point "r" has not been assigned a value so this is going to error out
        ##                          -
        if r.lower() == "water" and water > resources[r]:
            print("Sorry, there is not enough water.")
        if r.lower() == "coffee" and coffee > resources[r]:
            print("Sorry, there is not enough coffee.")
        if r.lower() == "milk" and milk > resources[r]:
            print("Sorry, there is not enough milk.")
        ##                          -

    elif coffeeChoice == "latte" and ((resources['water'] >= 200) and (resources['coffee'] >= 24) and (resources['milk'] >= 150)):
        resources['water'] = resources['water']-(((MENU['latte'])['ingredients'])['water'])
        resources['coffee'] = resources['coffee'] - (((MENU['latte'])['ingredients'])['coffee'])
        resources['milk'] = resources['milk'] - (((MENU['latte'])['ingredients'])['milk'])
        resources['money'] = resources['money'] - (((MENU['latte'])['cost']))
        if resources['money'] > 0:
            resources['money'] = round(resources['money'], 2)
            print(f"Here is ${resources['money']} in change. ")
        print(f"Here is your {coffeeChoice}. Enjoy!")
        resources['money'] = resources['money']-resources['money']

    if coffeeChoice == "cappuccino" and ((resources['water'] < 250) or (resources['coffee'] < 24) or (resources['milk'] < 100)):
        ##                          -
        ## At this point "r" has not been assigned a value so this is going to error out
        ##                          -
        if r.lower() == "water" and water > resources[r]:
            print("Sorry, there is not enough water.")
        if r.lower() == "coffee" and coffee > resources[r]:
            print("Sorry, there is not enough coffee.")
        if r.lower() == "milk" and milk > resources[r]:
            print("Sorry, there is not enough milk.")
        print("Insufficient resources")
        ##                          -

    elif coffeeChoice == "cappuccino" and ((resources['water'] >= 250) and (resources['coffee'] >= 24) and (resources['milk'] >= 100)):
        resources['water'] = resources['water']-(((MENU['cappuccino'])['ingredients'])['water'])
        print(f"{resources['water']}")
        resources['coffee'] = resources['coffee'] - (((MENU['cappuccino'])['ingredients'])['coffee'])
        resources['milk'] = resources['milk'] - (((MENU['cappuccino'])['ingredients'])['milk'])
        resources['money'] = resources['money'] - (((MENU['cappuccino'])['cost']))
        if resources['money'] > 0:
            resources['money'] = round(resources['money'], 2)
            print(f"Here is ${resources['money']} in change. ")
        print(f"Here is your {coffeeChoice}. Enjoy!")
        resources['money'] = resources['money']-resources['money']

    report()

    powerOff = input("Do you want to turn off the machine?: Y or N ").lower()
    if powerOff == 'y':
        power = False

以下是一些让您重新开始的想法:

##                          -
#Coffee ingredients and costs
##                          -
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,
    }
}
##                          -

##                          -
## Coffee machine resources
## Let's add in a little more data to make things easier later
##                          -
resources = {
    "water": {"quantity": 300, "unit_prefix": "", "unit_postfix": "ml"},
    "milk": {"quantity": 200, "unit_prefix": "", "unit_postfix": "ml"},
    "coffee": {"quantity": 100, "unit_prefix": "", "unit_postfix": "g"},
    "money": {"quantity": 0, "unit_prefix": "$", "unit_postfix": ""}
}
##                          -

##                          -
## Report on resources
##                          -
def report(resources):
    print("Resources Remaining:")
    for key, value in resources.items():
        print("\t%s: %s%s%s" % (key, value.get("unit_prefix"), value.get("quantity"), value.get("unit_postfix")))
##                          -

##                          -
## Refund the user's remaining credit
##                          -
def refund(resources):
    print("Here is $%s in change." % resources['money']["quantity"])
    resources['money']["quantity"] = 0
##                          -

while True:
    print("Welcome to the coffee machine.")
    print("You have credit of $%s" % resources["money"]["quantity"])

    pennies = int(input("How many pennies did you insert?: "))
    nickles = int(input("How many nickles did you insert?: "))
    dimes = int(input("How many dimes did you insert?: "))
    quarters = int(input("How many quarters did you insert?: "))

    coinValue = (0.01 * pennies) + (0.05 * nickles) + (0.10 * dimes) + (0.25 * quarters)
    resources['money']["quantity"] += coinValue

    coffeeChoice = input("Would you like? Espresso, Latte, Cappuccino, or Refund? ").lower()

    if coffeeChoice == "report":
        report(resources)
        continue

    if coffeeChoice == "refund":
        refund(resources)
        continue

    product_requested = MENU.get(coffeeChoice)

    if not product_requested:
        print(f"I do not have {coffeeChoice}.")
        continue

    if resources["money"]["quantity"] < product_requested["cost"]:
        print(f"Please insert more money to purchase {coffeeChoice}.")
        continue

    for ingredient, required_quantity in product_requested["ingredients"].items():
        # make sure we have enough stuff to make the request
        if required_quantity > resources[ingredient]["quantity"]:
            print(f"There is not enough {ingredient} to make {coffeeChoice}.")
            # a break here will stop the "for else" from happening
            break
    else:
        # everything seems go so let us vend
        resources["money"]["quantity"] -= product_requested["cost"]
        for ingredient, required_quantity in product_requested["ingredients"].items():
            resources[ingredient]["quantity"] -= required_quantity

        print(f"Here is your {coffeeChoice}.")
        if resources['money']["quantity"] > 0:
            refund(resources)

    if input("Do you want to turn off the machine?: Y or N ").lower() == "y":
        break

相关问题 更多 >

    热门问题