PyCharm:应为'int| slice' got 'str'而不是错误

eiee3dmh  于 2023-05-06  发布在  PyCharm
关注(0)|答案(2)|浏览(257)

这是一个初学者的Python咖啡机程序,PyCharm控制台返回一个int|切片得到“字符串”错误。如何整改?

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

def price_calculator(q, d, n, p):
    return ((q*25) + (d*10) + (n*5) + (p*1))/100

money_available = 0

def coffee_machine(money):

    coffee_type = input("What would you like? espresso/latte/cappuccino:").lower()

    if coffee_type == 'report':
        print("Water:", MENU[resources['water']])
        print("Milk:", MENU[resources['milk']])
        print("Coffee:", MENU[resources['coffee']])
        print("Money: $", money)
        coffee_machine(money)

    elif coffee_type in ['espresso', 'cappuccino', 'latte']:
        print("Please Insert Coins.")
        quarters = int(input("How many quarters? "))
        dimes = int(input("How many dimes? "))
        nickles = int(input("How many nickles? "))
        pennies = int(input("How many pennies? "))
        price = price_calculator(quarters, dimes, nickles, pennies)
        if price >= int(MENU[coffee_type['cost']]):
            print(f"Here's your {coffee_type} ☕ and your change {int(MENU[coffee_type['cost']])-price}")
        elif price == MENU[coffee_type['cost']]:
            print("Sorry, that's not enough money. Money Refunded.")
        MENU[resources['water']] -= MENU[coffee_type['ingredients'['water']]]
        MENU[resources['milk']] -= MENU[coffee_type['ingredients'['milk']]]
        MENU[resources['coffee']] -= MENU[coffee_type['ingredients'['coffee']]]
        money += price
        coffee_machine(money)

coffee_machine(money_available)

这是我的代码。错误显示在第60-66行中存在“ingredients”、“water”、“milk”、“coffee”、“cost”的部分。是coffee_type变量导致了问题,还是修改了列表调用问题?因为我试过这些方法。

o75abkj4

o75abkj41#

应该不是一个困难的修复,你只需要重新排序你的括号在elif part!例如,这些行应该是:

MENU[resources['water']] -= MENU[coffee_type['ingredients']['water']]
MENU[resources['milk']] -= MENU[coffee_type['ingredients']['milk']]
MENU[resources['coffee']] -= MENU[coffee_type['ingredients']['coffee']]

也就是说,你只需要先把结束括号放在'ingredients'之后,下一个开始括号之前。

icnyk63a

icnyk63a2#

问题在于如何访问MENU字典中的值。访问嵌套字典时,需要使用多个方括号,还需要正确访问资源字典。以下是代码的更正版本,注解突出显示了更改:

def coffee_machine(money):

    coffee_type = input("What would you like? espresso/latte/cappuccino:").lower()

    if coffee_type == 'report':
        print("Water:", resources['water'])  # Access resources dictionary
        print("Milk:", resources['milk'])    # Access resources dictionary
        print("Coffee:", resources['coffee'])  # Access resources dictionary
        print("Money: $", money)
        coffee_machine(money)

    elif coffee_type in ['espresso', 'cappuccino', 'latte']:
        print("Please Insert Coins.")
        quarters = int(input("How many quarters? "))
        dimes = int(input("How many dimes? "))
        nickles = int(input("How many nickles? "))
        pennies = int(input("How many pennies? "))
        price = price_calculator(quarters, dimes, nickles, pennies)
        if price >= MENU[coffee_type]['cost']:  # Correct way to access cost
            print(f"Here's your {coffee_type} ☕ and your change {MENU[coffee_type]['cost'] - price}")
        elif price == MENU[coffee_type]['cost']:
            print("Sorry, that's not enough money. Money Refunded.")
        resources['water'] -= MENU[coffee_type]['ingredients']['water']  # Correct way to access ingredients
        resources['milk'] -= MENU[coffee_type]['ingredients']['milk']    # Correct way to access ingredients
        resources['coffee'] -= MENU[coffee_type]['ingredients']['coffee']  # Correct way to access ingredients
        money += price
        coffee_machine(money)

coffee_machine(money_available)

现在,您的代码应该可以运行,而不会出现上述错误。只要确保你有适当的条件来处理没有足够的资源(例如,水,牛奶,咖啡)来煮咖啡的情况。
由于您正在学习添加了一个更好的改进版本,可能会帮助您了解一些最佳实践

class CoffeeMachine:
    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,
    }

    def __init__(self):
        self.money = 0

    @staticmethod
    def price_calculator(q, d, n, p):
        return ((q * 25) + (d * 10) + (n * 5) + (p * 1)) / 100

    def report(self):
        print("Water:", self.resources['water'])
        print("Milk:", self.resources['milk'])
        print("Coffee:", self.resources['coffee'])
        print("Money: $", self.money)

    def get_coins(self):
        print("Please Insert Coins.")
        quarters = int(input("How many quarters? "))
        dimes = int(input("How many dimes? "))
        nickles = int(input("How many nickles? "))
        pennies = int(input("How many pennies? "))
        return self.price_calculator(quarters, dimes, nickles, pennies)

    def check_resources(self, coffee_type):
        for key in self.MENU[coffee_type]["ingredients"]:
            if self.MENU[coffee_type]["ingredients"][key] > self.resources[key]:
                print(f"Sorry, there is not enough {key}.")
                return False
        return True

    def make_coffee(self, coffee_type):
        if self.check_resources(coffee_type):
            price = self.get_coins()
            if price >= self.MENU[coffee_type]['cost']:
                print(f"Here's your {coffee_type} ☕ and your change ${(price - self.MENU[coffee_type]['cost']):.2f}")
                for key in self.MENU[coffee_type]["ingredients"]:
                    self.resources[key] -= self.MENU[coffee_type]["ingredients"][key]
                self.money += self.MENU[coffee_type]['cost']
            else:
                print("Sorry, that's not enough money. Money Refunded.")

    def run(self):
        while True:
            coffee_type = input("What would you like? espresso/latte/cappuccino/report:").lower()

            if coffee_type == "report":
                self.report()
            elif coffee_type in ["espresso", "latte", "cappuccino"]:
                self.make_coffee(coffee_type)
            else:
                print("Invalid input. Please try again.")

coffee_machine = CoffeeMachine()
coffee_machine.run()

在重构版本中,进行了以下更改:
班级结构:代码被重构到CoffeeMachine类中。这将咖啡机的功能及其内部状态(如资源和金钱)封装在类中。这有助于组织代码,使其更具可读性和可维护性。
单独方法:该功能被划分为单独的方法,每个方法负责一个特定的任务。这遵循了单一职责原则,使代码更加模块化,更容易理解。单独的方法是:
report():显示咖啡机中资源和资金的当前状态。price_calculator():根据硬币的数量计算插入的总金额。get_coins():提示用户输入硬币的数量并返回插入的总金额。check_resources():检查是否有足够的资源来制作所选的咖啡并返回一个布尔结果。make_coffee():处理制作咖啡的过程,并根据咖啡类型更新资源和资金。run():运行咖啡机的主循环,提示用户输入并执行相应的操作。将功能分离到各个方法中可以更轻松地进行调试、测试和代码维护。
字符串格式:在重构后的代码中,使用f字符串将更改量格式化为两位小数:价格从€ 1.00到€ 1.00不等。这提高了输出的可读性并确保了一致的格式。
无效的输入处理:添加了一个额外的else情况来处理来自用户的无效输入。这在run()方法中提供了更好的用户体验和错误处理。

相关问题