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

Python如何使用while循环统计用户输入单词的字母长度

问题解决代码及说明

现有代码优化点

  • 第一行接收用户输入的单词数量时,不需要转换为float浮点型,应该转换为int整型,因为单词计数为整数
  • 目前你已经实现了用while循环收集用户输入的所有单词到my_list列表中,接下来只需要再写一个while循环遍历该列表,输出每个单词和对应长度即可
完整可运行代码
# 接收用户输入的单词数量,转成整型
word_count = int(input('Welcome to the Amazing Word Program; how many words will you enter?'))

my_list = []
word = input('Enter word:')

# 第一个while循环:收集用户输入的单词,输入空回车结束
while word != '':
    my_list.append(word)
    word = input('Enter word:')

# 第二个while循环:遍历列表输出单词和对应长度
index = 0
while index < len(my_list):
    current_word = my_list[index]
    print(f'Word: {current_word} Length: {len(current_word)}')
    index += 1
运行效果说明

运行后输入对应内容,输出示例如下:

Welcome to the Amazing Word Program; how many words will you enter? 4
Enter word: Python
Enter word: used
Enter word: for
Enter word: programming
Enter word: 

Word: Python Length: 6
Word: used Length: 4
Word: for Length: 3
Word: programming Length: 11

注:你给出的预期示例里所有输出的单词都写为Python属于示例笔误,上述代码会输出对应你输入的每个单词

如果想要严格限制用户输入的单词数量和最开始输入的数字一致,不需要用户输入空字符串结束,可以把第一个while循环调整为:

# 第一个while循环:按用户输入的数量收集单词
count = 0
while count < word_count:
    word = input('Enter word:')
    my_list.append(word)
    count += 1

这样用户输入够指定数量的单词后就会自动停止输入,直接输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:27:01