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

How to make an IF statement with conditions articulated with OR that stops as soon as the first True condition is reached?

Let’s take an example :
I would like to check if the variable s is a string with length equal or less than 3. I tried the following :

if (not isinstance(s,str)) | (len(s)>3) :
    print("The value of s is not correct : must be a string, with length equal or less than 3")

But it is not correct as the code considers the second condition whatever the result of the first one. For example, with s = 2, the code returns the error :

object of type 'int' has no len()

I would have thought that since the first condition is True, that the rest of the line would not have been considered. How please could I get the code to run until the first True condition is reached?

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

>Solution :

| is a bitwise or. use the keyword or instead.

The or will shortcircuit as you correctly mention in your question, so if s is not a string the second part will not evaluate, preventing the error of trying to apply len to a non-string object.

if not isinstance(s, str) or len(s) > 3:
    print("The value of s is not correct : must be a string, with length equal or less than 3")
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