如何在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
相关产品推荐
相关产品推荐

