Python While 使用元组循环



我正在编写一个函数,该函数应该计算输入短语中的数字。该短语存储为元组,while 循环应计算元音数。到目前为止,我已经得到了这个。

def whilephrase():
    vowels=['A','a','E','e','I','i','O','o','U','u']
    print('Please give me a phrase')
    inputphrase=input()
    inputphrase=tuple(inputphrase)
    i=0
    while True:
        if vowels in inputphrase:
            i=i+1
        else:
            print(i)

但这只会打印出一个无穷无尽的零循环。

您需要遍历输入短语:

for character in inputphrase:
    if character in vowels:
        i = i + 1
print(i)

但是,当然,有一种更简单的方法:

def count_vowels(string):
    return sum(1 for c in string if c.lower() in "aeiou")

编辑:使用 while 循环(虽然我不确定你为什么特别想要):

index = 0
i = 0
while index < len(inputphrase):
    if inputphrase[index] in vowels:
        i += 1
    index += 1
print(i)
print len([i for i in inputphrase if i in vowels])

你也可以使用collections

from collections import Counter
sum([Counter(inputphrase)[i] for i in vowels])

最新更新