Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

if statement for strings with the "or" conditional

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading