Reputation: 53
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.")
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"
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.
Upvotes: 0
Views: 615
Reputation: 71570
Because string objects are not callable so what are you expecting then:
Then use lambda
not that efficient tho:
def shut_down(s):
if (lambda: s == "yes")():
return "Shutting down"
elif (lambda: s == "no")():
return "Shutdown aborted"
else:
return "Sorry"
Upvotes: 0
Reputation: 27133
No, if
has nothing to do with ()
happy
is a function. happy()
is a call to that function. So, if happy():
tests if the happy
function returns true when called.
In other words, if happy(): speak("I'm happy!")
is equivalent to
result_of_happy = happy()
if result_of_happy:
speak("I'm happy!")
Upvotes: 4
Reputation: 1951
As has been mentioned happy() / sad()
are functions so they require ()
. In example two of your question you are comparing your value to the string "yes"
because it is a string it does not require ()
.
Within an if
statement you can use parentheses to make the code more readable and ensure certain operations are evaluated before others.
if (1+1)*2 == 4:
print 'here'
else:
print 'there'
Differs from:
if 1+1*2 == 4:
print 'here'
else:
print 'there'
Upvotes: 2
Reputation: 2647
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)
Upvotes: 5