我正在尝试编写一个程序来计算 Python 中的元音和辅音,然后在两个语句中打印元音和辅音的数量。元音和辅音必须具有两种不同的功能。我已经完成了大部分内容,但我无法找出两个错误。
1.) 如何阻止我的脚本为每个元音计数打印一个新行。我尝试了多种累加器和打印语句,但似乎都不起作用。
2.) 我根本无法运行我的 countConsonants 函数。我假设我会遇到与第一个类似的问题,但我什至无法让它运行。我假设它与我从主函数调用函数的方式有关,但我不确定。
这是我的:
def main():
user_input = input("Enter a string of vowels and consonants: ")
vowel_list = set(['a','e','i','o','u'])
countVowels(user_input, vowel_list)
countConsonants(user_input, vowel_list)
def countVowels(user_input, vowel_list):
user_input.lower()
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
def countConsonants(user_input, vowel_list):
user_input.lower()
index = 0
consonants = 0
while index < len(user_input):
if user_input[index] not in vowel_list:
consonants += 1
index += 1
print ('Your input has' , consonants , 'consonants.')
main()
这是一个 IO:
Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.
最佳答案
缩进是关键。
打印只应在 while 循环完成后发生,因此它的缩进必须与 while 相同。索引的增量也在错误的位置:无论 if
条件是否为 True,每次都必须发生这种情况。 (根据您的对齐方式,索引只会增加过去的元音,并且可能永远无法让 while
循环结束;这就是为什么您永远不会 countConsonants
。)
您的 countVowels
函数将变为:
def countVowels(user_input, vowel_list):
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
顺便说一句,考虑在 user_input
中的字符上使用 for
循环,而不是 while
和索引;即使用类似的东西:
for char in user_input:
if char in vowel_list:
vowels += 1
关于python - 如何计算 Python 中的元音和辅音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164161/