1

I'm trying to get an if statement to work, but for some reasons it doesn't work. It should be very simple.

Assume that the string title = "Today I went to the sea"

My code is:

 if "Today" or "sea" in title:
      print 1

 if "Today" or "sea" not in title:
      print 1

Both specifications result in 1.

Andrew
  • 678
  • 2
  • 9
  • 19

2 Answers2

2

Change your code to this:

if "Today" in title or "sea" in title:
  print 1

(similar for the second piece of code).

How if statements work is they evaluate expressions joined by words like or or and. So your statement was reading like this:

if ("Today") or ("sea" in title):
  print 1

Because "Today" is truthy it was always evaluating to true

winhowes
  • 7,845
  • 5
  • 28
  • 39
1

I guarantee this has been answered somewhere else on SO and you should first check there before asking a new question.

The issue with your code:

if 'Today' or 'sea' in title:

This checks if 'today' is True or if 'sea' is in title, 'today' == type(string) therefore it exists/True, 'sea' in title == True and evaluates to True, if 'today' or 'sea' not in title 'today' is again type(string) and therefore exists/True and 'sea' not in title = False, and again evaluates to True. How to fix this! if 'Today' in title or 'Sea' in title: or below to make it easily modable! Good Luck!

strings_to_compare = ['Today', 'sea', 'etc...']

for i in strings_to_compare:
    if i in title:
        print i
TheLazyScripter
  • 2,541
  • 1
  • 10
  • 19