Python真/假和在

时间:2012-06-17 06:24:41

标签: python python-2.7

如果有这样的字母/单词,我试图打印出来,如果没有,我打算打印出来,如果没有,我会打印出来,但无论我输入什么内容,都是真的。

phr1= raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2= raw_input("Check if a word/letter exists in the paragraph: ")
phr2 in phr1
if True:
    print "true"
elif False:
    print "false"
input("Press enter")

当我运行代码时:

Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph:
hello world
You entered: hello world
Check if a word/letter exists in the paragraph: g
true
Press enter

这怎么可能,不存在,为什么会这样呢?

4 个答案:

答案 0 :(得分:6)

检查if True将始终通过,因为正在评估的布尔表达式只是True。将整个if / else更改为print (phr2 in phr1)

如果第二个短语位于第一个短语,则会打印“True”,否则为“False”。要使其为小写(无论出于何种原因),您可以使用.lower(),详见下面的评论。

如果您想使用原始的if / else检查(优点是您的输出消息可能比“True”/“False”更有创意),您必须修改代码,例如这样:

if phr2 in phr1:
    print "true"
else:
    print "false"
input("Press enter")

答案 1 :(得分:1)

if <something>

表示它所说的内容:如果<something>为真,它会执行代码。前一行代码完全不相关。

phr2 in phr1

这意味着“检查phr2是否在phr1中,然后完全忽略该结果”(因为您对此无效)。

if True:

这意味着“如果True为真:”,它就是。

如果您想测试phr2是否在phr1中,那么您需要让Python做以下事情:if phr2 in phr1:

答案 2 :(得分:0)

试试这个:

phr1= raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2= raw_input("Check if a word/letter exists in the paragraph: ")
if phr2 in phr1:
    print "true"
else:
    print "false"
input("Press enter")

答案 3 :(得分:0)

phr1 = raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2 = raw_input("Check if a word/letter exists in the paragraph: ")
if phr2 in phr1:
    print "true"
else:
    print "false"
raw_input("Press enter")
相关问题