Python 检查变量的多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15851146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:10:13  来源:igfitidea点击:

Checking multiple values for a variable

pythonvariables

提问by Alexander Nilsson

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"

I want to check if a word starts with a vowel or consonant. However, this part does not work: if str(first) == "a" or "e" or "i" or "u" or "o"

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

So how would you check if the first letter is either "a" or "e" or "i" or "u" or "o"?

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

回答by Fernando Freitas Alves

You better use in

你最好用 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"

also you are doing it wrong, if you are trying to use OR clause you must use like this BUT it's not the better pythonic way:

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

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

回答by Yarkee

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

should moditied to

应该修改为

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

Python has a explicit demand on indent. Make sure you have a right indent.

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"