-1

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?"
Patrick
  • 3
  • 3
  • 2
    define what *works* and *doesn't work* mean in your case. – Cristian Lupascu Feb 16 '15 at 09:42
  • What I _want_ is that when raw_input is yes or y, it prints Oh yeah! right now, every print output is Yes indeed! No matter if the input given at raw_input is n, no or No. – Patrick Feb 16 '15 at 09:45
  • then replace `answer == "yes" or "y"` with `answer in ["yes", "y"]` or what Padraic suggested in his answer – Cristian Lupascu Feb 16 '15 at 09:45
  • 1
    possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – André Laszlo Feb 16 '15 at 09:45

3 Answers3

3

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"):
Constantinius
  • 34,183
  • 8
  • 77
  • 85
0
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"}:
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Just started to teach myself python as first programming language so it still is gibberish to me. I don't understand the boolean stuff yet, but your answer worked as well indeed! Might have missed something at the first attempt - as expected. This time gives me the output I was looking for! – Patrick Feb 16 '15 at 10:01
  • @Patrick.no worries. I suggest you check this out http://anandology.com/python-practice-book/index.html – Padraic Cunningham Feb 16 '15 at 10:03
0

Change this:

answer == "Yes" or "y"

to:

answer == "Yes" or answer == "y"

or even:

answer in ("Yes", "y")
André Laszlo
  • 15,169
  • 3
  • 63
  • 81