python - 如何计算 Python 中的元音和辅音?

标签 python

我正在尝试编写一个程序来计算 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/

相关文章:

python - 循环中的循环 Python

python - 如何从用户那里获取多行输入

python - 更新记录时发生 Django IntegrityError

python - 从 Python 中的路径获取文件名?

Photoshop 的 Python 脚本 - resizeImage 未按预期工作

Python 记录器忽略类中的 FileHandler 和 StreamHandler 级别

python - 使用 optimize.fmin_l_bfgs_b 进行参数误差估计

python - 将作为另一个列表元素的列表元素从字符串转换为整数

python - 如何返回 3D 数组中的 Scikit 图像分割?

python - 在 Mac 上升级到 Python 2.6.5