You need to enable JavaScript to run this app. Python用if-else实现0-999整数转英文出现IndexError的求助
优惠活动
大模型
产品
解决方案
定价
更多

Python用if-else实现0-999整数转英文出现IndexError的求助

报错原因拆解

触发IndexError的核心逻辑漏洞是三位数分支的索引计算错误:
当输入数值大于99时,代码直接用n//10计算要取的十位列表索引——比如输入136时,136//10的结果是13,而words_for_tens列表的有效索引仅为0-9,用超范围的索引取值自然会抛出越界错误。

除了直接触发报错的问题,原代码还存在3个隐含缺陷:

  • 词汇拼写错误:words_upto_19里的therteen是拼写错误(正确为thirteen),words_for_tens里的fourty是拼写错误(正确为forty)
  • 规则适配错误:当三位数的后两位数值在1-19区间(比如116),按原逻辑会直接取整十位置的空值,无法正确拼接出对应英文表达
  • 输出格式问题:拼接字符串时不会跳过空值,遇到整百类数值(比如200)会输出大量连续冗余空格,格式不整洁
可直接运行的修复版本

核心调整思路是拆分数值结构,复用0-99区间的判断逻辑,避免硬算超出列表范围的索引:

words_upto_19 = ['', 'one', 'two', 'three','four', 'five', 'six','seven', 'eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
words_for_tens = ['', '', 'twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
words_for_hundred = ['','one hundred','two hundred', 'three hundred','four hundred', 'five hundred', 'six hundred','seven hundred', 'eight hundred','nine hundred']

n = int(input("Enter a number between 0 to 999:"))

output = ''

if n > 999:
    output = 'Entered value is more than 999!'
elif n == 0:
    output = 'zero'
else:
    # 拆分百位部分
    hundred_digit = n // 100
    remainder = n % 100
    # 拼接百位词汇
    if hundred_digit > 0:
        output += words_for_hundred[hundred_digit]
    # 处理后两位的数值,逻辑和0-99判断一致
    if 0 < remainder <= 19:
        output += ' ' + words_upto_19[remainder]
    elif remainder > 19:
        tens_digit = remainder // 10
        unit_digit = remainder % 10
        output += ' ' + words_for_tens[tens_digit]
        if unit_digit > 0:
            output += ' ' + words_upto_19[unit_digit]
# 清理首尾多余空格
output = output.strip()

print(output)
修复后的效果
  • 输入136:正常输出one hundred thirty six,不再触发索引越界
  • 输入200:正常输出two hundred,无冗余空格
  • 输入116:正常输出one hundred sixteen,匹配英文数字表达规则
  • 输入超过999的数值:正常输出提示文字

内容的提问来源于stack exchange,提问作者Safa Abc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.26 14:45:10