简体   繁体   中英

Python true/false and in

I am trying to print out true if there is such letter/word and false if there isn't, but no matter what I type, it's always true.

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")

When I run the code:

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

How is this possible, g dosen't exist, why does it say it does?

Checking if True will always pass, because the boolean expression being evaluated is simply True . Change your entire if/else to just be print (phr2 in phr1)

This will print "True" in the event that the second phrase is located in the first, and "False" otherwise. To get it to be lowercase (for whatever reason), you can use .lower() as detailed in the comment below.

In the event that you wanted to use your original if/else check (the advantage being that you can be more creative with your output message than just "True"/"False"), you would have to modify the code like this:

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

means exactly what it says: it executes the code if <something> is true. The previous line of code is completely irrelevant.

phr2 in phr1

This means "check if phr2 is in phr1 , and then ignore the result completely" (because you do nothing with it).

if True:

This means "if True is true:", which it is.

If you want to test whether phr2 is in phr1 , then that's what you have to ask Python to do: if phr2 in phr1: .

Try this:

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")
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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM