【发布时间】: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 语句时,它都会自动以():。在第一个示例中,就是这样显示的。你明白我的困惑吗?
【问题讨论】:
-
看来您对functions 和
ifstatements 存在根本性的误解。 -
快乐和悲伤大概是functions
-
@chrisaycock 我认为您正在考虑与 OP 不同的任务
标签: python function if-statement