if语句的函数

时间:2013-11-14 21:00:15

标签: python function printing

我不明白为什么这个功能不打印我想要打印的文字,我可以改变什么?

def shut_down(answer):
    if answer == "Yes" or "YES" or "yes":
        print "Shutting down..."
        return "Shutting down..."
    if answer == "No"or "NO" or "no":
        print "Shutdown aborted!"
        return "Shutdown aborted!"
    else: 
        print "Sorry, I didn't understand you."
        return "Sorry, I didn't understand you."



shut_down(yes)

5 个答案:

答案 0 :(得分:1)

我猜这种语言是Python。 or运算符在条件之间运行,因此您需要执行

answer == "yes" OR answer == "YES"

等......

您的回答==“是”或“是”始终为真,因为"YES"被视为真实条件。

答案 1 :(得分:1)

if answer.lower() == 'yes':

这就是你应该怎么做的。实际上,请执行此操作:if answer.lower() in ('yes', 'y'):以使像我这样的懒人更方便。

无论如何,检查字符串列表的正确方法是:

if answer in ('foo', 'bar', 'foobar'):

答案 2 :(得分:0)

以下内容不正确(if的正文始终执行):

if answer == "Yes" or "YES" or "yes":

相反,写一下

if answer in {"Yes", "YES", "yes"}:

if answer.lower() == "yes":

答案 3 :(得分:0)

您想将其更改为:

if answer == "Yes" or answer == "YES" or answer == "yes":
    print "Shutting down..."
    return "Shutting down..."

甚至更整洁:

if answer in ["Yes", "YES", "yes"]:

甚至是moar更整洁:

 if answer.lower() == "yes":

答案 4 :(得分:-1)

您的代码可能有错误,因为您没有在任何地方定义变量yes

定义它,然后你好。


我说的是你传递给shut_down函数的变量