0

I'm trying to write the following piece of code as part of a bigger script (I don't think the rest of the script is relevant for this particular question, but let me know if it is!):

if A and B in C:
   print("Ok!")

The problem I'm encountering is that the string "Ok" is printed not when both conditions are met (if A and B in C) but also when just one of them happens, that is, "Ok" is printed even when only A is in C but B is not.

Any ideas about what I might be missing?

Thanks!

Ccp2809
  • 19
  • 1

2 Answers2

2

You need to write it like this:

if A in C and B in C:
   # do your thing

What's happening with your code is that even though it sounds amazing in plain English ("if A and B in C") it's actually being evaluated like this:

if (A) and (B in C):
    # your thing

So, when the A object is not None then the first part of the and clause will evaluate to True and the result will depend on whether B is in C or not.

So, you need to use the in operator separately in both sides of and clause as I suggested:

if (A in C) and (B in C):
    # your thing (parenthesis not needed, but explicitly put there for clarity
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
0

You can use all().

if all(x in C for x in [A,B]):
    #do your thing
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44