You need to enable JavaScript to run this app. Python:如何修改现有代码实现1-1000数字的英文单词打印
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何修改现有代码实现1-1000数字的英文单词打印

1-1000数字英文打印的扩写方案

你现有的代码已经完整覆盖了1-99范围的英文打印逻辑,要扩展到1-1000的范围,只需要对齐英文数字的通用表达规则,补充百位段、1000的打印逻辑即可,不需要大改原有代码结构。

具体需要调整/补充的内容

  • 修正原有tens列表的拼写问题:把字符串'fourty'替换为正确拼写'forty',避免打印出错误单词。
  • 移除原代码最后单独打印"one hundred"的语句,这部分逻辑会整合到后面的百位循环中,避免重复打印。
  • 新增百位循环逻辑,按照原有代码的输出风格生成100-999范围的数字表达:
    1. 遍历1-9的百位基数(直接复用现有digits列表),依次生成每个整百的表达:比如one hundred、two hundred直到nine hundred,对应100、200…900这些整百数字。
    2. 对每个百位基数,依次拼接对应1-99的余数部分,用and连接在整百表达后面,对应101-199、201-299…901-999的带余数的数字。
  • 在所有百位段的内容打印完成后,单独补上1000的打印内容:print("one thousand")

调整后的完整可运行代码

digits = ['one', 'two',   'three', 'four', 'five', 
          'six', 'seven', 'eight', 'nine']

teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 
          'sixteen', 'seventeen', 'eighteen', 'nineteen']

tens = ['twenty', 'thirty', 'forty', 'fifty', 
          'sixty', 'seventy', 'eighty', 'ninety']

# 保留原有1-99的打印逻辑
for word in digits + teens:
    print(word)

for tens_word in tens:
    print(tens_word)        # e.g. twenty
    for digits_word in digits:
        print(tens_word, digits_word)   # e.g. twenty one

# 新增100-999范围的打印逻辑
for hundred_word in digits:
    # 打印整百数字(100、200...900)
    print(hundred_word, "hundred")
    
    # 打印百位带1-19余数的数字(101-119、201-219...901-919)
    for word in digits + teens:
        print(hundred_word, "hundred and", word)
    
    # 打印百位带20-99余数的数字
    for tens_word in tens:
        # 带整十余数的数字(120、130...990)
        print(hundred_word, "hundred and", tens_word)
        # 带个位余数的数字(121-129、131-139...991-999)
        for digits_word in digits:
            print(hundred_word, "hundred and", tens_word, digits_word)

# 打印1000
print("one thousand")

输出效果说明

调整后的代码会完全匹配你原有代码的输出格式,从1开始顺序打印到1000:

  • 1-99的输出和你现有代码的效果完全一致
  • 100以上的数字会自动带上对应百位前缀,比如115打印为one hundred and fifteen,235打印为two hundred and thirty five,999打印为nine hundred and ninety nine
  • 最后一行输出为one thousand

小提示:如果你更习惯美式英语的数字表达,可以把代码里所有的"hundred and"替换为"hundred",输出就会变为比如one hundred one的美式风格,不会改变其他代码逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 11:15:06