user2989433
user2989433

Reputation: 53

Function with if statements

I don't understand why this function doesn't print the text I want it to print, what could I change?

def shut_down(answer):
    if answer == "Yes" or "YES" or "yes":
        print "Shutting down..."
        return "Shutting down..."
    if answer == "No"or "NO" or "no":
        print "Shutdown aborted!"
        return "Shutdown aborted!"
    else: 
        print "Sorry, I didn't understand you."
        return "Sorry, I didn't understand you."



shut_down(yes)

Upvotes: 0

Views: 72

Answers (5)

Shiny
Shiny

Reputation: 121

You want to change it to this:

if answer == "Yes" or answer == "YES" or answer == "yes":
    print "Shutting down..."
    return "Shutting down..."

Or even tidier:

if answer in ["Yes", "YES", "yes"]:

or even moar tidier:

 if answer.lower() == "yes":

Upvotes: 0

qwertynl
qwertynl

Reputation: 3933

You code probably has an error because you do not have the variable yes defined anywhere.

Define it, and then you should be good.


I am talking about the variable you are passing to your shut_down function

Upvotes: -1

NPE
NPE

Reputation: 500267

The following is not correct (the body of the if always executes):

if answer == "Yes" or "YES" or "yes":

Instead, write

if answer in {"Yes", "YES", "yes"}:

or

if answer.lower() == "yes":

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318488

if answer.lower() == 'yes':

That's how you should do it. Actually, do this: if answer.lower() in ('yes', 'y'): to make it more convenient for lazy people like myself.

Anyway, the proper way to check for a list of strings is this:

if answer in ('foo', 'bar', 'foobar'):

Upvotes: 1

mb14
mb14

Reputation: 22596

I guess the language is Python. The or operator operate between conditions, so you need to do

answer == "yes" OR answer == "YES"

etc ....

Your answer == "Yes" Or "YES" is always true because "YES" is considered as an true condition.

Upvotes: 1

Related Questions