【问题标题】:Python if( ): vs if:Python if(): 与 if:
【发布时间】:2015-10-21 00:03:10
【问题描述】:

在 Code Academy 上有这门课程,在他们展示的示例中

def speak(message):
    return message

if happy():
    speak("I'm happy!")
elif sad():
    speak("I'm sad.")
else:
    speak("I don't know what I'm feeling.")

上面的示例将与我展示的其余代码相关。这只是if 语句的一个示例。现在我的印象是,在编写 if 语句时,它必须以 (): 结尾,就像上面的示例一样。

但是在做作业时这不起作用:

def shut_down(s):
    if s == "yes"():
        return "Shutting down"
    elif s == "no"():
        return "Shutdown aborted"
    else:
        return "Sorry"

但这是可行的:

def shut_down(s):
    if s == "yes":
        return "Shutting down"
    elif s == "no":
        return "Shutdown aborted"
    else:
        return "Sorry"

我的问题是为什么 () 不需要在 "yes""no" 旁边但仍然需要 :。我想每当编写 if 语句时,它都会自动以():。在第一个示例中,就是这样显示的。你明白我的困惑吗?

【问题讨论】:

标签: python function if-statement


【解决方案1】:

在给出的示例中,happy()sad() 是函数,因此需要括号。 if 本身在末尾不需要括号(也不应该有括号)

【讨论】:

    【解决方案2】:

    不,if()无关

    happy 是一个函数。 happy() 是对该函数的调用。因此,if happy(): 测试 happy 函数在调用时是否返回 true。

    换句话说,if happy(): speak("I'm happy!") 等价于

    result_of_happy = happy()
    if result_of_happy:
        speak("I'm happy!")
    

    【讨论】:

      【解决方案3】:

      如前所述,happy() / sad() 是函数,因此它们需要()。在您的问题的示例二中,您将您的值与字符串 "yes" 进行比较,因为它是一个不需要 () 的字符串。

      if 语句中,您可以使用括号使代码更具可读性,并确保某些操作在其他操作之前被评估。

      if (1+1)*2 == 4:
          print 'here'
      else:
          print 'there'
      

      不同于:

      if 1+1*2 == 4:
          print 'here'
      else:
          print 'there'
      

      【讨论】:

        【解决方案4】:

        因为字符串对象是不可调用的,所以你期待什么:

        然后使用lambda 不是那么有效:

        def shut_down(s):
            if (lambda: s == "yes")():
                return "Shutting down"
            elif (lambda: s == "no")():
                return "Shutdown aborted"
            else:
                return "Sorry"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-06
          • 2015-09-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-10
          相关资源
          最近更新 更多