-2

so no matter what I try with these if staments

if (x,y,z == "no no yes"):
    print ("REBEL ROBOT DETECTED, DESTROY IMMEDIATELY")
if (x,y,z ==  "no yes no"):
    print ("PERFECT SOLDOER DETECTED, REPORT TO US ARMY")
if (x,y,z == "yes no no"):
    print ("LONER ROBOT DETECTED, DESTROY IMMEDIATELY")
if (x,y,z == "no yes yes"):
    print ("THIS ROBOT HURTS HUMANS")
if (x,y,z == "yes yes no"):
    print ("This robot is self destructive")
if (x,y,z == "yes no yes"):
    print ("This robot disobeys orders")
if (x,y,z  == "no no no"):
    print ("YOU HAVE A PHYCOPATH ROBOT, DESTROY AT ALL COSTS")

it just prints all the strings, can someone help me with this

coder
  • 12,832
  • 5
  • 39
  • 53

2 Answers2

3

x, y, z == "no no yes" evaluates to a tuple of three values: x, y, and a Boolean (true/false) value indicating whether z is equal to "no no yes". This being a tuple of non-zero length, it is truthy and so all if conditions pass.

Instead, write (x, y, z) == ("no", "no", "yes") and so on.

kindall
  • 178,883
  • 35
  • 278
  • 309
0
(x,y,z == "no no yes")

This does not do what you expect it to do. First of all, you cannot compare multiple variables at the same time against a single string. You would need to split this up into separate checks.

But why does your code print all strings? This might be a bit surprising if you’re new to Python: The comma in Python separates tuple elements, so x, y, z would be a tuple with three elements, x, y, and z. A tuple would never be equal to a string, so why are all your check successful?

The reason is that the == operator binds stronger than the comma. So what you’re actually writing is something like this: (x, y, (z == "no no yes")). So you compare z (and only z) against the string and put the result inside the tuple as the third value. x and y are taken as they are as the first and second element of the tuple.

And non-empty tuples happen to evaluate to True in Python. So the following will always work:

if (x, y, False):
    print('Works')

As mentioned above, to fix your code, you will have to check each variable against each value separately:

if x == "no no yes" or y == "no no yes" or z == "no no yes":
    print ("REBEL ROBOT DETECTED, DESTROY IMMEDIATELY")

Since you are checking for equality, you can also use the in operator here with the logic reversed:

if "no no yes" in (x, y, z):
    print ("REBEL ROBOT DETECTED, DESTROY IMMEDIATELY")

You can learn more about this (just in the other direction) from the following question: How do I test one variable against multiple values?


And as I just realized from kindall’s answer, you probably want to split up those strings into separate strings which you check against each variable separately:

if x == "no" and y == "no" and z == "yes":
    print ("REBEL ROBOT DETECTED, DESTROY IMMEDIATELY")
poke
  • 369,085
  • 72
  • 557
  • 602