Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions and if - else in python. Mutliple conditions. Codeacademy

Write a function, shut_down, that takes one parameter (you can use anything you like; in this case, we'd use s for string).

The shut_down function should return "Shutting down..." when it gets "Yes", "yes", or "YES" as an argument, and "Shutdown aborted!" when it gets "No", "no", or "NO". If it gets anything other than those inputs, the function should return "Sorry, I didn't understand you."

The code I wrote so far is below. It makes errors, e.g. given "No" as the argument, it does not return "Shutdown aborted!" as expected.

def shut_down(s):
    if s == "Yes" or "yes" or "YES":
        return "Shutting down..."
    elif s == "No" or "no" or "NO":
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
like image 970
user2121992 Avatar asked Mar 01 '13 02:03

user2121992


1 Answers

This:

s == "Yes" or "yes" or "YES"

is equivalent to this:

(s == "Yes") or ("yes") or ("YES")

Which will always return True, since a non-empty string is True.

Instead, you want to compare s with each string individually, like so:

(s == "Yes") or (s == "yes") or (s == "YES")  # brackets just for clarification

It should end up like this:

def shut_down(s):
    if s == "Yes" or s == "yes" or s == "YES":
        return "Shutting down..."
    elif s == "No" or s == "no" or s == "NO":
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."
like image 112
grc Avatar answered Oct 13 '22 00:10

grc