Python Forum
conditionals with boolean logic?? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: conditionals with boolean logic?? (/thread-29924.html)



conditionals with boolean logic?? - ridgerunnersjw - Sep-26-2020

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



RE: conditionals with boolean logic?? - bowlofred - Sep-26-2020

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



RE: conditionals with boolean logic?? - ridgerunnersjw - Sep-26-2020

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



RE: conditionals with boolean logic?? - deanhystad - Sep-26-2020

And since you are testing if a character is in a set of characters you can simplify to if cmd[1] in 'SDR':