Python真/假和在

kir*_*485 0 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")
Run Code Online (Sandbox Code Playgroud)

当我运行代码时:

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
Run Code Online (Sandbox Code Playgroud)

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

nbr*_*oks 6

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

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

如果您想使用原始的if/else检查(优点是您的输出消息可能比"True"/"False"更具创造性),您必须修改如下代码:

if phr2 in phr1:
    print "true"
else:
    print "false"
input("Press enter")
Run Code Online (Sandbox Code Playgroud)