代码输出字数而不是元音数

时间:2018-09-23 05:52:38

标签: python python-3.x

运行此代码时,我得到的输出是单词中字母的数量,而不是其具有的元音数量。

main():
    word = str(input('Give me a word '))
    vowels = 0
    i = 0
    while i < len(word):
        if word[i] == "o" or "i" or "e" or "u" or "a":
            vowels += 1
            i += 1
    print('Number of vowels is: ' + str(vowels))

main()

5 个答案:

答案 0 :(得分:2)

您的问题在于:

if word[i] == "o" or "i" or "e" or "u" or "a":

基本上,您只检查word[i] == "o"。您需要像这样提供所有支票:

您需要像这样对word[i]进行多次检查:

if word[i] == "o" or word[i] == "i" or word[i] == "e" or word[i] == "u" or word[i] == "a":

因此您的函数应如下所示:

def main():
    word = str(input('Give me a word '))
    vowels = 0
    i = 0
    while i < len(word):
        if word[i] == "o" or word[i] == "i" or word[i] == "e" or word[i] == "u" or word[i] == "a":
            vowels += 1
        i += 1
    print('Number of vowels is: ' + str(vowels))
main()

答案 1 :(得分:1)

尝试一下:

代码:

def main():
    word = input('Give me a word ')
    vowel_count = sum(ch in set("aeiou") for ch in word)
    print('Number of vowels is: {}'.format(vowel_count))

main()

工作原理:

通过使用集合,查找字母是否在集合中会更快。同样,对字符串进行迭代还可以测试字符串中的每个字符,以查看其是否在元音集中。

答案 2 :(得分:1)

为什么不sum

word=input('Give me a word ')
print(sum(1 for i in word if i in 'aeiou'))

答案 3 :(得分:1)

>>> def main():
...   word = str(input('Give me a word ')).lower()
...   return sum([word.count(x) for x in ['a','e','i','o','u']])
...
>>> main()
Give me a word This is a test string
5
>>>

尝试一下。 您的代码的问题在于,仅当找到元音时,它才会递增“ i”。另一个问题是

>>> bool('i')
True
>>> bool('o')
True

'i'和'o'以及其他字符本身为True,因此对所有字符都为true,这使它可以计算所有字符而不仅仅是元音。

答案 4 :(得分:1)

问题出在if word[i] == "o" or "i" or "e" or "u" or "a":

您只能判断是否为“ o”,然后if word[i] == "o" or "i" or "e" or "u" or "a":总是正确。因此,每个单词都算作vowels

您的原始代码陷入死循环,请在下面关注我的提示

您应该更改为:

while i < len(word):
    if word[i] == "o" or word[i] == "i" or word[i] == "e" or word[i] == "u" or word[i] == "a"::
        vowels += 1
    i += 1 #btw you get dead-loop here on your origin code

但是最好的方法是:

def main():
    word = str(input('Give me a word '))
    vowels = 0
    i = 0
    while i < len(word):
        if word[i].lower() in ["o","i","e","u","a"]:
            vowels += 1
        i += 1
    print('Number of vowels is: ' + str(vowels))

main()
相关问题