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

如何避免Python计算单词长度平均值时出现除零错误?

除零错误原因

你当前代码的报错触发场景是用户未输入任何单词直接按回车结束输入,此时 allwords 为空列表,len(allwords) = 0,代码直接执行除法计算平均长度就会触发除零异常。

解决方案

在计算平均值前增加空列表判断逻辑,没有输入单词时直接提示、跳过除法计算即可,修改后的参考代码如下:

def main():
    allwords = []
    while True:
        words = input("Enter a line of words, press Enter to stop: ")
        if not words:
            break
        allwords.extend(words.split())
    # 新增空列表判断逻辑规避除零错误
    word_count = len(allwords)
    print("There were {} words".format(word_count))
    if word_count == 0:
        print("未输入有效单词,无法计算平均长度")
    else:
        average = sum(len(word) for word in allwords) / word_count
        print("Average word length {:.2f}".format(average))    
main()
额外优化说明
  • 原代码中统计单词数的打印用了{:.2f}格式,单词数为整数无需保留两位小数,上述代码同步做了调整
  • 原代码计算长度的生成器变量名words和外层输入变量重名,改为word避免命名歧义

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:24:07