开发者

How to fix a Python elif?

Okay I have the below code performing something I don't want it to do. If you run the program it will ask you "How are you?" (obviously), but when you give a answer to the question that applies to the elif statement, I still get a if statement response. Why is this?

talk = raw_input("How are you?")
if "good" or "fine" in talk:
     print "Glad to here it..."
elif "bad" or "sad" or "terrib开发者_如何学Gole" in talk:
     print "I'm sorry to hear that!"


The problem is that the or operator does not do what you want here. What you're really saying is if the value of "good" is True or "fine" is in talk. The value of "good" is always True, since it's a non-empty string, which is why that branch always gets executed.


if "good" in talk or "fine" in talk is what you meant. What you wrote is equivalent to if "good" or ("fine" in talk).


Use a regular expression. What if the input is "I'm good. Well, i'm more fine. Sorry, i feel terrible, my bad." Then you'll have all conditions fulfilled and the output won't be what you expect.


talk = raw_input("How are you?")
if any(x in talk for x in ("good", "fine")):
     print "Glad to here it..."
elif any(x in talk for x in ("bad", "sad", "terrible")):
     print "I'm sorry to hear that!"

Note:

In [46]: "good" or "fine" in "I'm feeling blue"
Out[46]: 'good'

Python is grouping the condition like this:

("good") or ("fine" in "I'm feeling blue")

In terms of boolean values, that's equivalent to:

True or False

which is equal to

True

That's why the if-block is always getting executed.


You have to test each string separately, or test for inclusion in a list or tuple.

In your code, Python will take the value of your strings and test them for truth ("good"',"bad"' and "sad"' will returnTrue' as they're not empty), and then it will check if `"fine"' is in the characters of talk (because of the way the in operator works with strings).

You should do something like this:

talk = raw_input("How are you?")
if talk in ("good", "fine"):
     print "Glad to here it..."
elif talk in ("bad", "sad", "terrible"):
     print "I'm sorry to hear that!"


This worked for me:

talk = raw_input("How are you? ")
words = re.split("\\s+", talk)
if 'fine' in words:
    print "Glad to hear it..."
elif 'terrible' in words:
    print "I'm sorry to hear that!"
else:
    print "Huh?"

From reading the other answers, we'd have to expand the predicates for other words.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜