Python Forum
conditionals with boolean logic??
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
conditionals with boolean logic??
#1
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"):
Reply
#2
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
Reply
#3
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")):
Reply
#4
And since you are testing if a character is in a set of characters you can simplify to if cmd[1] in 'SDR':
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Doubt about conditionals in Python. Carmazum 6 1,596 Apr-01-2023, 12:01 AM
Last Post: Carmazum
  conditionals based on data frame mbrown009 1 893 Aug-12-2022, 08:18 AM
Last Post: Larz60+
  Efficiency with regard to nested conditionals or and statements Mark17 13 3,154 May-06-2022, 05:16 PM
Last Post: Mark17
  Nested conditionals vs conditionals connected by operators dboxall123 8 3,044 Feb-18-2022, 09:34 PM
Last Post: dboxall123
  Nested Conditionals shen123 3 2,623 Jul-28-2021, 08:24 AM
Last Post: Yoriz
  Help please: WHILE LOOPS with BOOLEAN LOGIC rbulmerstlouis 4 2,262 Jun-20-2021, 02:32 PM
Last Post: rbulmerstlouis
  Invalid syntax using conditionals if - else jperezqu 1 2,331 Jan-13-2021, 07:32 PM
Last Post: bowlofred
  two conditionals with intermediate code Skaperen 5 2,765 Jul-12-2020, 07:18 PM
Last Post: Skaperen
  Conditionals, while loops, continue, break (PyBite 102) Drone4four 2 2,973 Jun-04-2020, 12:08 PM
Last Post: Drone4four
  Nested Conditionals HELP absolum 4 2,776 Jul-17-2019, 06:40 PM
Last Post: absolum

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020