检查变量的多个值

时间:2013-04-06 12:48:13

标签: python variables

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = str(word)[0]
    print first
    if str(first) == "a" or "e" or "i" or "u" or "o":
        print "vowel"
else:
    print "consonant"

我想检查单词是否以元音或辅音开头。但是,此部分不起作用:如果str(first) == "a" or "e" or "i" or "u" or "o"

那你怎么检查第一个字母是“a”还是“e”或“i”或“u”还是“o”?

2 个答案:

答案 0 :(得分:7)

您最好使用in

    if len(original) and original.isalpha():
        word = original.lower()
        first = word[0]
        print first
        if first in ('a','e','i','o','u'):
            print "vowel"
        else:
            print "consonant"

你也做错了,如果你试图使用OR子句你必须使用这样但是它不是更好的pythonic方式:

 if first =='a' or first =='e' or first =='i' or first =='o' or first =='u':

答案 1 :(得分:1)

if str(first) == "a" or "e" or "i" or "u" or "o":

应该修改为

if str(first) in ("a", "e", "i", "o", "u"):

Python对缩进有明确的要求。确保你有一个正确的缩进。

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
    word = original.lower()
    first = str(word)[0]
    print first
    if str(first) in ("a", "e", "i", "o", "u"):
        print "vowel"
    else:
        print "consonant"