You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复TypeError错误:list indices must be integers or slices, not str

代码错误分析与修正

你的代码存在几个关键错误:

  • 变量被错误覆盖:你一开始将price_and_name定义为存储糖果名称与价格的字典,但在while True循环内,把它重新赋值成了小写名称的列表,直接破坏了原本的字典结构。后续计算总价时,你试图用字符串索引列表,自然会触发类型错误——列表仅支持数字索引。
  • 总价计算逻辑错误:计算总价时使用了+运算符,正确逻辑应该是价格乘以数量,需替换为*。
  • 重复打印糖果列表:每次循环都会重新打印所有糖果,完全没必要,应将打印代码移到循环外部,仅在程序启动时打印一次。
  • 冗余变量:定义了price_order列表但全程未使用,可直接删除。

修正后的完整代码

candy_name = ["Assorted Small Lollipops", "Assorted Flavours Small", "Assorted Flavours Large", "Large Lollipop", "100g Assorted Flavours Small", "100g Assorted Flavours Large", "Candy Cane", "100g Candy Canes"] # 所有糖果类型
candy_price = [0.1, 0.05, 0.2, 0.5, 4.5, 6, 0.2, 5.5] # 对应价格
total = 0
# 创建小写名称映射价格的字典,支持不区分大小写的用户输入
price_and_name = {name.lower(): price for name, price in zip(candy_name, candy_price)}
candy_order = []
number_order = []

# 仅打印一次可选糖果列表
for candies, price in zip(candy_name, candy_price):
    print(f"{candies} is ${price}")

while True:
    candy = input("What candy would you like to order? ").lower()

    while candy not in price_and_name:
        candy = input("That was not one of the options, check your spelling and try again. ").lower()
    candy_order.append(candy)
    
    number = input(f"How many {candy} would you like? ")
    while not number.isdigit() or int(number) <= 0:
        number = input("Only integers greater than 0 are allowed, please try again.")
    number_order.append(int(number))

    keep_ordering = input("Would you like to add more to your order? ").lower()
    while keep_ordering not in ["yes", "no"]:
        keep_ordering = input("Please enter just yes or no, try again. ").lower()

    if keep_ordering != "yes":
        for _candy, _number in zip(candy_order, number_order):
            total += price_and_name[_candy] * _number
        print(f"Your total is ${total:.2f}") # 保留两位小数,符合货币显示习惯
        break

核心修改点说明

  1. 重构price_and_name为小写名称键的字典,既兼容不区分大小写的输入,又能直接通过名称获取对应价格。
  2. 将糖果列表打印逻辑移至循环外,避免重复输出。
  3. 修正总价计算的运算符为*,还原正确的金额计算逻辑。
  4. 删除未使用的price_order变量,精简代码结构。
  5. 改用f-string格式化输出,提升代码可读性。

内容的提问来源于stack exchange,提问作者tham thmit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:36:27