Frank
Frank

Reputation: 349

Return True if no character in String s is a vowel in Python

I've tried looking for answers but none seem to help. I've done:

def noVowel(s):
    'return True if string s contains no vowel, False otherwise'
    for char in s:
        if char.lower() not in 'aeiou':
            return True
        else:
            return False

No matter the string, it always returns True.

Upvotes: 0

Views: 5729

Answers (2)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

With any and short circuiting properties:

def noVowel(s):
    return not any(vowel in s.lower() for vowel in "aeiou")

Upvotes: 3

turbulencetoo
turbulencetoo

Reputation: 3681

You've almost got it right, but the problem is, as soon as you see a character that is a non-vowel, you return True right then and there. You want to return True after you've made sure that all are non-vowel:

def noVowel(s):
    'return True if string s contains no vowel, False otherwise'
    for char in s:
        if char.lower() in 'aeiou':
            return False
    return True  # We didn't return False yet, so it must be all non-vowel.

It's important to remember that return stops the rest of the function from running, so only return if you're sure the function is done computing. In your case, we can safely return False once we see a vowel, even if we didn't check the whole string.

Upvotes: 5

Related Questions