如何编写Python代码实现输入到“end”时停止并统计每个输入的元音数量
Hey there! I see you're trying to count vowels for each input line separately and output the results as space-separated numbers. Let's walk through what's off with your current code and how to fix it.
What's Wrong with the Current Code?
Your current count variable is initialized once outside the loop, so it's accumulating vowels from all inputs instead of resetting for each new line. Also, you aren't storing each individual count to output later—right now you'd only get a total if you uncomment the print statement.
Modified Code That Works
Here's the adjusted version that tracks each input's vowel count separately:
vowels = 'aeiouAEIOU' vowel_counts = [] # Store counts for each input here text = input() while text != "end": count = 0 # Reset count for each new input for char in text: if char in vowels: count += 1 vowel_counts.append(count) # Save this input's count text = input() # Print all counts separated by spaces print(' '.join(map(str, vowel_counts)))
How It Works
- We use a list
vowel_countsto keep track of the vowel count for every input line. - Inside the loop, we reset
countto 0 each time we get a new input—this ensures we only count vowels for the current line. - After counting vowels for the line, we add the count to our list.
- Once we exit the loop (when someone types "end"), we convert all numbers in the list to strings, join them with spaces, and print the result.
Example Test Run
Input:
I LOVE YOU TEST YOU END endOutput:
5 1 2
This matches exactly the example output you provided—each number corresponds to the vowel count of the input lines before "end".
内容的提问来源于stack exchange,提问作者Kholofelo

