Reputation: 377
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?
Upvotes: 0
Views: 1703
Reputation: 61643
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:
.
Upvotes: 1
Reputation: 18233
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")
Upvotes: 6
Reputation: 7596
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")
Upvotes: 0
Reputation: 488
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")
Upvotes: 0