问题描述
运行此代码时,我得到的输出是单词中字母的数量,而不是其具有的元音数量。
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()
 
 1楼
您的问题是:
 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()
 
 2楼
尝试这个:
码:
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()
 
  这是如何运作的:
通过使用集合,可以更快地查找集合中的字母。 同样,对字符串进行迭代还可以测试字符串中的每个字符,以查看其是否在元音集中。
3楼
 
     为什么不sum : 
word=input('Give me a word ')
print(sum(1 for i in word if i in 'aeiou'))
 
 4楼
>>> 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,这使它可以计算所有字符而不仅仅是元音。
5楼
 
     问题出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()