-3

I have a variable called band with four possible options: broad, half1, half2, and control.

My code or Python should perform different computations depending on the variable I choose. As a simple demonstration, I simply print text messages in the example below.

Question: Why does Python execute the if (instead of elif) conditional, even when I use "half2" for the variable band? Python seems to ignore the elif condition and acts like the if condition was true.

band = "half2" # broad, half1, half2, control

if band == "broad" or "half1" or "control":
    print("broad or half1 or control")
elif band == "half2":
    print("half2")
Philipp
  • 335
  • 2
  • 4
  • 12
  • 1
    `and` and `or` separate conditions that are `True` or `False`. `"half1"` is not a condition. It's a string literal. As such, it's "Truthy". Instead `if band == "broad" or band == "half1" or band = "control"` or, `if band in ["broad","half1", "control"]` Check the marked duplicate answer for more in-depth explanation around this topic. – JNevill Aug 22 '23 at 15:04
  • The `if` condition *is* true. Python tests are not written like English is spoken. – jarmod Aug 22 '23 at 15:05

1 Answers1

2

The issue in your code lies in the way you've structured the if statement condition. When you write:

if band == "broad" or "half1" or "control":

Python interprets it as:

  1. Check if band is equal to "broad".
  2. If the first condition is false, evaluate the truthiness of "half1".
  3. Since non-empty strings are considered truthy, the condition becomes True.

This is not what you intend. You should compare band with each option separately. To fix this, you need to rewrite your condition like this:

if band == "broad" or band == "half1" or band == "control":

Or you can use the in keyword to simplify the condition:

if band in ["broad", "half1", "control"]:

So, your corrected code should look like:

band = "half2"  # broad, half1, half2, control

if band == "broad" or band == "half1" or band == "control":
    print("broad or half1 or control")
elif band == "half2":
    print("half2")

With this corrected code, Python will now execute the elif block when the band variable is set to "half2".

Nicolas Jit
  • 66
  • 1
  • 5