Python if():vs if: [英] Python if( ): vs if:

查看:117
本文介绍了Python if():vs if:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Code Academy上有这样的课程,在这个例子中,他们展示了:

On Code Academy there is this course where in the example they show

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.")

以上示例将 NOT 与我展示的其他代码相关联。这只是如果语句的一个例子。现在我的印象是,如果写了 if 语句,它必须以():结尾,就像上面的例子。

The above example will NOT be related to the rest of the code I show. That was just an example for the if statement. Now I was under the impression that when ever writing an if statement it had to end in an ():like the above example.

然而当做这些任务时,这是行不通的:

However when doing the assignments this does not work:

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



However this works:

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

我的问题是,()不需要在no 但仍然需要。我认为每当写 if 语句时,它将自动以():结尾。在第一个例子中,它就是这样显示的。您是否理解我的困惑。

My question is how come the () is not needed next to the "yes" and "no" but :is still needed. I thought whenever writing an if statement it will automatically have to end with ():. In that very first example, that's how it is shown. Do you understand my confusion.

推荐答案

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

In the example given, happy() and sad() are functions, and as such require parentheses. The if itself does not need parentheses at the end (and it shouldn't have them)

这篇关于Python if():vs if:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆