Jawad
Jawad

Reputation: 196

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

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.

Upvotes: 3

Views: 4823

Answers (6)

Noureddine
Noureddine

Reputation: 190

I think that a good option will be to create a list of condition and to check you the item of your list in a loop.

cond=[True, False, True, 5>10,True,False,1==1,3<-1,'a' == 'a'] # assume this is your list
for i in range(len(cond)):
    if cond[i]:
         print(i) # will return the Item adress correspending to True

Upvotes: 0

albert
albert

Reputation: 8593

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.

Upvotes: 2

Thomas Weller
Thomas Weller

Reputation: 59303

For hard coded conditions like in your example, a good IDE should have an indicator and propose that you simplify the condition.

If you have variables in the condition, this will of course not be possible. In such a case, I would refactor the code and introduce additional semantics by using a variable name for the individual boolean parts of the condition.

In PyCharm, the shortcut Ctrl+Alt+V extracts a condition into a variable.

A more realistic example (before):

class Customer:
    def __init__(self, age, totalsales, paymenttype):
        self.age = age
        self.totalsales = totalsales
        self.paymenttype = paymenttype


c = Customer(21, 3000, 2)
if c.age > 18 or c.totalsales > 5000 or c.paymenttype == 1:
    print('Hello World!')

After:

c = Customer(21, 3000, 2)
is_adult = c.age > 18
is_vip = c.totalsales > 5000
is_payed_in_advance = c.paymenttype == 1
if is_adult or is_vip or is_payed_in_advance:
    print('Hello World!')

When you reach the if-statement, you can inspect each part of the condition in the debugger.

Mouse hover in debugger

Note that this may change the behavior of your program, because with the changed code, each condition is evaluated, whereas short circuiting may have been applied before. However, I never ran into a situation where this caused a problem.

Upvotes: 1

Roy Cohen
Roy Cohen

Reputation: 1570

I don't know why you would ever want to use this but okay...
You need to return a value which has a special __bool__ so I would define a class. The class will have one instance variable, index to indecate the first True condition, or None if there's no True condition.
The __bool__ function then only needs to check whether index is None:

class Any:
    def __init__(self, *conditions):
        self.index = None
        for i, cond in enumerate(conditions):
            if cond:
                self.index = i
                break
    def __bool__(self):
        return self.index is not None

Example usage:

if o := Any(0 > 1, 9 < 10, 2 == 1):
       print(f'The index of the first True condition is {o.index}')

Upvotes: 1

h4z3
h4z3

Reputation: 5468

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.

Upvotes: 3

Jakub Klimek
Jakub Klimek

Reputation: 593

You can do: print(0 > 1) print(9 < 10) It will print true or false

Upvotes: -2

Related Questions