I'm pretty new to coding but I though I understood how the 'and' operator worked. In the example I provided I would have thought that the 'False' statement would get run not the 'True' statement. Can someone enlighten me on why this is not performing as I expected?
string = 'asdf'
if 'z' and 's' in string:
True
else:
False
The and
keyword is part of an expression and it should be located between two subexpressions. Here you write 'z' and 's' in string
which is interpreted as:
('z') and ('s' in string)
where the first subexpression, 'z'
is more or less evaluated as True
, while the second subexpression is a little more sophisticated (in your example, it is also intereted as True
since 's'
actually is in string
.
Combining both subexpressions yields True
(here).
You certainly wanted to write:
if 'z' in string and 's' in string: