Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to find which condition is true in if statement?

Tags:

python

I have an if statement has many conditions, for example:

if(0 > 1 or 9 < 10 or 2 == 1):
       print('Hello World!')

so i wanna know which is the right condition that let the if statement continues to print hello world? "without using another if statement or elif"

In my code I have lots of conditions so it's difficult to use a lot of else statements to just know what is the right condition was.

like image 858
Jawad Avatar asked Mar 25 '26 15:03

Jawad


2 Answers

In general, it's impossible - each condition is evaluated, we can only get a result.

However, if instead of ors, we have them stored* in a list like this:

conditions = [0>1, 9<10, 2==1] # it gets evaluated here!*
if any(conditions):
   print('Hello World!')

we could get the index of the True element by doing conditions.index(True).

[*] But be aware that conditions doesn't consist of pure conditions but of Trues and Falses because they got evaluated. That's why I said it's impossible to get the condition itself.

like image 106
h4z3 Avatar answered Mar 27 '26 04:03

h4z3


Chained boolean expressions will be evaluated from left to right. If one of the chained statements is evaluated as being True, the remaining conditions will not be checked.

Assuming second_condition is fulfilled and hence will be evaluated as True, the following pseudo-code snipped would evaluate first_condition as False and then enter the if statement because of second_condition being True. However, third_condition will not be checked as another check before was already evaluated as True and thus the complete statement will become True:

if (first_condition or second_condition or third_condition):
    pass

Knowing which condition was evaluated as True is not possible with the approach shown above. Therefore, I would suggest rewriting your checks as follows:

def handle_true(condition):
    pass


if first_condition:
    handle_true('first')
elif second_condition:
    handle_true('second')
elif third_condition:
    handle_true('third')
else:
    pass

The if/elif will be evaluated in the same way as your chained or expression. If one condition fails, the next will be checked. If one of the given conditions is evaluated as True the branch will be entered. If none of the given conditions is fulfilled, the default else will be entered.

Combining this with the small helper function handle_true() should do the trick and not only provide a way to check which condition fired, but also provide a single place for handling any True condition.

like image 23
albert Avatar answered Mar 27 '26 04:03

albert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!