如何修复Python elif?
好的,我有下面的代码执行一些我不希望它做的事情。如果你运行这个程序,它会问你“你好吗?”(很明显),但是当你回答适用于elif语句的问题时,我仍然会得到If语句的响应。为什么会这样如何修复Python elif?,python,Python,好的,我有下面的代码执行一些我不希望它做的事情。如果你运行这个程序,它会问你“你好吗?”(很明显),但是当你回答适用于elif语句的问题时,我仍然会得到If语句的响应。为什么会这样 talk = raw_input("How are you?") if "good" or "fine" in talk: print "Glad to here it..." elif "bad" or "sad" or "terrible" in talk: print "I'm sorry
talk = raw_input("How are you?")
if "good" or "fine" in talk:
print "Glad to here it..."
elif "bad" or "sad" or "terrible" in talk:
print "I'm sorry to hear that!"
如果你说的是“好”还是“好”
。如果你的意思是“好”或“好”,那么你写的东西就相当于
如果你的意思是“好”或“好”。你写的东西相当于,如果在谈话中是“好”还是(“好”)
注:
Python将条件分组如下:
("good") or ("fine" in "I'm feeling blue")
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!"
就布尔值而言,这相当于:
True or False
这等于
True
这就是为什么if块总是被执行的原因
注:
Python将条件分组如下:
("good") or ("fine" in "I'm feeling blue")
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!"
就布尔值而言,这相当于:
True or False
这等于
True
这就是为什么总是执行if块。使用正则表达式。如果输入是“我很好。嗯,我比较好。对不起,我感觉糟透了,我的糟糕。”
然后您将满足所有条件,并且输出将不是您所期望的。使用正则表达式。如果输入是“我很好。嗯,我比较好。对不起,我感觉糟透了,我的糟糕。”
然后,您将满足所有条件,并且输出将不是您期望的。问题在于
或
运算符没有执行您在此处希望执行的操作。你真正想说的是如果“good”的值是真的,或者“fine”的值在谈话中
。“good”的值总是真的,因为它是一个非空字符串,这就是为什么该分支总是被执行。问题在于或
操作符没有执行您想要的操作。你真正想说的是如果“good”的值是真的,或者“fine”的值在谈话中
。“good”的值总是真的,因为它是一个非空字符串,这就是为什么该分支总是被执行的原因。您必须单独测试每个字符串,或者测试是否包含在列表或元组中
在您的代码中,Python将获取字符串的值并测试它们的真实性(“good”、
“bad”和“sad”将返回True”,因为它们不是空的),然后它将检查talk的字符中是否有“fine”(因为In操作符处理字符串的方式)
你应该这样做:
("good") or ("fine" in "I'm feeling blue")
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!"
您必须分别测试每个字符串,或者测试是否包含在列表或元组中
在您的代码中,Python将获取字符串的值并测试它们的真实性(“good”、
“bad”和“sad”将返回True”,因为它们不是空的),然后它将检查talk的字符中是否有“fine”(因为In操作符处理字符串的方式)
你应该这样做:
("good") or ("fine" in "I'm feeling blue")
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!"
这对我很有用:
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?"
通过阅读其他答案,我们必须扩展其他单词的谓词。这对我很有用:
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?"
通过阅读其他答案,我们必须扩展其他单词的谓词。这将排除OP的代码将捕获的所有类型的字符串。@aaronasterling,您想解释一下吗?它在Ubuntu10.10Python2.6.6中工作。当然,它只进行严格的匹配。这将排除OP的代码将捕获的所有类型的字符串。@aaronasterling,您想解释一下吗?它在Ubuntu10.10Python2.6.6中工作。当然,它只做严格的匹配。如果谈话中的“好”和谈话中的“糟糕”:打印“下定决心”如果这是输入,你认为会发生什么?正则表达式在这里太过分了。如果在谈话中“好”而在谈话中“糟糕”:打印“下定决心”如果这是输入,你认为应该发生什么?正则表达式在这里太过分了。