Python if():vs if:

Kod*_*mes 0 python if-statement function

在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.")
Run Code Online (Sandbox Code Playgroud)

上面的例子将涉及到我显示代码的其余部分.这只是该if声明的一个例子.现在我的印象是,当写一个if声明时,它必须():像上面的例子一样结束.

但是,在执行分配时,这不起作用:

def shut_down(s):
    if s == "yes"():
        return "Shutting down"
    elif s == "no"():
        return "Shutdown aborted"
    else:
        return "Sorry"
Run Code Online (Sandbox Code Playgroud)

但是这有效:

def shut_down(s):
    if s == "yes":
        return "Shutting down"
    elif s == "no":
        return "Shutdown aborted"
    else:
        return "Sorry"
Run Code Online (Sandbox Code Playgroud)

我的问题是如何()不需要旁边"yes""no"但:仍然需要.我想每当写一个if声明时它都会自动结束():.在第一个例子中,它是如何显示的.你明白我的困惑吗? .

Ste*_*nTG 5

在给出的示例中,happy()并且sad()是函数,因此需要括号.在if本身并不在末尾括号需要(和它不应该有它们)