即使单词中有元音,我的代码也返回False

时间:2019-01-03 04:27:10

标签: python

程序和问题总结如下

Python 3.7.1版本

def has_vowel(s):
    '''(str) -> bool
    Retrun True only if s has atleast one vowel, not including y.
    >>> has_vowel('Anniversary')
    True
    >>> has_vowel('xyz')
    False
    '''

    vowel_found = False
    for char in s:
        if char in 'aieouAIEOU':
            return not vowel_found
        else:
            return vowel_found

预期结果

>>> has_vowel('Bhoot')
True

实际结果

>>> has_vowel('Bhoot')
False

1 个答案:

答案 0 :(得分:3)

您的函数遍历字符串中的每个值,但仅检查第一个值是否为元音,因为您在第一次迭代中return。您需要检查它是否存在于任何地方:

def has_vowel(s):
    '''(str) -> bool
    Retrun True only if s has atleast one vowel, not including y.
    >>> has_vowel('Anniversary')
    True
    >>> has_vowel('xyz')
    False
    '''

    for char in s:
        if char in 'aieouAIEOU':
            return True
    return False

else会立即使程序成为return,甚至认为它没有检查字符串的其余部分。

>>> has_vowel("Bhoot")
True
>>> has_vowel("xyz")
False