Python Forum

Full Version: conditionals with boolean logic??
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to Python....
Can someone tell me why code only responds to the first boolean characater and not the rest?

cmd = '$D00\r'
if cmd[1] == ("S" or "D" or "R"):
Your equality test isn't doing what you think. The portion on the right is set of OR operators. They will return the first one that is truthy.

>>> ("S" or "D" or "R")
'S'
So you are only checking if it is "S" (which it isn't). You probably want to use the in operation.

>>> "S" in ["S", "D", "R"]
True
>>> "D" in ["S", "D", "R"]
True
>>> "X" in ["S", "D", "R"]
False
I understand what you are saying that the () will eval and get precedence. Just the existence of the tuple yields TRUE. Is there a way like C where I can just use the element in question of the string (cmd[1]) and search in one line of code? (like above)...I have a bunch of commands and don't want to do a line of code for each especially when many times the commands are identical in response size. For instance D, S and R will all return 6 bytes....X, T, U, A, F, G may all return 8 bytes....Seems foolish to write a line of code for each command letter???

Thanks a bunch for the help!

This seems to work, although it is rather bloated looking

if ((cmd[1] == "S") or (cmd[1] == "D") or (cmd[1] == "R")):

I now see what you were saying....thank you!

if (cmd[1] in ("S", "D", "R")):
And since you are testing if a character is in a set of characters you can simplify to if cmd[1] in 'SDR':