Python' if'声明没有正确触发

时间:2016-03-27 06:55:31

标签: python if-statement

出于某种原因,无论user_input是什么(是,否,"",eserw3),将始终触发第一个if语句。有关为什么elif和其他人永远不会被激活的任何见解? (以下代码完美编译,没有任何错误)

提前谢谢。

def retry():
        user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
        if user_input == "Yes" or "yes":
            respawn()
            getMove()
        elif user_input == "No" or "no":
            print "Thanks for playing!"
        else:
            print "Please enter either Yes or No."

3 个答案:

答案 0 :(得分:0)

def retry():
    user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy)).lower()
    if user_input == "yes":
        respawn()
        getMove()
    elif user_input == "no":
        print "Thanks for playing!"
    else:
        print "Please enter either Yes or No."

答案 1 :(得分:0)

def retry():
        user_input = raw_input("Would you like to face %s again? (Yes/No)" % (Enemy))
        if user_input == "Yes" or user_input == "yes":
            respawn()
            getMove()
        elif user_input == "No" or user_input == "no":
            print "Thanks for playing!"
        else:
            print "Please enter either Yes or No."

答案 2 :(得分:-1)

将您的if条件更改为

user_input in ["Yes", "yes"]

原因:当您编写user_input == "Yes" or "yes"时,其评估为:

(user_input == "Yes") or "yes"

OR的第二部分总是True(非零长度字符串)。因此,if block始终执行问题。