Cannot determine vowels from consonants

前端 未结 5 1693
北恋
北恋 2021-01-07 00:28

With the code below, no matter what the first letter of the input is, it is always determined as a vowel:

original = raw_input(\"Please type in a word: \")
f         


        
5条回答
  •  渐次进展
    2021-01-07 00:41

    First you should know how or works, it evaluates both the left and right expression and it returns the first expression that evaluates true, otherwise it returns the last expression:

    From this source you can see that all of these evaluate false:

    • None
    • False
    • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
    • any empty sequence, for example, '', (), [].
    • any empty mapping, for example, {}.
    • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False.3.1

    >>> False or True
    True
    >>> '' or False
    False
    >>> '' or 0
    0
    

    So a non-empty string will evaluate as true and it will be returned:

    >>> 'abc' or False
    'abc
    

     if firstLetter == "a" or "e" or "i" or "o" or "u":
         print "vowel"
     else:
         print "consonant"
    

    For a string 'foo', 'f' is the first letter. In the first part of your code, firstLetter == "a" or "e", the left expression will evaluate as false, but 'e' is not an empty string so it evaluates as true and it will print "vowel"

    You can see my other answer here which answers your question, something like this:

    if c.upper() in "AEIOU"
    

    will check if a letter is a vowel.

提交回复
热议问题