0

I wrote:

def is_vowel(letter:str) ->bool:
    """
    takes a one-character-long string and returns 
    True if that character is a vowel and False otherwise.
    """
    if letter in ['a' or 'A' or 'e' or 'E' or 'i' or 'I' or 'o' or 
                  'O' or 'u' or 'U']:
        return True

print(is_vowel('A'))

but it prints None. Why?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331

2 Answers2

5

Firstly, look at ('a' or 'A') in an interpreter. It will return 'a', so you were originally looking for character in a list with only one character: ['a']. That is because a string of length greater than zero evaluates to True in a boolean context, which the or created. or will return the first True-ish thing, in this case, 'a'.

I recommend for readability, use as in the following function, first take the lowercase version of the letter, then tell if it exists in a canonical representation of a string of all such characters, and just return the result of the test for membership. No need for if-then control-flow:

def is_vowel(letter: str) -> bool:
    """
    takes a one-character-long string and returns True if 
    that character is a vowel and False otherwise.
    """
    return letter.lower() in 'aeiou'

print(is_vowel( 'b'))

In Python 2,

def is_vowel(letter):
    """
    takes a one-character-long string and returns True if 
    that character is a vowel and False otherwise.
    """
    return letter.lower() in 'aeiou'

The reason you're getting None is because your function (a different version simplified below) doesn't return False if it doesn't return True. And when a function doesn't return anything specified, it returns None. So below is a version closer to yours that returns False if it doesn't return True.

def is_vowel(letter: str) -> bool:
if letter in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
    return True
else:
    return False

But I think this is better written:

def is_vowel(letter: str) -> bool:
    return letter in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']

Or as I did, above.

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
3

Use in keyword:

if letter in ['a', 'e', 'i', ...]:

EDIT: related question: How do I test one variable against multiple values?

Community
  • 1
  • 1
Andrew_Lvov
  • 4,621
  • 2
  • 25
  • 31