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
4
  • 1
    You want 'z' in string and 's' in string Commented Jan 1, 2020 at 21:03
  • 1
    If you have more than two characters, use a list comprehension: if all(c in string for c in 'zs'): Commented Jan 1, 2020 at 21:15
  • @Boris I would even do that for two characters to keep the code dry Commented Jan 1, 2020 at 21:16
  • Related: How to test multiple variables against a value? Commented Jan 1, 2020 at 21:22

2 Answers 2

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:
Sign up to request clarification or add additional context in comments.

Comments

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")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.