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

如何在Python中获取单词长度并输出?代码无输出问题求助

解决单词长度无法输出的问题

现有代码的问题及修复

你的代码里已经用len(word)算出了单词长度,但没有输出这个结果——Python不会自动打印函数内部的计算值,必须显式调用输出操作。

修复方案有两种:

  • 直接在函数内打印结果:
def wordlength():
    word = "supercalifragilisticexpialidocious"
    print(len(word))  # 显式打印长度
wordlength()

执行后会输出34(这个单词的实际长度就是34)。

  • 让函数返回长度值,调用时再打印:
def wordlength():
    word = "supercalifragilisticexpialidocious"
    return len(word)  # 返回计算好的长度
print(wordlength())  # 打印函数返回的结果

用计数控制循环实现长度统计

如果不用内置的len()函数,手动通过计数循环统计的话,可以遍历单词的每个字符,每遍历一个就累加计数:

for循环版本(更简洁)

def wordlength():
    word = "supercalifragilisticexpialidocious"
    count = 0
    # 遍历单词的每个字符,每循环一次计数加1
    for _ in word:
        count += 1
    print(count)
wordlength()

while循环版本(典型的计数控制逻辑)

def wordlength():
    word = "supercalifragilisticexpialidocious"
    count = 0
    index = 0
    # 当索引没到单词末尾时,持续循环计数
    while index < len(word):
        count += 1
        index += 1
    print(count)
wordlength()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:47:36