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)
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.
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'):
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":
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":
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
Related
I can't figure out why the following doesn't work.
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer == "Yes":
print "Yes indeed!"
elif answer == "yes" or "y":
print "Oh yeah!"
elif answer == "No":
print "No it isn't!"
elif answer == "no" or "n":
print "Not really!"
else:
print "Say what?"
When I remove the or, it does work. What am I doing wrong?
-edit-
I have it now, thanks a lot!
# Example
print "So, yes or no?"
answer = raw_input()
print answer
if answer in "Yes":
print "Yes indeed!"
elif answer in ("yes", "y"):
print "Oh yeah!"
elif answer in "No":
print "No it isn't!"
elif answer in ("no", "n"):
print "Not really!"
else:
print "Say what?"
One problem I see is this:
elif answer == "yes" or "y":
that literally translates to "if answer is yes or True" which always result in True.
You could write it like this:
elif answer in ("yes", "y"):
elif answer == "yes" or answer == "y":
elif answer == "No" or answer == "n":
Using elif answer == "yes" or "y": etc.. you are basically checking if bool("n") not comparing if answer is equal to "n" so your statements will always evaluate to True:
any non empty string will always evaluate to True:
In [38]: bool("n")
Out[38]: True
In [39]: bool("y")
Out[39]: True
In [40]: bool("")
Out[40]: False
You can also test for membership using in if you want to check against more than one value:
elif answer in {"yes", "y"}:
Change this:
answer == "Yes" or "y"
to:
answer == "Yes" or answer == "y"
or even:
answer in ("Yes", "y")
I'm new to Python and I am currently doing some work with IF statements.
This is what I have so far...
print("Hello")
myName = input("What is your name?")
print("Hello " +myName)
myAge = int(input("How old are you?"))
if myAge <=18:
myResponse = input("You must still be at school?")
if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
mySchool = input("What school do you go to?")
print (mySchool, "that is a good school I hear")
if myResponse == "No" or "n" or "N" or "NO":
print("Lucky you, you have lots of free time!")
if myAge >=19:
myResponse = input("You must have a job?")
if myResponse == "Yes" or "yes" or "YES" or "Y" or "yEs" or "y":
myWork = input("What do you do?")
print (myWork, "Thats a tough job")
if myResponse == "No" or "n" or "N" or "NO":
print("Lucky you, you have lots of free time!")
I want the user to be able to answer a question with a one word answer however have various options that would be recognized by the program for example "No", "NO" and "no" or "yes", "YES" and "Yes".
I have just figured out this way of doing it seen above but is there a better way it should be done?
Bare in mind I am new to this so it is probably a silly question.
Any help would be greatly appreciated.
Si
This condition checks that myRespone is either yes or "y" and is case insensitive (meaning that yes, YeS, and others are all valid)
myResponse.lower() in ["yes","y"]
The question asks specifically for answers in the form "yes" or "no" with different capitalizations ("y" or "n" are not mentioned). With that in mind, we can do as follows, being careful to remove any extra spaces:
if myresponse.strip().lower() == "yes":
# if yes, do something
And similarly:
if myresponse.strip().lower() == "no":
# if no, do something else
Try this:
if myResonse.lower() == "yes":
etc
With string functions:
if myResponse.upper() == 'NO':
# do something
Or:
if myResponse.lower() == 'no':
#do something
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
I'm learning python on codecademy and my current task is this:
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."
Seemed easy to me but somehow I still can't do it.
My code I made to test the function:
def shut_down(s):
if s == "Yes" or s == "yes" or s == "YES":
return "Shutting down..."
elif s == "No" or "no" or "NO":
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
i = input("Do you want to shutdown?")
print(i) #was to test the input
print(shut_down(i)) #never returns "Sorry, I didn't understand you"
It works fine for the no's and yes', but somehow if I put a space before any yes or even if I just type in "a" it prints "Shutdown aborted!" although it should print "Sorry, I didn't understand you".
What am I doing wrong?
You forgot to write s == "no" in your first elif:
def shut_down(s):
if s == "Yes" or s == "yes" or s == "YES":
return "Shutting down..."
elif s == "No" or "no" or "NO": # you forgot the s== in this line
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
Do 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": # fixed it
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
This is because:
elif s == "No" or "no" or "NO": #<---this
elif s == "No" or True or True: #<---is the same as this
Since this is the accepted answer I'll elaborate to include standard practices: The convention for comparing strings regardless of capitalization (equalsIgnoreCase) is to use .lower() like this
elif s.lower() == "no":
Instead of checking for different combinations of capitalization you could uses the lower function to return a copy of s in lowercase and compare against that.
def shut_down(s):
if s.lower() == "yes":
return "Shutting down..."
elif s.lower() == "no":
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
This is much cleaner and easier to debug. Alternatively you could use upper also and compare against "YES" and "NO".
If this doesn't help because of matching cases like nO then I'd go with the in statement:
def shut_down(s):
if s in ("yes","Yes","YES"):
return "Shutting down..."
elif s in ("no","No","NO"):
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
Python evaluates non empty strings to be True, so your elif condition is always evaluated to True.
>>> bool('No')
True
>>> bool('NO')
True
Doing a boolean or with a True value would always return True, so it never reaches the else condition and gets stuck on the elif one.
You need to test the conditions using.
elif choice == 'no' or choice == 'NO' or choice == 'No':
EDIT - As glglgl pointed out in the comment, == binds harder than or, so your condition gets evaluated as (s == 'No') or 'no' or 'NO' and not s == ('No' or 'no' or 'NO'), in which case you would have gotten to the else part even for a user input of 'NO'.
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."
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."
You can do it a couple of ways:
if s == 'Yes' or s == 'yes' or s == 'YES':
return "Shutting down..."
Or:
if s in ['Yes', 'yes', 'YES']:
return "Shutting down..."
Welcome to SO. I am going to walk through the answer, step-by-step.
s = raw_input ("Would you like to shut down?")
This asks if the user would like to shut down.
def shut_down(s):
if s.lower() == "yes":
print "Shutting down..."
elif s.lower() == "no":
print "Shutdown aborted!"
else:
print "Sorry, I didn't understand you."
This is probably new to you. If you have a string, and then .lower() it changes all input from s to lowercase. This is simpler than giving a list of all possibilities.
shut_down(s)
This calls the function.
def shut_down(s):
return ("Shutting down..." if s in("Yes","yes","YES")
else "Shutdown aborted!" if s in ("No","no","NO")
else "Sorry, I didn't understand you.")
GordonsBeard's idea is a good one. Probably "yEs" and "yES" etc are acceptable criteria;
Then I propose in this case:
def shut_down(s,d = {'yes':"Shutting down...",'no':"Shutdown aborted!"}):
return d.get(s.lower(),"Sorry, I didn't understand you.")
I know this doesn't exactly fit the specification but this is another common option which would catch a few more permutations:
def shut_down(s):
s = s.upper()
if s == "YES":
return "Shutting down..."
elif s == "NO":
return "Shutdown aborted!"
else:
return "Sorry, I didn't understand you."
def shut_down(phrase):
word = phrase
return word
take_action = input(shut_down('do you want to shutdown the program?: '.title()))
if take_action.lower() == 'yes':
print('Shutting down...')
elif take_action.lower() == 'no':
print('Shutdown aborted!')
else:
print('Sorry, I didn\'t understand you.')
I'm a python programmer and have finished Codecademy. I see that you have a problem and let me give you my answer. It runs perfectly
def shut_down(s):
if s == "yes":
return "Shutting down"
elif s == "no":
return "Shutdown aborted"
else:
return "Sorry"
You can try this code:
def shut_down(s):
if s =="yes":
return "Shutting Down"
elif s =="no":
return "Shutdown aborted"
else:
return "Sorry"
print shut_down("yes")
The code from the user 'grc' posted here, almost worked for me. I had to tweak the return message to get it right.
If the message (meaning all returned strings) are not exactly the same as described on Codecademy, then the workspace will not validate your response.
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"
from sys import exit
def answer():
answer = raw_input("> ")
if answer == "Yes" or answer == "yes":
#going to next
joint()
elif answer == "No" or answer == "no":
print "You still have something, I know..."
again()
else:
fubar()
def again():
again = raw_input("> ")
if again == "Yes" or again == "yes":
#going to next
joint()
elif again == "No" or again == "no":
print "You still have something, I know..."
else:
fubar()
def fuck():
print "Fubar'd!"
def joint():
print "To be continue..."
def question():
print "Hi duuuude..."
raw_input("To say 'Hi' press Enter")
print "Can you help me?"
answer()
question()
Hi, can you help me with this? I`m trying to repeat the function "answer", when I get answer "NO". Im want to escape function "again"... And also is there a way to escape "answer == "Yes" or answer == "yes": " so no matter I write capital or small letter to accept the answer and not to write like a noob "Yes" or "yes"?
This is usually achieved with a while loop.
Edit: As pointed out, while loops are nice and clear, and avoid recursion limits.
Never thought a simple answer would generate so many votes....
Lets give you an example
while True:
ans = raw_input("Enter only y or n to continue").strip().lower()
if ans == "y":
print "Done!"
break
elif ans == "n":
print "No?"
else:
print "Not valid input."
The simplest solution to your problem is remove your again function, and recurse:
def answer():
ans = raw_input("> ")
if ans == "Yes" or ans == "yes":
#going to next
joint()
elif ans == "No" or ans == "no":
print "You still have something, I know..."
answer() # again()
else:
fubar()
I had to rename your answer variable to ans so that it didn't clash with the function name.
For the second question, you want either:
if answer.lower() == "yes":
or
if answer in ("Yes", "yes"):