-1

I've this code:

url='http://mybeautifulurl.com'

('h' or 'f') in url[0:4] #This is True
('f' or 'h') in url[0:4] #This is False

I'm just trying to understand why the 'or' operator seems to evaluate just the first condition.

cinv3
  • 101
  • 1
  • 6
  • 2
    Python is not English. Your condition must be `'h' in ... or 'f' in ...`. (Or some alternative check which allows you to express that in one go.) – deceze Jan 25 '18 at 10:29
  • 1
    hint: try running content inside the parenthesis by itself in the interpreter. maybe experiment with empty strings and 'and' operator as well. – LazyLeopard Jan 25 '18 at 10:34
  • Question has been marked has duplicated and it is; it has nothing to do with 'in' statement as even the following code is evaluated false: 'h' == ('f' or 'h') – cinv3 Jan 25 '18 at 11:42

1 Answers1

4

This or returns the first element if it evaluates to true (as a bool) and the second one otherwise... it's is usually applied to set default values.

This way, 'h' or 'f' is simply 'h' and 'f' or 'h' is simply 'f'.

You can achieve what you want with something like:

any(x in url[:4] for x in ['h', 'f'])
grovina
  • 2,999
  • 19
  • 25
  • 1
    If you are trying to generalize this you may want to look into more efficient operations, e.g.: `not set(['h', 'f', 'a', 'b', 'c', ..., 'awefw']).isdisjoint(url[:400]) – Cireo Jan 25 '18 at 11:25
  • Even the following code is evaluated false: `'h' == ('f' or 'h')`. I voted for below answer -but score didn't increment as question is duplicated. Other very useful answer can be found at suggested [link](https://stackoverflow.com/questions/13870378/python-or-operator-weird-behavior) or even [link2](https://stackoverflow.com/questions/4531794/whats-the-logical-value-of-string-in-python). – cinv3 Jan 25 '18 at 12:26
  • @cinv3 `'h' == ('h' or 'f')` evaluates to true (note the order between `'h'` and `'f'`). – grovina Jan 25 '18 at 13:35