简体   繁体   中英

Python if( ): vs if:

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.

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)

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

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'

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM