我如何获取用户输入并打印输入的每个单词 he/she 的字母数?

How can I grab the user inputs and print the letter count of each word he/she typed?

这是我目前所拥有的,但我被卡住了。

user_input = float(input('Welcome to the Amazing Word Program; how many words will you enter?'))

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

while word != '':
    my_list.append(word)
    word = input('Enter word:')

我的代码的重点是使用 while 循环。我们应该打印用户输入的单词的最终结果和每个单词的字母数。

这是我的程序的结果:

Welcome to the Amazing Word Program; how many words will you enter? 4
Enter word: apple
Enter word: orange
Enter word: strawberries
Enter word: kiwi
Enter word: 

用户输入4个单词后,还应该打印出每个单词的字母数。

这是一个完整的例子:

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

Word: Python Length: 6
Word: Python Length: 4
Word: Python Length: 3
Word: Python Length: 11

我是一名大学一年级学生,目前,while 循环看起来确实很难,所以如果这看起来是一个容易编写的代码,我深表歉意。

无论用户输入了多少个单词,我如何使用 while 循环打印出每个单词的长度?

PYTHON

您可以这样计算字符串的数量:

some_string = "hello world"

print(len(some_string))

当你可以像这样停止 while 循环时:

number = 0
while number <= 4:
    # do some work
    number += 1 # increment number

while 循环会在 number 命中 5 时自动停止。

您需要打印出您的输入。此外,您实际上不需要将单词保存到列表中,除非您之后要对列表进行操作。在这种情况下,您只是打印输入,因此您可以完全删除列表操作。

至于长度,Python 有一个 'len()' 函数,即 returns 给定输入的长度。

print('Welcome to the Amazing Word Program')

word = input('Enter word:')

while word != '':
    print("Word:", word, "Length:", len(word))
    word = input('Enter word:')

据我了解,您希望代码在用户输入所有单词后打印每个单词的长度...为此,我们首先需要捕获“my_list”列表的长度,我们通过创建一个 int 并设置长度值来实现:

listLen = len(my_list)

然后我们需要创建另一个int并将其值设置为0(我们将使用这个来计算要打印的单词长度并按顺序打印单词)

listNum = 0

现在我们创建一个 while 循环,直到 listNum 等于 listLen 值才会停止,为此我们将首先按升序打印单词长度:

while listNum != listLen:
  #While listNum (0) is not equal to listLen (number of words entered), it will loop again
  print( "Word", listNum, "length is:", len(my_list[listNum]) ) #Will print the length of the word number X (where X is the value of listNum that will be incremented 1 by 1 so we can print the length of each word 1 by 1 in ascending order)
  listNum += 1 #will increment 1 more value to the listNum, so the next loop will print the next word's length