Skip to content
Advertisement

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?

Advertisement

Answer

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