3

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
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
Shaky
  • 33
  • 4

2 Answers2

4

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:
Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
1

Just to build up on the answer above, to get the correct output that you expect from the if statement you need to specify if "z" in string and "s" in string in order for python to compute the correct meaning of what you intend it to do.

 string = 'asdf'

 if 'z' in string and 's' in string:
     print("True") 
 else:
     print("False")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Σ baryon
  • 236
  • 1
  • 11